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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
256741b442524fa1904d7f954f22a9152b7b0f5e
|
69d4931b605e11ca61881fc4f66db50a0a875e39
|
/src/algebra/module/basic.lean
|
420af75d6a8f2f3f32a6195eb9cdb0b006af2758
|
[
"Apache-2.0"
] |
permissive
|
abentkamp/mathlib
|
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
|
5360e476391508e092b5a1e5210bd0ed22dc0755
|
refs/heads/master
| 1,682,382,954,948
| 1,622,106,077,000
| 1,622,106,077,000
| 149,285,665
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 19,538
|
lean
|
/-
Copyright (c) 2015 Nathaniel Thomas. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro
-/
import algebra.big_operators.basic
import algebra.group.hom
import group_theory.group_action.group
import algebra.smul_with_zero
/-!
# Modules over a ring
In this file we define
* `module R M` : an additive commutative monoid `M` is a `module` over a
`semiring R` if for `r : R` and `x : M` their "scalar multiplication `r • x : M` is defined, and
the operation `•` satisfies some natural associativity and distributivity axioms similar to those
on a ring.
## Implementation notes
In typical mathematical usage, our definition of `module` corresponds to "semimodule", and the
word "module" is reserved for `module R M` where `R` is a `ring` and `M` an `add_comm_group`.
If `R` is a `field` and `M` an `add_comm_group`, `M` would be called an `R`-vector space.
Since those assumptions can be made by changing the typeclasses applied to `R` and `M`,
without changing the axioms in `module`, mathlib calls everything a `module`.
In older versions of mathlib, we had separate `semimodule` and `vector_space` abbreviations.
This caused inference issues in some cases, while not providing any real advantages, so we decided
to use a canonical `module` typeclass throughout.
## Tags
semimodule, module, vector space
-/
open function
open_locale big_operators
universes u u' v w x y z
variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y}
{ι : Type z}
/-- A module is a generalization of vector spaces to a scalar semiring.
It consists of a scalar semiring `R` and an additive monoid of "vectors" `M`,
connected by a "scalar multiplication" operation `r • x : M`
(where `r : R` and `x : M`) with some natural associativity and
distributivity axioms similar to those on a ring. -/
@[protect_proj] class module (R : Type u) (M : Type v) [semiring R]
[add_comm_monoid M] extends distrib_mul_action R M :=
(add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x)
(zero_smul : ∀x : M, (0 : R) • x = 0)
section add_comm_monoid
variables [semiring R] [add_comm_monoid M] [module R M] (r s : R) (x y : M)
/-- A module over a semiring automatically inherits a `mul_action_with_zero` structure. -/
@[priority 100] -- see Note [lower instance priority]
instance module.to_mul_action_with_zero :
mul_action_with_zero R M :=
{ smul_zero := smul_zero,
zero_smul := module.zero_smul,
..(infer_instance : mul_action R M) }
instance add_comm_monoid.nat_module : module ℕ M :=
{ one_smul := one_nsmul,
mul_smul := λ m n a, mul_nsmul a m n,
smul_add := λ n a b, nsmul_add a b n,
smul_zero := nsmul_zero,
zero_smul := zero_nsmul,
add_smul := λ r s x, add_nsmul x r s }
theorem add_smul : (r + s) • x = r • x + s • x := module.add_smul r s x
variables (R)
theorem two_smul : (2 : R) • x = x + x := by rw [bit0, add_smul, one_smul]
theorem two_smul' : (2 : R) • x = bit0 x := two_smul R x
/-- Pullback a `module` structure along an injective additive monoid homomorphism. -/
protected def function.injective.module [add_comm_monoid M₂] [has_scalar R M₂] (f : M₂ →+ M)
(hf : injective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) :
module R M₂ :=
{ smul := (•),
add_smul := λ c₁ c₂ x, hf $ by simp only [smul, f.map_add, add_smul],
zero_smul := λ x, hf $ by simp only [smul, zero_smul, f.map_zero],
.. hf.distrib_mul_action f smul }
/-- Pushforward a `module` structure along a surjective additive monoid homomorphism. -/
protected def function.surjective.module [add_comm_monoid M₂] [has_scalar R M₂] (f : M →+ M₂)
(hf : surjective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) :
module R M₂ :=
{ smul := (•),
add_smul := λ c₁ c₂ x, by { rcases hf x with ⟨x, rfl⟩,
simp only [add_smul, ← smul, ← f.map_add] },
zero_smul := λ x, by { rcases hf x with ⟨x, rfl⟩, simp only [← f.map_zero, ← smul, zero_smul] },
.. hf.distrib_mul_action f smul }
variables {R} (M)
/-- Compose a `module` with a `ring_hom`, with action `f s • m` -/
def module.comp_hom [semiring S] (f : S →+* R) :
module S M :=
{ smul := (•) ∘ f,
add_smul := λ r s x, by simp [add_smul],
.. mul_action_with_zero.comp_hom M f.to_monoid_with_zero_hom,
.. distrib_mul_action.comp_hom M (f : S →* R) }
variables (R) (M)
/-- `(•)` as an `add_monoid_hom`. -/
def smul_add_hom : R →+ M →+ M :=
{ to_fun := const_smul_hom M,
map_zero' := add_monoid_hom.ext $ λ r, by simp,
map_add' := λ x y, add_monoid_hom.ext $ λ r, by simp [add_smul] }
variables {R M}
@[simp] lemma smul_add_hom_apply (r : R) (x : M) :
smul_add_hom R M r x = r • x := rfl
@[simp] lemma smul_add_hom_one {R M : Type*} [semiring R] [add_comm_monoid M] [module R M] :
smul_add_hom R M 1 = add_monoid_hom.id _ :=
const_smul_hom_one
lemma module.eq_zero_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : x = 0 :=
by rw [←one_smul R x, ←zero_eq_one, zero_smul]
lemma list.sum_smul {l : list R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum :=
((smul_add_hom R M).flip x).map_list_sum l
lemma multiset.sum_smul {l : multiset R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum :=
((smul_add_hom R M).flip x).map_multiset_sum l
lemma finset.sum_smul {f : ι → R} {s : finset ι} {x : M} :
(∑ i in s, f i) • x = (∑ i in s, (f i) • x) :=
((smul_add_hom R M).flip x).map_sum f s
end add_comm_monoid
variables (R)
/-- An `add_comm_monoid` that is a `module` over a `ring` carries a natural `add_comm_group`
structure. -/
def module.add_comm_monoid_to_add_comm_group [ring R] [add_comm_monoid M] [module R M] :
add_comm_group M :=
{ neg := λ a, (-1 : R) • a,
add_left_neg := λ a, show (-1 : R) • a + a = 0, by {
nth_rewrite 1 ← one_smul _ a,
rw [← add_smul, add_left_neg, zero_smul] },
..(infer_instance : add_comm_monoid M), }
variables {R}
section add_comm_group
variables (R M) [semiring R] [add_comm_group M]
instance add_comm_group.int_module : module ℤ M :=
{ one_smul := one_gsmul,
mul_smul := λ m n a, mul_gsmul a m n,
smul_add := λ n a b, gsmul_add a b n,
smul_zero := gsmul_zero,
zero_smul := zero_gsmul,
add_smul := λ r s x, add_gsmul x r s }
/-- A structure containing most informations as in a module, except the fields `zero_smul`
and `smul_zero`. As these fields can be deduced from the other ones when `M` is an `add_comm_group`,
this provides a way to construct a module structure by checking less properties, in
`module.of_core`. -/
@[nolint has_inhabited_instance]
structure module.core extends has_scalar R M :=
(smul_add : ∀(r : R) (x y : M), r • (x + y) = r • x + r • y)
(add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x)
(mul_smul : ∀(r s : R) (x : M), (r * s) • x = r • s • x)
(one_smul : ∀x : M, (1 : R) • x = x)
variables {R M}
/-- Define `module` without proving `zero_smul` and `smul_zero` by using an auxiliary
structure `module.core`, when the underlying space is an `add_comm_group`. -/
def module.of_core (H : module.core R M) : module R M :=
by letI := H.to_has_scalar; exact
{ zero_smul := λ x, (add_monoid_hom.mk' (λ r : R, r • x) (λ r s, H.add_smul r s x)).map_zero,
smul_zero := λ r, (add_monoid_hom.mk' ((•) r) (H.smul_add r)).map_zero,
..H }
end add_comm_group
/--
To prove two module structures on a fixed `add_comm_monoid` agree,
it suffices to check the scalar multiplications agree.
-/
-- We'll later use this to show `module ℕ M` and `module ℤ M` are subsingletons.
@[ext]
lemma module_ext {R : Type*} [semiring R] {M : Type*} [add_comm_monoid M] (P Q : module R M)
(w : ∀ (r : R) (m : M), by { haveI := P, exact r • m } = by { haveI := Q, exact r • m }) :
P = Q :=
begin
unfreezingI { rcases P with ⟨⟨⟨⟨P⟩⟩⟩⟩, rcases Q with ⟨⟨⟨⟨Q⟩⟩⟩⟩ },
congr,
funext r m,
exact w r m,
all_goals { apply proof_irrel_heq },
end
section module
variables [ring R] [add_comm_group M] [module R M] (r s : R) (x y : M)
@[simp] theorem neg_smul : -r • x = - (r • x) :=
eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul])
@[simp] theorem units.neg_smul (u : units R) (x : M) : -u • x = - (u • x) :=
by rw [units.smul_def, units.coe_neg, neg_smul, units.smul_def]
variables (R)
theorem neg_one_smul (x : M) : (-1 : R) • x = -x := by simp
variables {R}
theorem sub_smul (r s : R) (y : M) : (r - s) • y = r • y - s • y :=
by simp [add_smul, sub_eq_add_neg]
end module
/-- A module over a `subsingleton` semiring is a `subsingleton`. We cannot register this
as an instance because Lean has no way to guess `R`. -/
protected
theorem module.subsingleton (R M : Type*) [semiring R] [subsingleton R] [add_comm_monoid M]
[module R M] :
subsingleton M :=
⟨λ x y, by rw [← one_smul R x, ← one_smul R y, subsingleton.elim (1:R) 0, zero_smul, zero_smul]⟩
@[priority 910] -- see Note [lower instance priority]
instance semiring.to_module [semiring R] : module R R :=
{ smul_add := mul_add,
add_smul := add_mul,
zero_smul := zero_mul,
smul_zero := mul_zero }
/-- A ring homomorphism `f : R →+* M` defines a module structure by `r • x = f r * x`. -/
def ring_hom.to_module [semiring R] [semiring S] (f : R →+* S) : module R S :=
{ smul := λ r x, f r * x,
smul_add := λ r x y, by unfold has_scalar.smul; rw [mul_add],
add_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_add, add_mul],
mul_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_mul, mul_assoc],
one_smul := λ x, show f 1 * x = _, by rw [f.map_one, one_mul],
zero_smul := λ x, show f 0 * x = 0, by rw [f.map_zero, zero_mul],
smul_zero := λ r, mul_zero (f r) }
section add_comm_monoid
variables [semiring R] [add_comm_monoid M] [module R M]
section
variables (R)
/-- `nsmul` is equal to any other module structure via a cast. -/
lemma nsmul_eq_smul_cast (n : ℕ) (b : M) :
n • b = (n : R) • b :=
begin
induction n with n ih,
{ rw [nat.cast_zero, zero_smul, zero_smul] },
{ rw [nat.succ_eq_add_one, nat.cast_succ, add_smul, add_smul, one_smul, ih, one_smul], }
end
end
/-- Convert back any exotic `ℕ`-smul to the canonical instance. This should not be needed since in
mathlib all `add_comm_monoid`s should normally have exactly one `ℕ`-module structure by design.
-/
lemma nat_smul_eq_nsmul (h : module ℕ M) (n : ℕ) (x : M) :
@has_scalar.smul ℕ M h.to_has_scalar n x = n • x :=
by rw [nsmul_eq_smul_cast ℕ n x, nat.cast_id]
/-- All `ℕ`-module structures are equal. Not an instance since in mathlib all `add_comm_monoid`
should normally have exactly one `ℕ`-module structure by design. -/
def add_comm_monoid.nat_module.unique : unique (module ℕ M) :=
{ default := by apply_instance,
uniq := λ P, module_ext P _ $ λ n, nat_smul_eq_nsmul P n }
instance add_comm_monoid.nat_is_scalar_tower :
is_scalar_tower ℕ R M :=
{ smul_assoc := λ n x y, nat.rec_on n
(by simp only [zero_smul])
(λ n ih, by simp only [nat.succ_eq_add_one, add_smul, one_smul, ih]) }
instance add_comm_monoid.nat_smul_comm_class : smul_comm_class ℕ R M :=
{ smul_comm := λ n r m, nat.rec_on n
(by simp only [zero_smul, smul_zero])
(λ n ih, by simp only [nat.succ_eq_add_one, add_smul, one_smul, ←ih, smul_add]) }
-- `smul_comm_class.symm` is not registered as an instance, as it would cause a loop
instance add_comm_monoid.nat_smul_comm_class' : smul_comm_class R ℕ M :=
smul_comm_class.symm _ _ _
end add_comm_monoid
section add_comm_group
variables [semiring S] [ring R] [add_comm_group M] [module S M] [module R M]
section
variables (R)
/-- `gsmul` is equal to any other module structure via a cast. -/
lemma gsmul_eq_smul_cast (n : ℤ) (b : M) : n • b = (n : R) • b :=
begin
induction n using int.induction_on with p hp n hn,
{ rw [int.cast_zero, zero_smul, zero_smul] },
{ rw [int.cast_add, int.cast_one, add_smul, add_smul, one_smul, one_smul, hp] },
{ rw [int.cast_sub, int.cast_one, sub_smul, sub_smul, one_smul, one_smul, hn] },
end
end
/-- Convert back any exotic `ℤ`-smul to the canonical instance. This should not be needed since in
mathlib all `add_comm_group`s should normally have exactly one `ℤ`-module structure by design. -/
lemma int_smul_eq_gsmul (h : module ℤ M) (n : ℤ) (x : M) :
@has_scalar.smul ℤ M h.to_has_scalar n x = n • x :=
by rw [gsmul_eq_smul_cast ℤ n x, int.cast_id]
/-- All `ℤ`-module structures are equal. Not an instance since in mathlib all `add_comm_group`
should normally have exactly one `ℤ`-module structure by design. -/
def add_comm_group.int_module.unique : unique (module ℤ M) :=
{ default := by apply_instance,
uniq := λ P, module_ext P _ $ λ n, int_smul_eq_gsmul P n }
instance add_comm_group.int_is_scalar_tower : is_scalar_tower ℤ R M :=
{ smul_assoc := λ n x y, int.induction_on n
(by simp only [zero_smul])
(λ n ih, by simp only [one_smul, add_smul, ih])
(λ n ih, by simp only [one_smul, sub_smul, ih]) }
instance add_comm_group.int_smul_comm_class : smul_comm_class ℤ S M :=
{ smul_comm := λ n x y, int.induction_on n
(by simp only [zero_smul, smul_zero])
(λ n ih, by simp only [one_smul, add_smul, smul_add, ih])
(λ n ih, by simp only [one_smul, sub_smul, smul_sub, ih]) }
-- `smul_comm_class.symm` is not registered as an instance, as it would cause a loop
instance add_comm_group.int_smul_comm_class' : smul_comm_class S ℤ M :=
smul_comm_class.symm _ _ _
end add_comm_group
namespace add_monoid_hom
lemma map_nat_module_smul [add_comm_monoid M] [add_comm_monoid M₂]
(f : M →+ M₂) (x : ℕ) (a : M) : f (x • a) = x • f a :=
by simp only [f.map_nsmul]
lemma map_int_module_smul [add_comm_group M] [add_comm_group M₂]
(f : M →+ M₂) (x : ℤ) (a : M) : f (x • a) = x • f a :=
by simp only [f.map_gsmul]
lemma map_int_cast_smul
[ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂]
(f : M →+ M₂) (x : ℤ) (a : M) : f ((x : R) • a) = (x : R) • f a :=
by simp only [←gsmul_eq_smul_cast, f.map_gsmul]
lemma map_nat_cast_smul
[semiring R] [add_comm_monoid M] [add_comm_monoid M₂]
[module R M] [module R M₂] (f : M →+ M₂) (x : ℕ) (a : M) :
f ((x : R) • a) = (x : R) • f a :=
by simp only [←nsmul_eq_smul_cast, f.map_nsmul]
lemma map_rat_cast_smul {R : Type*} [division_ring R] [char_zero R]
{E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F]
(f : E →+ F) (c : ℚ) (x : E) :
f ((c : R) • x) = (c : R) • f x :=
begin
have : ∀ (x : E) (n : ℕ), 0 < n → f (((n⁻¹ : ℚ) : R) • x) = ((n⁻¹ : ℚ) : R) • f x,
{ intros x n hn,
replace hn : (n : R) ≠ 0 := nat.cast_ne_zero.2 (ne_of_gt hn),
conv_rhs { congr, skip, rw [← one_smul R x, ← mul_inv_cancel hn, mul_smul] },
rw [f.map_nat_cast_smul, smul_smul, rat.cast_inv, rat.cast_coe_nat,
inv_mul_cancel hn, one_smul] },
refine c.num_denom_cases_on (λ m n hn hmn, _),
rw [rat.mk_eq_div, div_eq_mul_inv, rat.cast_mul, int.cast_coe_nat, mul_smul, mul_smul,
rat.cast_coe_int, f.map_int_cast_smul, this _ n hn]
end
lemma map_rat_module_smul {E : Type*} [add_comm_group E] [module ℚ E]
{F : Type*} [add_comm_group F] [module ℚ F] (f : E →+ F) (c : ℚ) (x : E) :
f (c • x) = c • f x :=
rat.cast_id c ▸ f.map_rat_cast_smul c x
end add_monoid_hom
section no_zero_smul_divisors
/-! ### `no_zero_smul_divisors`
This section defines the `no_zero_smul_divisors` class, and includes some tests
for the vanishing of elements (especially in modules over division rings).
-/
/-- `no_zero_smul_divisors R M` states that a scalar multiple is `0` only if either argument is `0`.
This a version of saying that `M` is torsion free, without assuming `R` is zero-divisor free.
The main application of `no_zero_smul_divisors R M`, when `M` is a module,
is the result `smul_eq_zero`: a scalar multiple is `0` iff either argument is `0`.
It is a generalization of the `no_zero_divisors` class to heterogeneous multiplication.
-/
class no_zero_smul_divisors (R M : Type*) [has_zero R] [has_zero M] [has_scalar R M] : Prop :=
(eq_zero_or_eq_zero_of_smul_eq_zero : ∀ {c : R} {x : M}, c • x = 0 → c = 0 ∨ x = 0)
export no_zero_smul_divisors (eq_zero_or_eq_zero_of_smul_eq_zero)
section module
variables [semiring R] [add_comm_monoid M] [module R M]
instance no_zero_smul_divisors.of_no_zero_divisors [no_zero_divisors R] :
no_zero_smul_divisors R R :=
⟨λ c x, no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero⟩
@[simp]
theorem smul_eq_zero [no_zero_smul_divisors R M] {c : R} {x : M} :
c • x = 0 ↔ c = 0 ∨ x = 0 :=
⟨eq_zero_or_eq_zero_of_smul_eq_zero,
λ h, h.elim (λ h, h.symm ▸ zero_smul R x) (λ h, h.symm ▸ smul_zero c)⟩
theorem smul_ne_zero [no_zero_smul_divisors R M] {c : R} {x : M} :
c • x ≠ 0 ↔ c ≠ 0 ∧ x ≠ 0 :=
by simp only [ne.def, smul_eq_zero, not_or_distrib]
section nat
variables (R) (M) [no_zero_smul_divisors R M] [char_zero R]
include R
lemma nat.no_zero_smul_divisors : no_zero_smul_divisors ℕ M :=
⟨by { intros c x, rw [nsmul_eq_smul_cast R, smul_eq_zero], simp }⟩
variables {M}
lemma eq_zero_of_smul_two_eq_zero {v : M} (hv : 2 • v = 0) : v = 0 :=
by haveI := nat.no_zero_smul_divisors R M;
exact (smul_eq_zero.mp hv).resolve_left (by norm_num)
end nat
end module
section add_comm_group -- `R` can still be a semiring here
variables [semiring R] [add_comm_group M] [module R M]
section smul_injective
variables (M)
lemma smul_left_injective [no_zero_smul_divisors R M] {c : R} (hc : c ≠ 0) :
function.injective (λ (x : M), c • x) :=
λ x y h, sub_eq_zero.mp ((smul_eq_zero.mp
(calc c • (x - y) = c • x - c • y : smul_sub c x y
... = 0 : sub_eq_zero.mpr h)).resolve_left hc)
end smul_injective
section nat
variables (R) [no_zero_smul_divisors R M] [char_zero R]
include R
lemma eq_zero_of_eq_neg {v : M} (hv : v = - v) : v = 0 :=
begin
haveI := nat.no_zero_smul_divisors R M,
refine eq_zero_of_smul_two_eq_zero R _,
rw two_smul,
exact add_eq_zero_iff_eq_neg.mpr hv
end
end nat
end add_comm_group
section module
variables [ring R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M]
section smul_injective
variables (R)
lemma smul_right_injective {x : M} (hx : x ≠ 0) :
function.injective (λ (c : R), c • x) :=
λ c d h, sub_eq_zero.mp ((smul_eq_zero.mp
(calc (c - d) • x = c • x - d • x : sub_smul c d x
... = 0 : sub_eq_zero.mpr h)).resolve_right hx)
end smul_injective
section nat
variables [char_zero R]
lemma ne_neg_of_ne_zero [no_zero_divisors R] {v : R} (hv : v ≠ 0) : v ≠ -v :=
λ h, hv (eq_zero_of_eq_neg R h)
end nat
end module
section division_ring
variables [division_ring R] [add_comm_group M] [module R M]
@[priority 100] -- see note [lower instance priority]
instance no_zero_smul_divisors.of_division_ring : no_zero_smul_divisors R M :=
⟨λ c x h, or_iff_not_imp_left.2 $ λ hc, (smul_eq_zero_iff_eq' hc).1 h⟩
end division_ring
end no_zero_smul_divisors
@[simp] lemma nat.smul_one_eq_coe {R : Type*} [semiring R] (m : ℕ) :
m • (1 : R) = ↑m :=
by rw [nsmul_eq_mul, mul_one]
@[simp] lemma int.smul_one_eq_coe {R : Type*} [ring R] (m : ℤ) :
m • (1 : R) = ↑m :=
by rw [gsmul_eq_mul, mul_one]
|
ea8390c7adb9ca681bac341ad61a57137814039f
|
cf39355caa609c0f33405126beee2739aa3cb77e
|
/tests/lean/interactive/complete.lean
|
a45eedff1966a409fbdb55fe19597867b48fb5bf
|
[
"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
| 498
|
lean
|
prelude
inductive foo
example := foo
--^ "command": "complete"
-- should not complete empty declaration completion
example := foo
--^ "command": "complete"
@[reducible]
--^ "command": "complete", "skip_completions": true
example := foo
set_option trace.simplify true
--^ "command": "complete", "skip_completions": true
#print foo
--^ "command": "complete", "skip_completions": true
section foo
end foo
--^ "command": "complete", "skip_completions": true
|
06c2a3b5aaebbfaca2488e20acbf64141f76e792
|
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
|
/src/topology/basic.lean
|
5273b659085013740ae19dec70b6a9624a3c0788
|
[
"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
| 68,830
|
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, Jeremy Avigad
-/
import order.filter.ultrafilter
import order.filter.partial
import algebra.support
/-!
# Basic theory of topological spaces.
The main definition is the type class `topological space α` which endows a type `α` with a topology.
Then `set α` gets predicates `is_open`, `is_closed` and functions `interior`, `closure` and
`frontier`. Each point `x` of `α` gets a neighborhood filter `𝓝 x`. A filter `F` on `α` has
`x` as a cluster point if `cluster_pt x F : 𝓝 x ⊓ F ≠ ⊥`. A map `f : ι → α` clusters at `x`
along `F : filter ι` if `map_cluster_pt x F f : cluster_pt x (map f F)`. In particular
the notion of cluster point of a sequence `u` is `map_cluster_pt x at_top u`.
This file also defines locally finite families of subsets of `α`.
For topological spaces `α` and `β`, a function `f : α → β` and a point `a : α`,
`continuous_at f a` means `f` is continuous at `a`, and global continuity is
`continuous f`. There is also a version of continuity `pcontinuous` for
partially defined functions.
## Notation
* `𝓝 x`: the filter of neighborhoods of a point `x`;
* `𝓟 s`: the principal filter of a set `s`;
* `𝓝[s] x`: the filter `nhds_within x s` of neighborhoods of a point `x` within a set `s`.
## Implementation notes
Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in
<https://leanprover-community.github.io/theories/topology.html>.
## References
* [N. Bourbaki, *General Topology*][bourbaki1966]
* [I. M. James, *Topologies and Uniformities*][james1999]
## Tags
topological space, interior, closure, frontier, neighborhood, continuity, continuous function
-/
noncomputable theory
open set filter classical
open_locale classical filter
universes u v w
/-!
### Topological spaces
-/
/-- A topology on `α`. -/
@[protect_proj] structure topological_space (α : Type u) :=
(is_open : set α → Prop)
(is_open_univ : is_open univ)
(is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t))
(is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s))
attribute [class] topological_space
/-- A constructor for topologies by specifying the closed sets,
and showing that they satisfy the appropriate conditions. -/
def topological_space.of_closed {α : Type u} (T : set (set α))
(empty_mem : ∅ ∈ T) (sInter_mem : ∀ A ⊆ T, ⋂₀ A ∈ T) (union_mem : ∀ A B ∈ T, A ∪ B ∈ T) :
topological_space α :=
{ is_open := λ X, Xᶜ ∈ T,
is_open_univ := by simp [empty_mem],
is_open_inter := λ s t hs ht, by simpa [set.compl_inter] using union_mem sᶜ tᶜ hs ht,
is_open_sUnion := λ s hs,
by rw set.compl_sUnion; exact sInter_mem (set.compl '' s)
(λ z ⟨y, hy, hz⟩, by simpa [hz.symm] using hs y hy) }
section topological_space
variables {α : Type u} {β : Type v} {ι : Sort w} {a : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop}
@[ext]
lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g
| ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl
section
variables [t : topological_space α]
include t
/-- `is_open s` means that `s` is open in the ambient topological space on `α` -/
def is_open (s : set α) : Prop := topological_space.is_open t s
@[simp]
lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ t
lemma is_open.inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) :=
topological_space.is_open_inter t s₁ s₂ h₁ h₂
lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) :=
topological_space.is_open_sUnion t s h
end
lemma topological_space_eq_iff {t t' : topological_space α} :
t = t' ↔ ∀ s, @is_open α t s ↔ @is_open α t' s :=
⟨λ h s, h ▸ iff.rfl, λ h, by { ext, exact h _ }⟩
lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s :=
rfl
variables [topological_space α]
lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) :=
is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i
lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) :
is_open (⋃i∈s, f i) :=
is_open_Union $ assume i, is_open_Union $ assume hi, h i hi
lemma is_open.union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) :=
by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 ⟨h₂, h₁⟩)
@[simp] lemma is_open_empty : is_open (∅ : set α) :=
by rw ← sUnion_empty; exact is_open_sUnion (assume a, false.elim)
lemma is_open_sInter {s : set (set α)} (hs : finite s) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) :=
finite.induction_on hs (λ _, by rw sInter_empty; exact is_open_univ) $
λ a s has hs ih h, by rw sInter_insert; exact
is_open.inter (h _ $ mem_insert _ _) (ih $ λ t, h t ∘ mem_insert_of_mem _)
lemma is_open_bInter {s : set β} {f : β → set α} (hs : finite s) :
(∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) :=
finite.induction_on hs
(λ _, by rw bInter_empty; exact is_open_univ)
(λ a s has hs ih h, by rw bInter_insert; exact
is_open.inter (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi))))
lemma is_open_Inter [fintype β] {s : β → set α}
(h : ∀ i, is_open (s i)) : is_open (⋂ i, s i) :=
suffices is_open (⋂ (i : β) (hi : i ∈ @univ β), s i), by simpa,
is_open_bInter finite_univ (λ i _, h i)
lemma is_open_Inter_prop {p : Prop} {s : p → set α}
(h : ∀ h : p, is_open (s h)) : is_open (Inter s) :=
by by_cases p; simp *
lemma is_open_const {p : Prop} : is_open {a : α | p} :=
by_cases
(assume : p, begin simp only [this]; exact is_open_univ end)
(assume : ¬ p, begin simp only [this]; exact is_open_empty end)
lemma is_open.and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} :=
is_open.inter
/-- A set is closed if its complement is open -/
class is_closed (s : set α) : Prop :=
(is_open_compl : is_open sᶜ)
@[simp] lemma is_open_compl_iff {s : set α} : is_open sᶜ ↔ is_closed s :=
⟨λ h, ⟨h⟩, λ h, h.is_open_compl⟩
@[simp] lemma is_closed_empty : is_closed (∅ : set α) :=
by { rw [← is_open_compl_iff, compl_empty], exact is_open_univ }
@[simp] lemma is_closed_univ : is_closed (univ : set α) :=
by { rw [← is_open_compl_iff, compl_univ], exact is_open_empty }
lemma is_closed.union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) :=
λ h₁ h₂, by { rw [← is_open_compl_iff] at *, rw compl_union, exact is_open.inter h₁ h₂ }
lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) :=
by simpa only [← is_open_compl_iff, compl_sInter, sUnion_image] using is_open_bUnion
lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) :=
is_closed_sInter $ assume t ⟨i, (heq : f i = t)⟩, heq ▸ h i
lemma is_closed_bInter {s : set β} {f : β → set α} (h : ∀ i ∈ s, is_closed (f i)) :
is_closed (⋂ i ∈ s, f i) :=
is_closed_Inter $ λ i, is_closed_Inter $ h i
@[simp] lemma is_closed_compl_iff {s : set α} : is_closed sᶜ ↔ is_open s :=
by rw [←is_open_compl_iff, compl_compl]
lemma is_open.is_closed_compl {s : set α} (hs : is_open s) : is_closed sᶜ :=
is_closed_compl_iff.2 hs
lemma is_open.sdiff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) :=
is_open.inter h₁ $ is_open_compl_iff.mpr h₂
lemma is_closed.inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) :=
by { rw [← is_open_compl_iff] at *, rw compl_inter, exact is_open.union h₁ h₂ }
lemma is_closed.sdiff {s t : set α} (h₁ : is_closed s) (h₂ : is_open t) : is_closed (s \ t) :=
is_closed.inter h₁ (is_closed_compl_iff.mpr h₂)
lemma is_closed_bUnion {s : set β} {f : β → set α} (hs : finite s) :
(∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) :=
finite.induction_on hs
(λ _, by rw bUnion_empty; exact is_closed_empty)
(λ a s has hs ih h, by rw bUnion_insert; exact
is_closed.union (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi))))
lemma is_closed_Union [fintype β] {s : β → set α}
(h : ∀ i, is_closed (s i)) : is_closed (Union s) :=
suffices is_closed (⋃ (i : β) (hi : i ∈ @univ β), s i),
by convert this; simp [set.ext_iff],
is_closed_bUnion finite_univ (λ i _, h i)
lemma is_closed_Union_prop {p : Prop} {s : p → set α}
(h : ∀ h : p, is_closed (s h)) : is_closed (Union s) :=
by by_cases p; simp *
lemma is_closed_imp {p q : α → Prop} (hp : is_open {x | p x})
(hq : is_closed {x | q x}) : is_closed {x | p x → q x} :=
have {x | p x → q x} = {x | p x}ᶜ ∪ {x | q x}, from set.ext $ λ x, imp_iff_not_or,
by rw [this]; exact is_closed.union (is_closed_compl_iff.mpr hp) hq
lemma is_closed.not : is_closed {a | p a} → is_open {a | ¬ p a} :=
is_open_compl_iff.mpr
/-!
### Interior of a set
-/
/-- The interior of a set `s` is the largest open subset of `s`. -/
def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s}
lemma mem_interior {s : set α} {x : α} :
x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t :=
by simp only [interior, mem_set_of_eq, exists_prop, and_assoc, and.left_comm]
@[simp] lemma is_open_interior {s : set α} : is_open (interior s) :=
is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁
lemma interior_subset {s : set α} : interior s ⊆ s :=
sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂
lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s :=
subset_sUnion_of_mem ⟨h₂, h₁⟩
lemma is_open.interior_eq {s : set α} (h : is_open s) : interior s = s :=
subset.antisymm interior_subset (interior_maximal (subset.refl s) h)
lemma interior_eq_iff_open {s : set α} : interior s = s ↔ is_open s :=
⟨assume h, h ▸ is_open_interior, is_open.interior_eq⟩
lemma subset_interior_iff_open {s : set α} : s ⊆ interior s ↔ is_open s :=
by simp only [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset, true_and]
lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : is_open s) :
s ⊆ interior t ↔ s ⊆ t :=
⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩
@[mono] lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t :=
interior_maximal (subset.trans interior_subset h) is_open_interior
@[simp] lemma interior_empty : interior (∅ : set α) = ∅ :=
is_open_empty.interior_eq
@[simp] lemma interior_univ : interior (univ : set α) = univ :=
is_open_univ.interior_eq
@[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s :=
is_open_interior.interior_eq
@[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t :=
subset.antisymm
(subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t))
(interior_maximal (inter_subset_inter interior_subset interior_subset) $
is_open.inter is_open_interior is_open_interior)
@[simp] lemma finset.interior_Inter {ι : Type*} (s : finset ι) (f : ι → set α) :
interior (⋂ i ∈ s, f i) = ⋂ i ∈ s, interior (f i) :=
begin
classical,
refine s.induction_on (by simp) _,
intros i s h₁ h₂,
simp [h₂],
end
@[simp] lemma interior_Inter_of_fintype {ι : Type*} [fintype ι] (f : ι → set α) :
interior (⋂ i, f i) = ⋂ i, interior (f i) :=
by { convert finset.univ.interior_Inter f; simp, }
lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s)
(h₂ : interior t = ∅) :
interior (s ∪ t) = interior s :=
have interior (s ∪ t) ⊆ s, from
assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩,
classical.by_contradiction $ assume hx₂ : x ∉ s,
have u \ s ⊆ t,
from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂,
have u \ s ⊆ interior t,
by rwa subset_interior_iff_subset_of_open (is_open.sdiff hu₁ h₁),
have u \ s ⊆ ∅,
by rwa h₂ at this,
this ⟨hx₁, hx₂⟩,
subset.antisymm
(interior_maximal this is_open_interior)
(interior_mono $ subset_union_left _ _)
lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t :=
by rw ← subset_interior_iff_open; simp only [subset_def, mem_interior]
lemma interior_Inter_subset (s : ι → set α) : interior (⋂ i, s i) ⊆ ⋂ i, interior (s i) :=
subset_Inter $ λ i, interior_mono $ Inter_subset _ _
lemma interior_bInter_subset (p : ι → Sort*) (s : Π i, p i → set α) :
interior (⋂ i (hi : p i), s i hi) ⊆ ⋂ i (hi : p i), interior (s i hi) :=
(interior_Inter_subset _).trans $ Inter_subset_Inter $ λ i, interior_Inter_subset _
lemma interior_sInter_subset (S : set (set α)) : interior (⋂₀ S) ⊆ ⋂ s ∈ S, interior s :=
calc interior (⋂₀ S) = interior (⋂ s ∈ S, s) : by rw sInter_eq_bInter
... ⊆ ⋂ s ∈ S, interior s : interior_bInter_subset _ _
/-!
### Closure of a set
-/
/-- The closure of `s` is the smallest closed set containing `s`. -/
def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t}
@[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) :=
is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁
lemma subset_closure {s : set α} : s ⊆ closure s :=
subset_sInter $ assume t ⟨h₁, h₂⟩, h₂
lemma not_mem_of_not_mem_closure {s : set α} {P : α} (hP : P ∉ closure s) : P ∉ s :=
λ h, hP (subset_closure h)
lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t :=
sInter_subset_of_mem ⟨h₂, h₁⟩
lemma is_closed.closure_eq {s : set α} (h : is_closed s) : closure s = s :=
subset.antisymm (closure_minimal (subset.refl s) h) subset_closure
lemma is_closed.closure_subset {s : set α} (hs : is_closed s) : closure s ⊆ s :=
closure_minimal (subset.refl _) hs
lemma is_closed.closure_subset_iff {s t : set α} (h₁ : is_closed t) :
closure s ⊆ t ↔ s ⊆ t :=
⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩
@[mono] lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t :=
closure_minimal (subset.trans h subset_closure) is_closed_closure
lemma monotone_closure (α : Type*) [topological_space α] : monotone (@closure α _) :=
λ _ _, closure_mono
lemma diff_subset_closure_iff {s t : set α} :
s \ t ⊆ closure t ↔ s ⊆ closure t :=
by rw [diff_subset_iff, union_eq_self_of_subset_left subset_closure]
lemma closure_inter_subset_inter_closure (s t : set α) :
closure (s ∩ t) ⊆ closure s ∩ closure t :=
(monotone_closure α).map_inf_le s t
lemma is_closed_of_closure_subset {s : set α} (h : closure s ⊆ s) : is_closed s :=
by rw subset.antisymm subset_closure h; exact is_closed_closure
lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s :=
⟨assume h, h ▸ is_closed_closure, is_closed.closure_eq⟩
lemma closure_subset_iff_is_closed {s : set α} : closure s ⊆ s ↔ is_closed s :=
⟨is_closed_of_closure_subset, is_closed.closure_subset⟩
@[simp] lemma closure_empty : closure (∅ : set α) = ∅ :=
is_closed_empty.closure_eq
@[simp] lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ :=
⟨subset_eq_empty subset_closure, λ h, h.symm ▸ closure_empty⟩
@[simp] lemma closure_nonempty_iff {s : set α} : (closure s).nonempty ↔ s.nonempty :=
by simp only [← ne_empty_iff_nonempty, ne.def, closure_empty_iff]
alias closure_nonempty_iff ↔ set.nonempty.of_closure set.nonempty.closure
@[simp] lemma closure_univ : closure (univ : set α) = univ :=
is_closed_univ.closure_eq
@[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s :=
is_closed_closure.closure_eq
@[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t :=
subset.antisymm
(closure_minimal (union_subset_union subset_closure subset_closure) $
is_closed.union is_closed_closure is_closed_closure)
((monotone_closure α).le_map_sup s t)
@[simp] lemma finset.closure_Union {ι : Type*} (s : finset ι) (f : ι → set α) :
closure (⋃ i ∈ s, f i) = ⋃ i ∈ s, closure (f i) :=
begin
classical,
refine s.induction_on (by simp) _,
intros i s h₁ h₂,
simp [h₂],
end
@[simp] lemma closure_Union_of_fintype {ι : Type*} [fintype ι] (f : ι → set α) :
closure (⋃ i, f i) = ⋃ i, closure (f i) :=
by { convert finset.univ.closure_Union f; simp, }
lemma interior_subset_closure {s : set α} : interior s ⊆ closure s :=
subset.trans interior_subset subset_closure
lemma closure_eq_compl_interior_compl {s : set α} : closure s = (interior sᶜ)ᶜ :=
begin
rw [interior, closure, compl_sUnion, compl_image_set_of],
simp only [compl_subset_compl, is_open_compl_iff],
end
@[simp] lemma interior_compl {s : set α} : interior sᶜ = (closure s)ᶜ :=
by simp [closure_eq_compl_interior_compl]
@[simp] lemma closure_compl {s : set α} : closure sᶜ = (interior s)ᶜ :=
by simp [closure_eq_compl_interior_compl]
theorem mem_closure_iff {s : set α} {a : α} :
a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → (o ∩ s).nonempty :=
⟨λ h o oo ao, classical.by_contradiction $ λ os,
have s ⊆ oᶜ, from λ x xs xo, os ⟨x, xo, xs⟩,
closure_minimal this (is_closed_compl_iff.2 oo) h ao,
λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc,
let ⟨x, hc, hs⟩ := (H _ h₁.is_open_compl nc) in hc (h₂ hs)⟩
/-- A set is dense in a topological space if every point belongs to its closure. -/
def dense (s : set α) : Prop := ∀ x, x ∈ closure s
lemma dense_iff_closure_eq {s : set α} : dense s ↔ closure s = univ :=
eq_univ_iff_forall.symm
lemma dense.closure_eq {s : set α} (h : dense s) : closure s = univ :=
dense_iff_closure_eq.mp h
lemma interior_eq_empty_iff_dense_compl {s : set α} : interior s = ∅ ↔ dense sᶜ :=
by rw [dense_iff_closure_eq, closure_compl, compl_univ_iff]
lemma dense.interior_compl {s : set α} (h : dense s) : interior sᶜ = ∅ :=
interior_eq_empty_iff_dense_compl.2 $ by rwa compl_compl
/-- The closure of a set `s` is dense if and only if `s` is dense. -/
@[simp] lemma dense_closure {s : set α} : dense (closure s) ↔ dense s :=
by rw [dense, dense, closure_closure]
alias dense_closure ↔ dense.of_closure dense.closure
@[simp] lemma dense_univ : dense (univ : set α) := λ x, subset_closure trivial
/-- A set is dense if and only if it has a nonempty intersection with each nonempty open set. -/
lemma dense_iff_inter_open {s : set α} :
dense s ↔ ∀ U, is_open U → U.nonempty → (U ∩ s).nonempty :=
begin
split ; intro h,
{ rintros U U_op ⟨x, x_in⟩,
exact mem_closure_iff.1 (by simp only [h.closure_eq]) U U_op x_in },
{ intro x,
rw mem_closure_iff,
intros U U_op x_in,
exact h U U_op ⟨_, x_in⟩ },
end
alias dense_iff_inter_open ↔ dense.inter_open_nonempty _
lemma dense.exists_mem_open {s : set α} (hs : dense s) {U : set α} (ho : is_open U)
(hne : U.nonempty) :
∃ x ∈ s, x ∈ U :=
let ⟨x, hx⟩ := hs.inter_open_nonempty U ho hne in ⟨x, hx.2, hx.1⟩
lemma dense.nonempty_iff {s : set α} (hs : dense s) :
s.nonempty ↔ nonempty α :=
⟨λ ⟨x, hx⟩, ⟨x⟩, λ ⟨x⟩,
let ⟨y, hy⟩ := hs.inter_open_nonempty _ is_open_univ ⟨x, trivial⟩ in ⟨y, hy.2⟩⟩
lemma dense.nonempty [h : nonempty α] {s : set α} (hs : dense s) : s.nonempty :=
hs.nonempty_iff.2 h
@[mono]
lemma dense.mono {s₁ s₂ : set α} (h : s₁ ⊆ s₂) (hd : dense s₁) : dense s₂ :=
λ x, closure_mono h (hd x)
/-- Complement to a singleton is dense if and only if the singleton is not an open set. -/
lemma dense_compl_singleton_iff_not_open {x : α} : dense ({x}ᶜ : set α) ↔ ¬is_open ({x} : set α) :=
begin
fsplit,
{ intros hd ho,
exact (hd.inter_open_nonempty _ ho (singleton_nonempty _)).ne_empty (inter_compl_self _) },
{ refine λ ho, dense_iff_inter_open.2 (λ U hU hne, inter_compl_nonempty_iff.2 $ λ hUx, _),
obtain rfl : U = {x}, from eq_singleton_iff_nonempty_unique_mem.2 ⟨hne, hUx⟩,
exact ho hU }
end
/-!
### Frontier of a set
-/
/-- The frontier of a set is the set of points between the closure and interior. -/
def frontier (s : set α) : set α := closure s \ interior s
lemma frontier_eq_closure_inter_closure {s : set α} :
frontier s = closure s ∩ closure sᶜ :=
by rw [closure_compl, frontier, diff_eq]
lemma frontier_subset_closure {s : set α} : frontier s ⊆ closure s := diff_subset _ _
/-- The complement of a set has the same frontier as the original set. -/
@[simp] lemma frontier_compl (s : set α) : frontier sᶜ = frontier s :=
by simp only [frontier_eq_closure_inter_closure, compl_compl, inter_comm]
@[simp] lemma frontier_univ : frontier (univ : set α) = ∅ := by simp [frontier]
@[simp] lemma frontier_empty : frontier (∅ : set α) = ∅ := by simp [frontier]
lemma frontier_inter_subset (s t : set α) :
frontier (s ∩ t) ⊆ (frontier s ∩ closure t) ∪ (closure s ∩ frontier t) :=
begin
simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union],
convert inter_subset_inter_left _ (closure_inter_subset_inter_closure s t),
simp only [inter_distrib_left, inter_distrib_right, inter_assoc],
congr' 2,
apply inter_comm
end
lemma frontier_union_subset (s t : set α) :
frontier (s ∪ t) ⊆ (frontier s ∩ closure tᶜ) ∪ (closure sᶜ ∩ frontier t) :=
by simpa only [frontier_compl, ← compl_union]
using frontier_inter_subset sᶜ tᶜ
lemma is_closed.frontier_eq {s : set α} (hs : is_closed s) : frontier s = s \ interior s :=
by rw [frontier, hs.closure_eq]
lemma is_open.frontier_eq {s : set α} (hs : is_open s) : frontier s = closure s \ s :=
by rw [frontier, hs.interior_eq]
lemma is_open.inter_frontier_eq {s : set α} (hs : is_open s) : s ∩ frontier s = ∅ :=
by rw [hs.frontier_eq, inter_diff_self]
/-- The frontier of a set is closed. -/
lemma is_closed_frontier {s : set α} : is_closed (frontier s) :=
by rw frontier_eq_closure_inter_closure; exact is_closed.inter is_closed_closure is_closed_closure
/-- The frontier of a closed set has no interior point. -/
lemma interior_frontier {s : set α} (h : is_closed s) : interior (frontier s) = ∅ :=
begin
have A : frontier s = s \ interior s, from h.frontier_eq,
have B : interior (frontier s) ⊆ interior s, by rw A; exact interior_mono (diff_subset _ _),
have C : interior (frontier s) ⊆ frontier s := interior_subset,
have : interior (frontier s) ⊆ (interior s) ∩ (s \ interior s) :=
subset_inter B (by simpa [A] using C),
rwa [inter_diff_self, subset_empty_iff] at this,
end
lemma closure_eq_interior_union_frontier (s : set α) : closure s = interior s ∪ frontier s :=
(union_diff_cancel interior_subset_closure).symm
lemma closure_eq_self_union_frontier (s : set α) : closure s = s ∪ frontier s :=
(union_diff_cancel' interior_subset subset_closure).symm
lemma is_open.inter_frontier_eq_empty_of_disjoint {s t : set α} (ht : is_open t)
(hd : disjoint s t) :
t ∩ frontier s = ∅ :=
begin
rw [inter_comm, ← subset_compl_iff_disjoint],
exact subset.trans frontier_subset_closure (closure_minimal (λ _, disjoint_left.1 hd)
(is_closed_compl_iff.2 ht))
end
lemma frontier_eq_inter_compl_interior {s : set α} :
frontier s = (interior s)ᶜ ∩ (interior (sᶜ))ᶜ :=
by { rw [←frontier_compl, ←closure_compl], refl }
lemma compl_frontier_eq_union_interior {s : set α} :
(frontier s)ᶜ = interior s ∪ interior sᶜ :=
begin
rw frontier_eq_inter_compl_interior,
simp only [compl_inter, compl_compl],
end
/-!
### Neighborhoods
-/
/-- A set is called a neighborhood of `a` if it contains an open set around `a`. The set of all
neighborhoods of `a` forms a filter, the neighborhood filter at `a`, is here defined as the
infimum over the principal filters of all open sets containing `a`. -/
@[irreducible] def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s)
localized "notation `𝓝` := nhds" in topological_space
/-- The "neighborhood within" filter. Elements of `𝓝[s] a` are sets containing the
intersection of `s` and a neighborhood of `a`. -/
def nhds_within (a : α) (s : set α) : filter α := 𝓝 a ⊓ 𝓟 s
localized "notation `𝓝[` s `] ` x:100 := nhds_within x s" in topological_space
lemma nhds_def (a : α) : 𝓝 a = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) := by rw nhds
/-- The open sets containing `a` are a basis for the neighborhood filter. See `nhds_basis_opens'`
for a variant using open neighborhoods instead. -/
lemma nhds_basis_opens (a : α) : (𝓝 a).has_basis (λ s : set α, a ∈ s ∧ is_open s) (λ x, x) :=
begin
rw nhds_def,
exact has_basis_binfi_principal
(λ s ⟨has, hs⟩ t ⟨hat, ht⟩, ⟨s ∩ t, ⟨⟨has, hat⟩, is_open.inter hs ht⟩,
⟨inter_subset_left _ _, inter_subset_right _ _⟩⟩)
⟨univ, ⟨mem_univ a, is_open_univ⟩⟩
end
/-- A filter lies below the neighborhood filter at `a` iff it contains every open set around `a`. -/
lemma le_nhds_iff {f a} : f ≤ 𝓝 a ↔ ∀ s : set α, a ∈ s → is_open s → s ∈ f :=
by simp [nhds_def]
/-- To show a filter is above the neighborhood filter at `a`, it suffices to show that it is above
the principal filter of some open set `s` containing `a`. -/
lemma nhds_le_of_le {f a} {s : set α} (h : a ∈ s) (o : is_open s) (sf : 𝓟 s ≤ f) : 𝓝 a ≤ f :=
by rw nhds_def; exact infi_le_of_le s (infi_le_of_le ⟨h, o⟩ sf)
lemma mem_nhds_iff {a : α} {s : set α} :
s ∈ 𝓝 a ↔ ∃t⊆s, is_open t ∧ a ∈ t :=
(nhds_basis_opens a).mem_iff.trans
⟨λ ⟨t, ⟨hat, ht⟩, hts⟩, ⟨t, hts, ht, hat⟩, λ ⟨t, hts, ht, hat⟩, ⟨t, ⟨hat, ht⟩, hts⟩⟩
/-- A predicate is true in a neighborhood of `a` iff it is true for all the points in an open set
containing `a`. -/
lemma eventually_nhds_iff {a : α} {p : α → Prop} :
(∀ᶠ x in 𝓝 a, p x) ↔ ∃ (t : set α), (∀ x ∈ t, p x) ∧ is_open t ∧ a ∈ t :=
mem_nhds_iff.trans $ by simp only [subset_def, exists_prop, mem_set_of_eq]
lemma map_nhds {a : α} {f : α → β} :
map f (𝓝 a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 (image f s)) :=
((nhds_basis_opens a).map f).eq_binfi
lemma mem_of_mem_nhds {a : α} {s : set α} : s ∈ 𝓝 a → a ∈ s :=
λ H, let ⟨t, ht, _, hs⟩ := mem_nhds_iff.1 H in ht hs
/-- If a predicate is true in a neighborhood of `a`, then it is true for `a`. -/
lemma filter.eventually.self_of_nhds {p : α → Prop} {a : α}
(h : ∀ᶠ y in 𝓝 a, p y) : p a :=
mem_of_mem_nhds h
lemma is_open.mem_nhds {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) :
s ∈ 𝓝 a :=
mem_nhds_iff.2 ⟨s, subset.refl _, hs, ha⟩
lemma is_closed.compl_mem_nhds {a : α} {s : set α} (hs : is_closed s) (ha : a ∉ s) : sᶜ ∈ 𝓝 a :=
hs.is_open_compl.mem_nhds (mem_compl ha)
lemma is_open.eventually_mem {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) :
∀ᶠ x in 𝓝 a, x ∈ s :=
is_open.mem_nhds hs ha
/-- The open neighborhoods of `a` are a basis for the neighborhood filter. See `nhds_basis_opens`
for a variant using open sets around `a` instead. -/
lemma nhds_basis_opens' (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_open s) (λ x, x) :=
begin
convert nhds_basis_opens a,
ext s,
split,
{ rintros ⟨s_in, s_op⟩,
exact ⟨mem_of_mem_nhds s_in, s_op⟩ },
{ rintros ⟨a_in, s_op⟩,
exact ⟨is_open.mem_nhds s_op a_in, s_op⟩ },
end
/-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of `s`:
it contains an open set containing `s`. -/
lemma exists_open_set_nhds {s U : set α} (h : ∀ x ∈ s, U ∈ 𝓝 x) :
∃ V : set α, s ⊆ V ∧ is_open V ∧ V ⊆ U :=
begin
have := λ x hx, (nhds_basis_opens x).mem_iff.1 (h x hx),
choose! Z hZ hZ' using this,
refine ⟨⋃ x ∈ s, Z x, _, _, bUnion_subset hZ'⟩,
{ intros x hx,
simp only [mem_Union],
exact ⟨x, hx, (hZ x hx).1⟩ },
{ apply is_open_Union,
intros x,
by_cases hx : x ∈ s ; simp [hx],
exact (hZ x hx).2 }
end
/-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of s:
it contains an open set containing `s`. -/
lemma exists_open_set_nhds' {s U : set α} (h : U ∈ ⨆ x ∈ s, 𝓝 x) :
∃ V : set α, s ⊆ V ∧ is_open V ∧ V ⊆ U :=
exists_open_set_nhds (by simpa using h)
/-- If a predicate is true in a neighbourhood of `a`, then for `y` sufficiently close
to `a` this predicate is true in a neighbourhood of `y`. -/
lemma filter.eventually.eventually_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) :
∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x :=
let ⟨t, htp, hto, ha⟩ := eventually_nhds_iff.1 h in
eventually_nhds_iff.2 ⟨t, λ x hx, eventually_nhds_iff.2 ⟨t, htp, hto, hx⟩, hto, ha⟩
@[simp] lemma eventually_eventually_nhds {p : α → Prop} {a : α} :
(∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x) ↔ ∀ᶠ x in 𝓝 a, p x :=
⟨λ h, h.self_of_nhds, λ h, h.eventually_nhds⟩
@[simp] lemma nhds_bind_nhds : (𝓝 a).bind 𝓝 = 𝓝 a := filter.ext $ λ s, eventually_eventually_nhds
@[simp] lemma eventually_eventually_eq_nhds {f g : α → β} {a : α} :
(∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g) ↔ f =ᶠ[𝓝 a] g :=
eventually_eventually_nhds
lemma filter.eventually_eq.eq_of_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : f a = g a :=
h.self_of_nhds
@[simp] lemma eventually_eventually_le_nhds [has_le β] {f g : α → β} {a : α} :
(∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g) ↔ f ≤ᶠ[𝓝 a] g :=
eventually_eventually_nhds
/-- If two functions are equal in a neighbourhood of `a`, then for `y` sufficiently close
to `a` these functions are equal in a neighbourhood of `y`. -/
lemma filter.eventually_eq.eventually_eq_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) :
∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g :=
h.eventually_nhds
/-- If `f x ≤ g x` in a neighbourhood of `a`, then for `y` sufficiently close to `a` we have
`f x ≤ g x` in a neighbourhood of `y`. -/
lemma filter.eventually_le.eventually_le_nhds [has_le β] {f g : α → β} {a : α} (h : f ≤ᶠ[𝓝 a] g) :
∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g :=
h.eventually_nhds
theorem all_mem_nhds (x : α) (P : set α → Prop) (hP : ∀ s t, s ⊆ t → P s → P t) :
(∀ s ∈ 𝓝 x, P s) ↔ (∀ s, is_open s → x ∈ s → P s) :=
((nhds_basis_opens x).forall_iff hP).trans $ by simp only [and_comm (x ∈ _), and_imp]
theorem all_mem_nhds_filter (x : α) (f : set α → set β) (hf : ∀ s t, s ⊆ t → f s ⊆ f t)
(l : filter β) :
(∀ s ∈ 𝓝 x, f s ∈ l) ↔ (∀ s, is_open s → x ∈ s → f s ∈ l) :=
all_mem_nhds _ _ (λ s t ssubt h, mem_of_superset h (hf s t ssubt))
theorem rtendsto_nhds {r : rel β α} {l : filter β} {a : α} :
rtendsto r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.core s ∈ l) :=
all_mem_nhds_filter _ _ (λ s t, id) _
theorem rtendsto'_nhds {r : rel β α} {l : filter β} {a : α} :
rtendsto' r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.preimage s ∈ l) :=
by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono }
theorem ptendsto_nhds {f : β →. α} {l : filter β} {a : α} :
ptendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.core s ∈ l) :=
rtendsto_nhds
theorem ptendsto'_nhds {f : β →. α} {l : filter β} {a : α} :
ptendsto' f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.preimage s ∈ l) :=
rtendsto'_nhds
theorem tendsto_nhds {f : β → α} {l : filter β} {a : α} :
tendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f ⁻¹' s ∈ l) :=
all_mem_nhds_filter _ _ (λ s t h, preimage_mono h) _
lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (𝓝 a) :=
tendsto_nhds.mpr $ assume s hs ha, univ_mem' $ assume _, ha
lemma tendsto_at_top_of_eventually_const {ι : Type*} [semilattice_sup ι] [nonempty ι]
{x : α} {u : ι → α} {i₀ : ι} (h : ∀ i ≥ i₀, u i = x) : tendsto u at_top (𝓝 x) :=
tendsto.congr' (eventually_eq.symm (eventually_at_top.mpr ⟨i₀, h⟩)) tendsto_const_nhds
lemma tendsto_at_bot_of_eventually_const {ι : Type*} [semilattice_inf ι] [nonempty ι]
{x : α} {u : ι → α} {i₀ : ι} (h : ∀ i ≤ i₀, u i = x) : tendsto u at_bot (𝓝 x) :=
tendsto.congr' (eventually_eq.symm (eventually_at_bot.mpr ⟨i₀, h⟩)) tendsto_const_nhds
lemma pure_le_nhds : pure ≤ (𝓝 : α → filter α) :=
assume a s hs, mem_pure.2 $ mem_of_mem_nhds hs
lemma tendsto_pure_nhds {α : Type*} [topological_space β] (f : α → β) (a : α) :
tendsto f (pure a) (𝓝 (f a)) :=
(tendsto_pure_pure f a).mono_right (pure_le_nhds _)
lemma order_top.tendsto_at_top_nhds {α : Type*} [partial_order α] [order_top α]
[topological_space β] (f : α → β) : tendsto f at_top (𝓝 $ f ⊤) :=
(tendsto_at_top_pure f).mono_right (pure_le_nhds _)
@[simp] instance nhds_ne_bot {a : α} : ne_bot (𝓝 a) :=
ne_bot_of_le (pure_le_nhds a)
/-!
### Cluster points
In this section we define [cluster points](https://en.wikipedia.org/wiki/Limit_point)
(also known as limit points and accumulation points) of a filter and of a sequence.
-/
/-- A point `x` is a cluster point of a filter `F` if 𝓝 x ⊓ F ≠ ⊥. Also known as
an accumulation point or a limit point. -/
def cluster_pt (x : α) (F : filter α) : Prop := ne_bot (𝓝 x ⊓ F)
lemma cluster_pt.ne_bot {x : α} {F : filter α} (h : cluster_pt x F) : ne_bot (𝓝 x ⊓ F) := h
lemma filter.has_basis.cluster_pt_iff {ιa ιF} {pa : ιa → Prop} {sa : ιa → set α}
{pF : ιF → Prop} {sF : ιF → set α} {F : filter α}
(ha : (𝓝 a).has_basis pa sa) (hF : F.has_basis pF sF) :
cluster_pt a F ↔ ∀ ⦃i⦄ (hi : pa i) ⦃j⦄ (hj : pF j), (sa i ∩ sF j).nonempty :=
ha.inf_basis_ne_bot_iff hF
lemma cluster_pt_iff {x : α} {F : filter α} :
cluster_pt x F ↔ ∀ ⦃U : set α⦄ (hU : U ∈ 𝓝 x) ⦃V⦄ (hV : V ∈ F), (U ∩ V).nonempty :=
inf_ne_bot_iff
/-- `x` is a cluster point of a set `s` if every neighbourhood of `x` meets `s` on a nonempty
set. -/
lemma cluster_pt_principal_iff {x : α} {s : set α} :
cluster_pt x (𝓟 s) ↔ ∀ U ∈ 𝓝 x, (U ∩ s).nonempty :=
inf_principal_ne_bot_iff
lemma cluster_pt_principal_iff_frequently {x : α} {s : set α} :
cluster_pt x (𝓟 s) ↔ ∃ᶠ y in 𝓝 x, y ∈ s :=
by simp only [cluster_pt_principal_iff, frequently_iff, set.nonempty, exists_prop, mem_inter_iff]
lemma cluster_pt.of_le_nhds {x : α} {f : filter α} (H : f ≤ 𝓝 x) [ne_bot f] : cluster_pt x f :=
by rwa [cluster_pt, inf_eq_right.mpr H]
lemma cluster_pt.of_le_nhds' {x : α} {f : filter α} (H : f ≤ 𝓝 x) (hf : ne_bot f) :
cluster_pt x f :=
cluster_pt.of_le_nhds H
lemma cluster_pt.of_nhds_le {x : α} {f : filter α} (H : 𝓝 x ≤ f) : cluster_pt x f :=
by simp only [cluster_pt, inf_eq_left.mpr H, nhds_ne_bot]
lemma cluster_pt.mono {x : α} {f g : filter α} (H : cluster_pt x f) (h : f ≤ g) :
cluster_pt x g :=
⟨ne_bot_of_le_ne_bot H.ne $ inf_le_inf_left _ h⟩
lemma cluster_pt.of_inf_left {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) :
cluster_pt x f :=
H.mono inf_le_left
lemma cluster_pt.of_inf_right {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) :
cluster_pt x g :=
H.mono inf_le_right
lemma ultrafilter.cluster_pt_iff {x : α} {f : ultrafilter α} : cluster_pt x f ↔ ↑f ≤ 𝓝 x :=
⟨f.le_of_inf_ne_bot', λ h, cluster_pt.of_le_nhds h⟩
/-- A point `x` is a cluster point of a sequence `u` along a filter `F` if it is a cluster point
of `map u F`. -/
def map_cluster_pt {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : Prop := cluster_pt x (map u F)
lemma map_cluster_pt_iff {ι :Type*} (x : α) (F : filter ι) (u : ι → α) :
map_cluster_pt x F u ↔ ∀ s ∈ 𝓝 x, ∃ᶠ a in F, u a ∈ s :=
by { simp_rw [map_cluster_pt, cluster_pt, inf_ne_bot_iff_frequently_left, frequently_map], refl }
lemma map_cluster_pt_of_comp {ι δ :Type*} {F : filter ι} {φ : δ → ι} {p : filter δ}
{x : α} {u : ι → α} [ne_bot p] (h : tendsto φ p F) (H : tendsto (u ∘ φ) p (𝓝 x)) :
map_cluster_pt x F u :=
begin
have := calc
map (u ∘ φ) p = map u (map φ p) : map_map
... ≤ map u F : map_mono h,
have : map (u ∘ φ) p ≤ 𝓝 x ⊓ map u F,
from le_inf H this,
exact ne_bot_of_le this
end
/-!
### Interior, closure and frontier in terms of neighborhoods
-/
lemma interior_eq_nhds' {s : set α} : interior s = {a | s ∈ 𝓝 a} :=
set.ext $ λ x, by simp only [mem_interior, mem_nhds_iff, mem_set_of_eq]
lemma interior_eq_nhds {s : set α} : interior s = {a | 𝓝 a ≤ 𝓟 s} :=
interior_eq_nhds'.trans $ by simp only [le_principal_iff]
lemma mem_interior_iff_mem_nhds {s : set α} {a : α} :
a ∈ interior s ↔ s ∈ 𝓝 a :=
by rw [interior_eq_nhds', mem_set_of_eq]
@[simp] lemma interior_mem_nhds {s : set α} {a : α} :
interior s ∈ 𝓝 a ↔ s ∈ 𝓝 a :=
⟨λ h, mem_of_superset h interior_subset,
λ h, is_open.mem_nhds is_open_interior (mem_interior_iff_mem_nhds.2 h)⟩
lemma interior_set_of_eq {p : α → Prop} :
interior {x | p x} = {x | ∀ᶠ y in 𝓝 x, p y} :=
interior_eq_nhds'
lemma is_open_set_of_eventually_nhds {p : α → Prop} :
is_open {x | ∀ᶠ y in 𝓝 x, p y} :=
by simp only [← interior_set_of_eq, is_open_interior]
lemma subset_interior_iff_nhds {s V : set α} : s ⊆ interior V ↔ ∀ x ∈ s, V ∈ 𝓝 x :=
show (∀ x, x ∈ s → x ∈ _) ↔ _, by simp_rw mem_interior_iff_mem_nhds
lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, 𝓝 a ≤ 𝓟 s :=
calc is_open s ↔ s ⊆ interior s : subset_interior_iff_open.symm
... ↔ (∀a∈s, 𝓝 a ≤ 𝓟 s) : by rw [interior_eq_nhds]; refl
lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ 𝓝 a :=
is_open_iff_nhds.trans $ forall_congr $ λ _, imp_congr_right $ λ _, le_principal_iff
theorem is_open_iff_ultrafilter {s : set α} :
is_open s ↔ (∀ (x ∈ s) (l : ultrafilter α), ↑l ≤ 𝓝 x → s ∈ l) :=
by simp_rw [is_open_iff_mem_nhds, ← mem_iff_ultrafilter]
lemma mem_closure_iff_frequently {s : set α} {a : α} : a ∈ closure s ↔ ∃ᶠ x in 𝓝 a, x ∈ s :=
by rw [filter.frequently, filter.eventually, ← mem_interior_iff_mem_nhds,
closure_eq_compl_interior_compl]; refl
alias mem_closure_iff_frequently ↔ _ filter.frequently.mem_closure
/-- The set of cluster points of a filter is closed. In particular, the set of limit points
of a sequence is closed. -/
lemma is_closed_set_of_cluster_pt {f : filter α} : is_closed {x | cluster_pt x f} :=
begin
simp only [cluster_pt, inf_ne_bot_iff_frequently_left, set_of_forall, imp_iff_not_or],
refine is_closed_Inter (λ p, is_closed.union _ _); apply is_closed_compl_iff.2,
exacts [is_open_set_of_eventually_nhds, is_open_const]
end
theorem mem_closure_iff_cluster_pt {s : set α} {a : α} : a ∈ closure s ↔ cluster_pt a (𝓟 s) :=
mem_closure_iff_frequently.trans cluster_pt_principal_iff_frequently.symm
lemma mem_closure_iff_nhds_ne_bot {s : set α} : a ∈ closure s ↔ 𝓝 a ⊓ 𝓟 s ≠ ⊥ :=
mem_closure_iff_cluster_pt.trans ne_bot_iff
lemma mem_closure_iff_nhds_within_ne_bot {s : set α} {x : α} :
x ∈ closure s ↔ ne_bot (𝓝[s] x) :=
mem_closure_iff_cluster_pt
/-- If `x` is not an isolated point of a topological space, then `{x}ᶜ` is dense in the whole
space. -/
lemma dense_compl_singleton (x : α) [ne_bot (𝓝[{x}ᶜ] x)] : dense ({x}ᶜ : set α) :=
begin
intro y,
unfreezingI { rcases eq_or_ne y x with rfl|hne },
{ rwa mem_closure_iff_nhds_within_ne_bot },
{ exact subset_closure hne }
end
/-- If `x` is not an isolated point of a topological space, then the closure of `{x}ᶜ` is the whole
space. -/
@[simp] lemma closure_compl_singleton (x : α) [ne_bot (𝓝[{x}ᶜ] x)] :
closure {x}ᶜ = (univ : set α) :=
(dense_compl_singleton x).closure_eq
/-- If `x` is not an isolated point of a topological space, then the interior of `{x}ᶜ` is empty. -/
@[simp] lemma interior_singleton (x : α) [ne_bot (𝓝[{x}ᶜ] x)] :
interior {x} = (∅ : set α) :=
interior_eq_empty_iff_dense_compl.2 (dense_compl_singleton x)
lemma closure_eq_cluster_pts {s : set α} : closure s = {a | cluster_pt a (𝓟 s)} :=
set.ext $ λ x, mem_closure_iff_cluster_pt
theorem mem_closure_iff_nhds {s : set α} {a : α} :
a ∈ closure s ↔ ∀ t ∈ 𝓝 a, (t ∩ s).nonempty :=
mem_closure_iff_cluster_pt.trans cluster_pt_principal_iff
theorem mem_closure_iff_nhds' {s : set α} {a : α} :
a ∈ closure s ↔ ∀ t ∈ 𝓝 a, ∃ y : s, ↑y ∈ t :=
by simp only [mem_closure_iff_nhds, set.nonempty_inter_iff_exists_right]
theorem mem_closure_iff_comap_ne_bot {A : set α} {x : α} :
x ∈ closure A ↔ ne_bot (comap (coe : A → α) (𝓝 x)) :=
by simp_rw [mem_closure_iff_nhds, comap_ne_bot_iff, set.nonempty_inter_iff_exists_right]
theorem mem_closure_iff_nhds_basis' {a : α} {p : ι → Prop} {s : ι → set α} (h : (𝓝 a).has_basis p s)
{t : set α} :
a ∈ closure t ↔ ∀ i, p i → (s i ∩ t).nonempty :=
mem_closure_iff_cluster_pt.trans $ (h.cluster_pt_iff (has_basis_principal _)).trans $
by simp only [exists_prop, forall_const]
theorem mem_closure_iff_nhds_basis {a : α} {p : ι → Prop} {s : ι → set α} (h : (𝓝 a).has_basis p s)
{t : set α} :
a ∈ closure t ↔ ∀ i, p i → ∃ y ∈ t, y ∈ s i :=
(mem_closure_iff_nhds_basis' h).trans $
by simp only [set.nonempty, mem_inter_eq, exists_prop, and_comm]
/-- `x` belongs to the closure of `s` if and only if some ultrafilter
supported on `s` converges to `x`. -/
lemma mem_closure_iff_ultrafilter {s : set α} {x : α} :
x ∈ closure s ↔ ∃ (u : ultrafilter α), s ∈ u ∧ ↑u ≤ 𝓝 x :=
by simp [closure_eq_cluster_pts, cluster_pt, ← exists_ultrafilter_iff, and.comm]
lemma is_closed_iff_cluster_pt {s : set α} : is_closed s ↔ ∀a, cluster_pt a (𝓟 s) → a ∈ s :=
calc is_closed s ↔ closure s ⊆ s : closure_subset_iff_is_closed.symm
... ↔ (∀a, cluster_pt a (𝓟 s) → a ∈ s) : by simp only [subset_def, mem_closure_iff_cluster_pt]
lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀ x, (∀ U ∈ 𝓝 x, (U ∩ s).nonempty) → x ∈ s :=
by simp_rw [is_closed_iff_cluster_pt, cluster_pt, inf_principal_ne_bot_iff]
lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) :=
begin
rintro a ⟨hs, ht⟩,
have : s ∈ 𝓝 a := is_open.mem_nhds h hs,
rw mem_closure_iff_nhds_ne_bot at ht ⊢,
rwa [← inf_principal, ← inf_assoc, inf_eq_left.2 (le_principal_iff.2 this)],
end
lemma closure_inter_open' {s t : set α} (h : is_open t) : closure s ∩ t ⊆ closure (s ∩ t) :=
by simpa only [inter_comm] using closure_inter_open h
lemma dense.open_subset_closure_inter {s t : set α} (hs : dense s) (ht : is_open t) :
t ⊆ closure (t ∩ s) :=
calc t = t ∩ closure s : by rw [hs.closure_eq, inter_univ]
... ⊆ closure (t ∩ s) : closure_inter_open ht
lemma mem_closure_of_mem_closure_union {s₁ s₂ : set α} {x : α} (h : x ∈ closure (s₁ ∪ s₂))
(h₁ : s₁ᶜ ∈ 𝓝 x) : x ∈ closure s₂ :=
begin
rw mem_closure_iff_nhds_ne_bot at *,
rwa ← calc
𝓝 x ⊓ principal (s₁ ∪ s₂) = 𝓝 x ⊓ (principal s₁ ⊔ principal s₂) : by rw sup_principal
... = (𝓝 x ⊓ principal s₁) ⊔ (𝓝 x ⊓ principal s₂) : inf_sup_left
... = ⊥ ⊔ 𝓝 x ⊓ principal s₂ : by rw inf_principal_eq_bot.mpr h₁
... = 𝓝 x ⊓ principal s₂ : bot_sup_eq
end
/-- The intersection of an open dense set with a dense set is a dense set. -/
lemma dense.inter_of_open_left {s t : set α} (hs : dense s) (ht : dense t) (hso : is_open s) :
dense (s ∩ t) :=
λ x, (closure_minimal (closure_inter_open hso) is_closed_closure) $
by simp [hs.closure_eq, ht.closure_eq]
/-- The intersection of a dense set with an open dense set is a dense set. -/
lemma dense.inter_of_open_right {s t : set α} (hs : dense s) (ht : dense t) (hto : is_open t) :
dense (s ∩ t) :=
inter_comm t s ▸ ht.inter_of_open_left hs hto
lemma dense.inter_nhds_nonempty {s t : set α} (hs : dense s) {x : α} (ht : t ∈ 𝓝 x) :
(s ∩ t).nonempty :=
let ⟨U, hsub, ho, hx⟩ := mem_nhds_iff.1 ht in
(hs.inter_open_nonempty U ho ⟨x, hx⟩).mono $ λ y hy, ⟨hy.2, hsub hy.1⟩
lemma closure_diff {s t : set α} : closure s \ closure t ⊆ closure (s \ t) :=
calc closure s \ closure t = (closure t)ᶜ ∩ closure s : by simp only [diff_eq, inter_comm]
... ⊆ closure ((closure t)ᶜ ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure
... = closure (s \ closure t) : by simp only [diff_eq, inter_comm]
... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure
lemma filter.frequently.mem_of_closed {a : α} {s : set α} (h : ∃ᶠ x in 𝓝 a, x ∈ s)
(hs : is_closed s) : a ∈ s :=
hs.closure_subset h.mem_closure
lemma is_closed.mem_of_frequently_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α}
(hs : is_closed s) (h : ∃ᶠ x in b, f x ∈ s) (hf : tendsto f b (𝓝 a)) : a ∈ s :=
(hf.frequently $ show ∃ᶠ x in b, (λ y, y ∈ s) (f x), from h).mem_of_closed hs
lemma is_closed.mem_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α}
[ne_bot b] (hs : is_closed s) (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ s :=
hs.mem_of_frequently_of_tendsto h.frequently hf
lemma mem_closure_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α}
[ne_bot b] (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ closure s :=
is_closed_closure.mem_of_tendsto hf $ h.mono (preimage_mono subset_closure)
/-- Suppose that `f` sends the complement to `s` to a single point `a`, and `l` is some filter.
Then `f` tends to `a` along `l` restricted to `s` if and only if it tends to `a` along `l`. -/
lemma tendsto_inf_principal_nhds_iff_of_forall_eq {f : β → α} {l : filter β} {s : set β}
{a : α} (h : ∀ x ∉ s, f x = a) :
tendsto f (l ⊓ 𝓟 s) (𝓝 a) ↔ tendsto f l (𝓝 a) :=
begin
rw [tendsto_iff_comap, tendsto_iff_comap],
replace h : 𝓟 sᶜ ≤ comap f (𝓝 a),
{ rintros U ⟨t, ht, htU⟩ x hx,
have : f x ∈ t, from (h x hx).symm ▸ mem_of_mem_nhds ht,
exact htU this },
refine ⟨λ h', _, le_trans inf_le_left⟩,
have := sup_le h' h,
rw [sup_inf_right, sup_principal, union_compl_self, principal_univ,
inf_top_eq, sup_le_iff] at this,
exact this.1
end
/-!
### Limits of filters in topological spaces
-/
section lim
/-- If `f` is a filter, then `Lim f` is a limit of the filter, if it exists. -/
noncomputable def Lim [nonempty α] (f : filter α) : α := epsilon $ λa, f ≤ 𝓝 a
/--
If `f` is a filter satisfying `ne_bot f`, then `Lim' f` is a limit of the filter, if it exists.
-/
def Lim' (f : filter α) [ne_bot f] : α := @Lim _ _ (nonempty_of_ne_bot f) f
/--
If `F` is an ultrafilter, then `filter.ultrafilter.Lim F` is a limit of the filter, if it exists.
Note that dot notation `F.Lim` can be used for `F : ultrafilter α`.
-/
def ultrafilter.Lim : ultrafilter α → α := λ F, Lim' F
/-- If `f` is a filter in `β` and `g : β → α` is a function, then `lim f` is a limit of `g` at `f`,
if it exists. -/
noncomputable def lim [nonempty α] (f : filter β) (g : β → α) : α :=
Lim (f.map g)
/-- If a filter `f` is majorated by some `𝓝 a`, then it is majorated by `𝓝 (Lim f)`. We formulate
this lemma with a `[nonempty α]` argument of `Lim` derived from `h` to make it useful for types
without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify
this instance with any other instance. -/
lemma le_nhds_Lim {f : filter α} (h : ∃a, f ≤ 𝓝 a) : f ≤ 𝓝 (@Lim _ _ (nonempty_of_exists h) f) :=
epsilon_spec h
/-- If `g` tends to some `𝓝 a` along `f`, then it tends to `𝓝 (lim f g)`. We formulate
this lemma with a `[nonempty α]` argument of `lim` derived from `h` to make it useful for types
without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify
this instance with any other instance. -/
lemma tendsto_nhds_lim {f : filter β} {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) :
tendsto g f (𝓝 $ @lim _ _ _ (nonempty_of_exists h) f g) :=
le_nhds_Lim h
end lim
/-!
### Locally finite families
-/
/- locally finite family [General Topology (Bourbaki, 1995)] -/
section locally_finite
/-- A family of sets in `set α` is locally finite if at every point `x:α`,
there is a neighborhood of `x` which meets only finitely many sets in the family -/
def locally_finite (f : β → set α) :=
∀x:α, ∃t ∈ 𝓝 x, finite {i | (f i ∩ t).nonempty }
lemma locally_finite.point_finite {f : β → set α} (hf : locally_finite f) (x : α) :
finite {b | x ∈ f b} :=
let ⟨t, hxt, ht⟩ := hf x in ht.subset $ λ b hb, ⟨x, hb, mem_of_mem_nhds hxt⟩
lemma locally_finite_of_fintype [fintype β] (f : β → set α) : locally_finite f :=
assume x, ⟨univ, univ_mem, finite.of_fintype _⟩
lemma locally_finite.subset
{f₁ f₂ : β → set α} (hf₂ : locally_finite f₂) (hf : ∀b, f₁ b ⊆ f₂ b) : locally_finite f₁ :=
assume a,
let ⟨t, ht₁, ht₂⟩ := hf₂ a in
⟨t, ht₁, ht₂.subset $ assume i hi, hi.mono $ inter_subset_inter (hf i) $ subset.refl _⟩
lemma locally_finite.comp_injective {ι} {f : β → set α} {g : ι → β} (hf : locally_finite f)
(hg : function.injective g) : locally_finite (f ∘ g) :=
λ x, let ⟨t, htx, htf⟩ := hf x in ⟨t, htx, htf.preimage (hg.inj_on _)⟩
lemma locally_finite.closure {f : β → set α} (hf : locally_finite f) :
locally_finite (λ i, closure (f i)) :=
begin
intro x,
rcases hf x with ⟨s, hsx, hsf⟩,
refine ⟨interior s, interior_mem_nhds.2 hsx, hsf.subset $ λ i hi, _⟩,
exact (hi.mono (closure_inter_open' is_open_interior)).of_closure.mono
(inter_subset_inter_right _ interior_subset)
end
lemma locally_finite.is_closed_Union {f : β → set α}
(h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) :=
begin
simp only [← is_open_compl_iff, compl_Union, is_open_iff_mem_nhds, mem_Inter],
intros a ha,
replace ha : ∀ i, (f i)ᶜ ∈ 𝓝 a := λ i, (h₂ i).is_open_compl.mem_nhds (ha i),
rcases h₁ a with ⟨t, h_nhds, h_fin⟩,
have : t ∩ (⋂ i ∈ {i | (f i ∩ t).nonempty}, (f i)ᶜ) ∈ 𝓝 a,
from inter_mem h_nhds ((bInter_mem h_fin).2 (λ i _, ha i)),
filter_upwards [this],
simp only [mem_inter_eq, mem_Inter],
rintros b ⟨hbt, hn⟩ i hfb,
exact hn i ⟨b, hfb, hbt⟩ hfb
end
lemma locally_finite.closure_Union {f : β → set α} (h : locally_finite f) :
closure (⋃ i, f i) = ⋃ i, closure (f i) :=
subset.antisymm
(closure_minimal (Union_subset_Union $ λ _, subset_closure) $
h.closure.is_closed_Union $ λ _, is_closed_closure)
(Union_subset $ λ i, closure_mono $ subset_Union _ _)
end locally_finite
end topological_space
/-!
### Continuity
-/
section continuous
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
variables [topological_space α] [topological_space β] [topological_space γ]
open_locale topological_space
/-- A function between topological spaces is continuous if the preimage
of every open set is open. Registered as a structure to make sure it is not unfolded by Lean. -/
structure continuous (f : α → β) : Prop :=
(is_open_preimage : ∀s, is_open s → is_open (f ⁻¹' s))
lemma continuous_def {f : α → β} : continuous f ↔ (∀s, is_open s → is_open (f ⁻¹' s)) :=
⟨λ hf s hs, hf.is_open_preimage s hs, λ h, ⟨h⟩⟩
lemma is_open.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_open s) :
is_open (f ⁻¹' s) :=
hf.is_open_preimage s h
/-- A function between topological spaces is continuous at a point `x₀`
if `f x` tends to `f x₀` when `x` tends to `x₀`. -/
def continuous_at (f : α → β) (x : α) := tendsto f (𝓝 x) (𝓝 (f x))
lemma continuous_at.tendsto {f : α → β} {x : α} (h : continuous_at f x) :
tendsto f (𝓝 x) (𝓝 (f x)) :=
h
lemma continuous_at_congr {f g : α → β} {x : α} (h : f =ᶠ[𝓝 x] g) :
continuous_at f x ↔ continuous_at g x :=
by simp only [continuous_at, tendsto_congr' h, h.eq_of_nhds]
lemma continuous_at.congr {f g : α → β} {x : α} (hf : continuous_at f x) (h : f =ᶠ[𝓝 x] g) :
continuous_at g x :=
(continuous_at_congr h).1 hf
lemma continuous_at.preimage_mem_nhds {f : α → β} {x : α} {t : set β} (h : continuous_at f x)
(ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝 x :=
h ht
lemma eventually_eq_zero_nhds {M₀} [has_zero M₀] {a : α} {f : α → M₀} :
f =ᶠ[𝓝 a] 0 ↔ a ∉ closure (function.support f) :=
by rw [← mem_compl_eq, ← interior_compl, mem_interior_iff_mem_nhds, function.compl_support]; refl
lemma cluster_pt.map {x : α} {la : filter α} {lb : filter β} (H : cluster_pt x la)
{f : α → β} (hfc : continuous_at f x) (hf : tendsto f la lb) :
cluster_pt (f x) lb :=
⟨ne_bot_of_le_ne_bot ((map_ne_bot_iff f).2 H).ne $ hfc.tendsto.inf hf⟩
/-- See also `interior_preimage_subset_preimage_interior`. -/
lemma preimage_interior_subset_interior_preimage {f : α → β} {s : set β}
(hf : continuous f) : f⁻¹' (interior s) ⊆ interior (f⁻¹' s) :=
interior_maximal (preimage_mono interior_subset) (is_open_interior.preimage hf)
lemma continuous_id : continuous (id : α → α) :=
continuous_def.2 $ assume s h, h
lemma continuous.comp {g : β → γ} {f : α → β} (hg : continuous g) (hf : continuous f) :
continuous (g ∘ f) :=
continuous_def.2 $ assume s h, (h.preimage hg).preimage hf
lemma continuous.iterate {f : α → α} (h : continuous f) (n : ℕ) : continuous (f^[n]) :=
nat.rec_on n continuous_id (λ n ihn, ihn.comp h)
lemma continuous_at.comp {g : β → γ} {f : α → β} {x : α}
(hg : continuous_at g (f x)) (hf : continuous_at f x) :
continuous_at (g ∘ f) x :=
hg.comp hf
lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) :
tendsto f (𝓝 x) (𝓝 (f x)) :=
((nhds_basis_opens x).tendsto_iff $ nhds_basis_opens $ f x).2 $
λ t ⟨hxt, ht⟩, ⟨f ⁻¹' t, ⟨hxt, ht.preimage hf⟩, subset.refl _⟩
/-- A version of `continuous.tendsto` that allows one to specify a simpler form of the limit.
E.g., one can write `continuous_exp.tendsto' 0 1 exp_zero`. -/
lemma continuous.tendsto' {f : α → β} (hf : continuous f) (x : α) (y : β) (h : f x = y) :
tendsto f (𝓝 x) (𝓝 y) :=
h ▸ hf.tendsto x
lemma continuous.continuous_at {f : α → β} {x : α} (h : continuous f) :
continuous_at f x :=
h.tendsto x
lemma continuous_iff_continuous_at {f : α → β} : continuous f ↔ ∀ x, continuous_at f x :=
⟨continuous.tendsto,
assume hf : ∀x, tendsto f (𝓝 x) (𝓝 (f x)),
continuous_def.2 $
assume s, assume hs : is_open s,
have ∀a, f a ∈ s → s ∈ 𝓝 (f a),
from λ a ha, is_open.mem_nhds hs ha,
show is_open (f ⁻¹' s),
from is_open_iff_nhds.2 $ λ a ha, le_principal_iff.2 $ hf _ (this a ha)⟩
lemma continuous_at_const {x : α} {b : β} : continuous_at (λ a:α, b) x :=
tendsto_const_nhds
lemma continuous_const {b : β} : continuous (λa:α, b) :=
continuous_iff_continuous_at.mpr $ assume a, continuous_at_const
lemma filter.eventually_eq.continuous_at {x : α} {f : α → β} {y : β} (h : f =ᶠ[𝓝 x] (λ _, y)) :
continuous_at f x :=
(continuous_at_congr h).2 tendsto_const_nhds
lemma continuous_of_const {f : α → β} (h : ∀ x y, f x = f y) : continuous f :=
continuous_iff_continuous_at.mpr $ λ x, filter.eventually_eq.continuous_at $
eventually_of_forall (λ y, h y x)
lemma continuous_at_id {x : α} : continuous_at id x :=
continuous_id.continuous_at
lemma continuous_at.iterate {f : α → α} {x : α} (hf : continuous_at f x) (hx : f x = x) (n : ℕ) :
continuous_at (f^[n]) x :=
nat.rec_on n continuous_at_id $ λ n ihn,
show continuous_at (f^[n] ∘ f) x,
from continuous_at.comp (hx.symm ▸ ihn) hf
lemma continuous_iff_is_closed {f : α → β} :
continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) :=
⟨assume hf s hs, by simpa using (continuous_def.1 hf sᶜ hs.is_open_compl).is_closed_compl,
assume hf, continuous_def.2 $ assume s,
by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩
lemma is_closed.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_closed s) :
is_closed (f ⁻¹' s) :=
continuous_iff_is_closed.mp hf s h
lemma mem_closure_image {f : α → β} {x : α} {s : set α} (hf : continuous_at f x)
(hx : x ∈ closure s) : f x ∈ closure (f '' s) :=
begin
rw [mem_closure_iff_nhds_ne_bot] at hx ⊢,
rw ← bot_lt_iff_ne_bot,
haveI : ne_bot _ := ⟨hx⟩,
calc
⊥ < map f (𝓝 x ⊓ principal s) : bot_lt_iff_ne_bot.mpr ne_bot.ne'
... ≤ (map f $ 𝓝 x) ⊓ (map f $ principal s) : map_inf_le
... = (map f $ 𝓝 x) ⊓ (principal $ f '' s) : by rw map_principal
... ≤ 𝓝 (f x) ⊓ (principal $ f '' s) : inf_le_inf hf le_rfl
end
lemma continuous_at_iff_ultrafilter {f : α → β} {x} : continuous_at f x ↔
∀ g : ultrafilter α, ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) :=
tendsto_iff_ultrafilter f (𝓝 x) (𝓝 (f x))
lemma continuous_iff_ultrafilter {f : α → β} :
continuous f ↔ ∀ x (g : ultrafilter α), ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) :=
by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter]
lemma continuous.closure_preimage_subset {f : α → β}
(hf : continuous f) (t : set β) :
closure (f ⁻¹' t) ⊆ f ⁻¹' (closure t) :=
begin
rw ← (is_closed_closure.preimage hf).closure_eq,
exact closure_mono (preimage_mono subset_closure),
end
lemma continuous.frontier_preimage_subset
{f : α → β} (hf : continuous f) (t : set β) :
frontier (f ⁻¹' t) ⊆ f ⁻¹' (frontier t) :=
diff_subset_diff (hf.closure_preimage_subset t) (preimage_interior_subset_interior_preimage hf)
/-! ### Continuity and partial functions -/
/-- Continuity of a partial function -/
def pcontinuous (f : α →. β) := ∀ s, is_open s → is_open (f.preimage s)
lemma open_dom_of_pcontinuous {f : α →. β} (h : pcontinuous f) : is_open f.dom :=
by rw [←pfun.preimage_univ]; exact h _ is_open_univ
lemma pcontinuous_iff' {f : α →. β} :
pcontinuous f ↔ ∀ {x y} (h : y ∈ f x), ptendsto' f (𝓝 x) (𝓝 y) :=
begin
split,
{ intros h x y h',
simp only [ptendsto'_def, mem_nhds_iff],
rintros s ⟨t, tsubs, opent, yt⟩,
exact ⟨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩ },
intros hf s os,
rw is_open_iff_nhds,
rintros x ⟨y, ys, fxy⟩ t,
rw [mem_principal],
assume h : f.preimage s ⊆ t,
change t ∈ 𝓝 x,
apply mem_of_superset _ h,
have h' : ∀ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x,
{ intros s hs,
have : ptendsto' f (𝓝 x) (𝓝 y) := hf fxy,
rw ptendsto'_def at this,
exact this s hs },
show f.preimage s ∈ 𝓝 x,
apply h', rw mem_nhds_iff, exact ⟨s, set.subset.refl _, os, ys⟩
end
/-- If a continuous map `f` maps `s` to `t`, then it maps `closure s` to `closure t`. -/
lemma set.maps_to.closure {s : set α} {t : set β} {f : α → β} (h : maps_to f s t)
(hc : continuous f) : maps_to f (closure s) (closure t) :=
begin
simp only [maps_to, mem_closure_iff_cluster_pt],
exact λ x hx, hx.map hc.continuous_at (tendsto_principal_principal.2 h)
end
lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) :
f '' closure s ⊆ closure (f '' s) :=
((maps_to_image f s).closure h).image_subset
lemma closure_subset_preimage_closure_image {f : α → β} {s : set α} (h : continuous f) :
closure s ⊆ f ⁻¹' (closure (f '' s)) :=
by { rw ← set.image_subset_iff, exact image_closure_subset_closure_image h }
lemma map_mem_closure {s : set α} {t : set β} {f : α → β} {a : α}
(hf : continuous f) (ha : a ∈ closure s) (ht : ∀a∈s, f a ∈ t) : f a ∈ closure t :=
set.maps_to.closure ht hf ha
/-!
### Function with dense range
-/
section dense_range
variables {κ ι : Type*} (f : κ → β) (g : β → γ)
/-- `f : ι → β` has dense range if its range (image) is a dense subset of β. -/
def dense_range := dense (range f)
variables {f}
/-- A surjective map has dense range. -/
lemma function.surjective.dense_range (hf : function.surjective f) : dense_range f :=
λ x, by simp [hf.range_eq]
lemma dense_range_iff_closure_range : dense_range f ↔ closure (range f) = univ :=
dense_iff_closure_eq
lemma dense_range.closure_range (h : dense_range f) : closure (range f) = univ :=
h.closure_eq
lemma dense.dense_range_coe {s : set α} (h : dense s) : dense_range (coe : s → α) :=
by simpa only [dense_range, subtype.range_coe_subtype]
lemma continuous.range_subset_closure_image_dense {f : α → β} (hf : continuous f)
{s : set α} (hs : dense s) :
range f ⊆ closure (f '' s) :=
by { rw [← image_univ, ← hs.closure_eq], exact image_closure_subset_closure_image hf }
/-- The image of a dense set under a continuous map with dense range is a dense set. -/
lemma dense_range.dense_image {f : α → β} (hf' : dense_range f) (hf : continuous f)
{s : set α} (hs : dense s) :
dense (f '' s) :=
(hf'.mono $ hf.range_subset_closure_image_dense hs).of_closure
/-- If `f` has dense range and `s` is an open set in the codomain of `f`, then the image of the
preimage of `s` under `f` is dense in `s`. -/
lemma dense_range.subset_closure_image_preimage_of_is_open (hf : dense_range f) {s : set β}
(hs : is_open s) : s ⊆ closure (f '' (f ⁻¹' s)) :=
by { rw image_preimage_eq_inter_range, exact hf.open_subset_closure_inter hs }
/-- If a continuous map with dense range maps a dense set to a subset of `t`, then `t` is a dense
set. -/
lemma dense_range.dense_of_maps_to {f : α → β} (hf' : dense_range f) (hf : continuous f)
{s : set α} (hs : dense s) {t : set β} (ht : maps_to f s t) :
dense t :=
(hf'.dense_image hf hs).mono ht.image_subset
/-- Composition of a continuous map with dense range and a function with dense range has dense
range. -/
lemma dense_range.comp {g : β → γ} {f : κ → β} (hg : dense_range g) (hf : dense_range f)
(cg : continuous g) :
dense_range (g ∘ f) :=
by { rw [dense_range, range_comp], exact hg.dense_image cg hf }
lemma dense_range.nonempty_iff (hf : dense_range f) : nonempty κ ↔ nonempty β :=
range_nonempty_iff_nonempty.symm.trans hf.nonempty_iff
lemma dense_range.nonempty [h : nonempty β] (hf : dense_range f) : nonempty κ :=
hf.nonempty_iff.mpr h
/-- Given a function `f : α → β` with dense range and `b : β`, returns some `a : α`. -/
def dense_range.some (hf : dense_range f) (b : β) : κ :=
classical.choice $ hf.nonempty_iff.mpr ⟨b⟩
lemma dense_range.exists_mem_open (hf : dense_range f) {s : set β} (ho : is_open s)
(hs : s.nonempty) :
∃ a, f a ∈ s :=
exists_range_iff.1 $ hf.exists_mem_open ho hs
lemma dense_range.mem_nhds {f : κ → β} (h : dense_range f) {b : β} {U : set β}
(U_in : U ∈ nhds b) : ∃ a, f a ∈ U :=
begin
rcases (mem_closure_iff_nhds.mp
((dense_range_iff_closure_range.mp h).symm ▸ mem_univ b : b ∈ closure (range f)) U U_in)
with ⟨_, h, a, rfl⟩,
exact ⟨a, h⟩
end
end dense_range
end continuous
/--
The library contains many lemmas stating that functions/operations are continuous. There are many
ways to formulate the continuity of operations. Some are more convenient than others.
Note: for the most part this note also applies to other properties
(`measurable`, `differentiable`, `continuous_on`, ...).
### The traditional way
As an example, let's look at addition `(+) : M → M → M`. We can state that this is continuous
in different definitionally equal ways (omitting some typing information)
* `continuous (λ p, p.1 + p.2)`;
* `continuous (function.uncurry (+))`;
* `continuous ↿(+)`. (`↿` is notation for recursively uncurrying a function)
However, lemmas with this conclusion are not nice to use in practice because
1. They confuse the elaborator. The following two examples fail, because of limitations in the
elaboration process.
```
variables {M : Type*} [has_mul M] [topological_space M] [has_continuous_mul M]
example : continuous (λ x : M, x + x) :=
continuous_add.comp _
example : continuous (λ x : M, x + x) :=
continuous_add.comp (continuous_id.prod_mk continuous_id)
```
The second is a valid proof, which is accepted if you write it as
`continuous_add.comp (continuous_id.prod_mk continuous_id : _)`
2. If the operation has more than 2 arguments, they are impractical to use, because in your
application the arguments in the domain might be in a different order or associated differently.
### The convenient way
A much more convenient way to write continuity lemmas is like `continuous.add`:
```
continuous.add {f g : X → M} (hf : continuous f) (hg : continuous g) : continuous (λ x, f x + g x)
```
The conclusion can be `continuous (f + g)`, which is definitionally equal.
This has the following advantages
* It supports projection notation, so is shorter to write.
* `continuous.add _ _` is recognized correctly by the elaborator and gives useful new goals.
* It works generally, since the domain is a variable.
As an example for an unary operation, we have `continuous.neg`.
```
continuous.neg {f : α → G} (hf : continuous f) : continuous (λ x, -f x)
```
For unary functions, the elaborator is not confused when applying the traditional lemma
(like `continuous_neg`), but it's still convenient to have the short version available (compare
`hf.neg.neg.neg` with `continuous_neg.comp $ continuous_neg.comp $ continuous_neg.comp hf`).
As a harder example, consider an operation of the following type:
```
def strans {x : F} (γ γ' : path x x) (t₀ : I) : path x x
```
The precise definition is not important, only its type.
The correct continuity principle for this operation is something like this:
```
{f : X → F} {γ γ' : ∀ x, path (f x) (f x)} {t₀ s : X → I}
(hγ : continuous ↿γ) (hγ' : continuous ↿γ')
(ht : continuous t₀) (hs : continuous s) :
continuous (λ x, strans (γ x) (γ' x) (t x) (s x))
```
Note that *all* arguments of `strans` are indexed over `X`, even the basepoint `x`, and the last
argument `s` that arises since `path x x` has a coercion to `I → F`. The paths `γ` and `γ'` (which
are unary functions from `I`) become binary functions in the continuity lemma.
### Summary
* Make sure that your continuity lemmas are stated in the most general way, and in a convenient
form. That means that:
- The conclusion has a variable `X` as domain (not something like `Y × Z`);
- Wherever possible, all point arguments `c : Y` are replaced by functions `c : X → Y`;
- All `n`-ary function arguments are replaced by `n+1`-ary functions
(`f : Y → Z` becomes `f : X → Y → Z`);
- All (relevant) arguments have continuity assumptions, and perhaps there are additional
assumptions needed to make the operation continuous;
- The function in the conclusion is fully applied.
* These remarks are mostly about the format of the *conclusion* of a continuity lemma.
In assumptions it's fine to state that a function with more than 1 argument is continuous using
`↿` or `function.uncurry`.
### Functions with discontinuities
In some cases, you want to work with discontinuous functions, and in certain expressions they are
still continuous. For example, consider the fractional part of a number, `fract : ℝ → ℝ`.
In this case, you want to add conditions to when a function involving `fract` is continuous, so you
get something like this: (assumption `hf` could be weakened, but the important thing is the shape
of the conclusion)
```
lemma continuous_on.comp_fract {X Y : Type*} [topological_space X] [topological_space Y]
{f : X → ℝ → Y} {g : X → ℝ} (hf : continuous ↿f) (hg : continuous g) (h : ∀ s, f s 0 = f s 1) :
continuous (λ x, f x (fract (g x)))
```
With `continuous_at` you can be even more precise about what to prove in case of discontinuities,
see e.g. `continuous_at.comp_div_cases`.
-/
library_note "continuity lemma statement"
|
21d2fe2c80c51c995ccbc03780688f8a5dbdddec
|
f20db13587f4dd28a4b1fbd31953afd491691fa0
|
/library/init/meta/lean/parser.lean
|
a1e305ddfd3e88d16c2b6146333a2a0297a87aef
|
[
"Apache-2.0"
] |
permissive
|
AHartNtkn/lean
|
9a971edfc6857c63edcbf96bea6841b9a84cf916
|
0d83a74b26541421fc1aa33044c35b03759710ed
|
refs/heads/master
| 1,620,592,591,236
| 1,516,749,881,000
| 1,516,749,881,000
| 118,697,288
| 1
| 0
| null | 1,516,759,470,000
| 1,516,759,470,000
| null |
UTF-8
|
Lean
| false
| false
| 3,156
|
lean
|
/-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
prelude
import init.meta.tactic
namespace lean
-- TODO: make inspectable (and pure)
meta constant parser_state : Type
meta constant parser_state.env : parser_state → environment
meta constant parser_state.options : parser_state → options
meta constant parser_state.cur_pos : parser_state → pos
@[reducible] meta def parser := interaction_monad parser_state
@[reducible] meta def parser_result := interaction_monad.result parser_state
open interaction_monad
open interaction_monad.result
namespace parser
variable {α : Type}
meta constant set_env : environment → parser unit
/-- Make sure the next token is an identifier, consume it, and
produce the quoted name `t, where t is the identifier. -/
meta constant ident : parser name
/-- Make sure the next token is a small nat, consume it, and produce it -/
meta constant small_nat : parser nat
/-- Check that the next token is `tk` and consume it. `tk` must be a registered token. -/
meta constant tk (tk : string) : parser unit
/-- Parse an unelaborated expression using the given right-binding power. -/
protected meta constant pexpr (rbp := std.prec.max) : parser pexpr
/-- Do not report info from content parsed by `p`. -/
meta constant skip_info (p : parser α) : parser α
/-- Set goal info position of content parsed by `p` to current position. Nested calls take precedence. -/
meta constant set_goal_info_pos (p : parser α) : parser α
/-- Return the current parser position without consuming any input. -/
meta def cur_pos : parser pos := λ s, success (parser_state.cur_pos s) s
/-- Temporarily replace input of the parser state, run `p`, and return remaining input. -/
meta constant with_input (p : parser α) (input : string) : parser (α × string)
/-- Parse a top-level command. -/
meta constant command_like : parser unit
meta def parser_orelse (p₁ p₂ : parser α) : parser α :=
λ s,
let pos₁ := parser_state.cur_pos s in
result.cases_on (p₁ s)
success
(λ e₁ ref₁ s',
let pos₂ := parser_state.cur_pos s' in
if pos₁ ≠ pos₂ then
exception e₁ ref₁ s'
else result.cases_on (p₂ s)
success
exception)
meta instance : alternative parser :=
{ failure := @interaction_monad.failed _,
orelse := @parser_orelse,
..interaction_monad.monad }
-- TODO: move
meta def {u v} many {f : Type u → Type v} [monad f] [alternative f] {a : Type u} : f a → f (list a)
| x := (do y ← x,
ys ← many x,
return $ y::ys) <|> pure list.nil
local postfix `?`:100 := optional
local postfix `*`:100 := many
meta def sep_by : parser unit → parser α → parser (list α)
| s p := (list.cons <$> p <*> (s *> p)*) <|> return []
meta def tactic_to_parser : tactic α → parser α :=
λ t s, match t (tactic_state.mk_empty s.env s.options) with
| success x ts := (set_env ts.env >> pure x) s
| exception f p _ := exception f p s
end
meta instance : has_coe (tactic α) (parser α) :=
⟨tactic_to_parser⟩
end parser
end lean
|
9618c4214b108133dfcbfa679f72b231d8228fd4
|
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
|
/src/order/filter/basic.lean
|
96a927b27eb7db751b86611bb4b3656473f5f0e8
|
[
"Apache-2.0"
] |
permissive
|
johoelzl/mathlib
|
253f46daa30b644d011e8e119025b01ad69735c4
|
592e3c7a2dfbd5826919b4605559d35d4d75938f
|
refs/heads/master
| 1,625,657,216,488
| 1,551,374,946,000
| 1,551,374,946,000
| 98,915,829
| 0
| 0
|
Apache-2.0
| 1,522,917,267,000
| 1,501,524,499,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 79,639
|
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, Jeremy Avigad
Theory of filters on sets.
-/
import order.galois_connection order.zorn
import data.set.finite data.list data.pfun
import algebra.pi_instances
import category.applicative
open lattice set
universes u v w x y
local attribute [instance] classical.prop_decidable
namespace lattice
variables {α : Type u} {ι : Sort v}
def complete_lattice.copy (c : complete_lattice α)
(le : α → α → Prop) (eq_le : le = @complete_lattice.le α c)
(top : α) (eq_top : top = @complete_lattice.top α c)
(bot : α) (eq_bot : bot = @complete_lattice.bot α c)
(sup : α → α → α) (eq_sup : sup = @complete_lattice.sup α c)
(inf : α → α → α) (eq_inf : inf = @complete_lattice.inf α c)
(Sup : set α → α) (eq_Sup : Sup = @complete_lattice.Sup α c)
(Inf : set α → α) (eq_Inf : Inf = @complete_lattice.Inf α c) :
complete_lattice α :=
begin
refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, ..};
subst_vars,
exact @complete_lattice.le_refl α c,
exact @complete_lattice.le_trans α c,
exact @complete_lattice.le_antisymm α c,
exact @complete_lattice.le_sup_left α c,
exact @complete_lattice.le_sup_right α c,
exact @complete_lattice.sup_le α c,
exact @complete_lattice.inf_le_left α c,
exact @complete_lattice.inf_le_right α c,
exact @complete_lattice.le_inf α c,
exact @complete_lattice.le_top α c,
exact @complete_lattice.bot_le α c,
exact @complete_lattice.le_Sup α c,
exact @complete_lattice.Sup_le α c,
exact @complete_lattice.Inf_le α c,
exact @complete_lattice.le_Inf α c
end
end lattice
open set lattice
section order
variables {α : Type u} (r : α → α → Prop)
local infix `≼` : 50 := r
lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊆) f)
(h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) :=
by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact
assume a₁ b₁ fb₁ a₂ b₂ fb₂,
let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂,
⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in
⟨x, ⟨z, xf⟩, xa₁, xa₂⟩
end order
theorem directed_of_chain {α β r} [is_refl β r] {f : α → β} {c : set α}
(h : zorn.chain (f ⁻¹'o r) c) :
directed r (λx:{a:α // a ∈ c}, f (x.val)) :=
assume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases
(assume : a = b, by simp only [this, exists_prop, and_self, subtype.exists];
exact ⟨b, hb, refl _⟩)
(assume : a ≠ b, (h a ha b hb this).elim
(λ h : r (f a) (f b), ⟨⟨b, hb⟩, h, refl _⟩)
(λ h : r (f b) (f a), ⟨⟨a, ha⟩, refl _, h⟩))
structure filter (α : Type*) :=
(sets : set (set α))
(univ_sets : set.univ ∈ sets)
(sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets)
(inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets)
namespace filter
variables {α : Type u} {f g : filter α} {s t : set α}
lemma filter_eq : ∀{f g : filter α}, f.sets = g.sets → f = g
| ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl
lemma filter_eq_iff : f = g ↔ f.sets = g.sets :=
⟨congr_arg _, filter_eq⟩
protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f.sets ↔ s ∈ g.sets :=
by rw [filter_eq_iff, ext_iff]
@[extensionality]
protected lemma ext : (∀ s, s ∈ f.sets ↔ s ∈ g.sets) → f = g :=
filter.ext_iff.2
lemma univ_mem_sets : univ ∈ f.sets :=
f.univ_sets
lemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f.sets → x ⊆ y → y ∈ f.sets :=
f.sets_of_superset
lemma inter_mem_sets : ∀{s t}, s ∈ f.sets → t ∈ f.sets → s ∩ t ∈ f.sets :=
f.inter_sets
lemma univ_mem_sets' (h : ∀ a, a ∈ s): s ∈ f.sets :=
mem_sets_of_superset univ_mem_sets (assume x _, h x)
lemma mp_sets (hs : s ∈ f.sets) (h : {x | x ∈ s → x ∈ t} ∈ f.sets) : t ∈ f.sets :=
mem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁
lemma Inter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) :
(∀i∈is, s i ∈ f.sets) → (⋂i∈is, s i) ∈ f.sets :=
finite.induction_on hf
(assume hs, by simp only [univ_mem_sets, mem_empty_eq, Inter_neg, Inter_univ, not_false_iff])
(assume i is _ hf hi hs,
have h₁ : s i ∈ f.sets, from hs i (by simp),
have h₂ : (⋂x∈is, s x) ∈ f.sets, from hi $ assume a ha, hs _ $ by simp only [ha, mem_insert_iff, or_true],
by simp [inter_mem_sets h₁ h₂])
lemma exists_sets_subset_iff : (∃t∈f.sets, t ⊆ s) ↔ s ∈ f.sets :=
⟨assume ⟨t, ht, ts⟩, mem_sets_of_superset ht ts, assume hs, ⟨s, hs, subset.refl _⟩⟩
lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f.sets) :=
assume s t hst h, mem_sets_of_superset h hst
end filter
namespace tactic.interactive
open tactic interactive
/-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f.sets`
and terms `h1 : t1 ∈ f.sets, ⋯, hn : tn ∈ f.sets` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`.
`filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], exact e }`.
-/
meta def filter_upwards
(s : parse types.pexpr_list)
(e' : parse $ optional types.texpr) : tactic unit :=
do
s.reverse.mmap (λ e, eapplyc `filter.mp_sets >> eapply e),
eapplyc `filter.univ_mem_sets',
match e' with
| some e := interactive.exact e
| none := skip
end
end tactic.interactive
namespace filter
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}
section principal
/-- The principal filter of `s` is the collection of all supersets of `s`. -/
def principal (s : set α) : filter α :=
{ sets := {t | s ⊆ t},
univ_sets := subset_univ s,
sets_of_superset := assume x y hx hy, subset.trans hx hy,
inter_sets := assume x y, subset_inter }
instance : inhabited (filter α) :=
⟨principal ∅⟩
@[simp] lemma mem_principal_sets {s t : set α} : s ∈ (principal t).sets ↔ t ⊆ s := iff.rfl
lemma mem_principal_self (s : set α) : s ∈ (principal s).sets := subset.refl _
end principal
section join
/-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/
def join (f : filter (filter α)) : filter α :=
{ sets := {s | {t : filter α | s ∈ t.sets} ∈ f.sets},
univ_sets := by simp only [univ_mem_sets, mem_set_of_eq]; exact univ_mem_sets,
sets_of_superset := assume x y hx xy,
mem_sets_of_superset hx $ assume f h, mem_sets_of_superset h xy,
inter_sets := assume x y hx hy,
mem_sets_of_superset (inter_mem_sets hx hy) $ assume f ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂ }
@[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} :
s ∈ (join f).sets ↔ {t | s ∈ filter.sets t} ∈ f.sets := iff.rfl
end join
section lattice
instance : partial_order (filter α) :=
{ le := λf g, g.sets ⊆ f.sets,
le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁,
le_refl := assume a, subset.refl _,
le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ }
theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g.sets, x ∈ f.sets := iff.rfl
/-- `generate_sets g s`: `s` is in the filter closure of `g`. -/
inductive generate_sets (g : set (set α)) : set α → Prop
| basic {s : set α} : s ∈ g → generate_sets s
| univ {} : generate_sets univ
| superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t
| inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t)
/-- `generate g` is the smallest filter containing the sets `g`. -/
def generate (g : set (set α)) : filter α :=
{ sets := {s | generate_sets g s},
univ_sets := generate_sets.univ,
sets_of_superset := assume x y, generate_sets.superset,
inter_sets := assume s t, generate_sets.inter }
lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets :=
iff.intro
(assume h u hu, h $ generate_sets.basic $ hu)
(assume h u hu, hu.rec_on h univ_mem_sets
(assume x y _ hxy hx, mem_sets_of_superset hx hxy)
(assume x y _ _ hx hy, inter_mem_sets hx hy))
protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α :=
{ sets := s,
univ_sets := hs ▸ univ_mem_sets,
sets_of_superset := assume x y, hs ▸ mem_sets_of_superset,
inter_sets := assume x y, hs ▸ inter_mem_sets }
lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} :
filter.mk_of_closure s hs = generate s :=
filter.ext $ assume u, hs.symm ▸ iff.refl _
/- Galois insertion from sets of sets into a filters. -/
def gi_generate (α : Type*) :
@galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets :=
{ gc := assume s f, sets_iff_generate,
le_l_u := assume f u, generate_sets.basic,
choice := λs hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_refl _),
choice_eq := assume s hs, mk_of_closure_sets }
/-- The infimum of filters is the filter generated by intersections
of elements of the two filters. -/
instance : has_inf (filter α) := ⟨λf g : filter α,
{ sets := {s | ∃ (a ∈ f.sets) (b ∈ g.sets), a ∩ b ⊆ s },
univ_sets := ⟨_, univ_mem_sets, _, univ_mem_sets, inter_subset_left _ _⟩,
sets_of_superset := assume x y ⟨a, ha, b, hb, h⟩ xy, ⟨a, ha, b, hb, subset.trans h xy⟩,
inter_sets := assume x y ⟨a, ha, b, hb, hx⟩ ⟨c, hc, d, hd, hy⟩,
⟨_, inter_mem_sets ha hc, _, inter_mem_sets hb hd,
calc a ∩ c ∩ (b ∩ d) = (a ∩ b) ∩ (c ∩ d) : by ac_refl
... ⊆ x ∩ y : inter_subset_inter hx hy⟩ }⟩
@[simp] lemma mem_inf_sets {f g : filter α} {s : set α} :
s ∈ (f ⊓ g).sets ↔ ∃t₁∈f.sets, ∃t₂∈g.sets, t₁ ∩ t₂ ⊆ s := iff.rfl
lemma mem_inf_sets_of_left {f g : filter α} {s : set α} (h : s ∈ f.sets) : s ∈ (f ⊓ g).sets :=
⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩
lemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g.sets) : s ∈ (f ⊓ g).sets :=
⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩
lemma inter_mem_inf_sets {α : Type u} {f g : filter α} {s t : set α}
(hs : s ∈ f.sets) (ht : t ∈ g.sets) : s ∩ t ∈ (f ⊓ g).sets :=
inter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht)
instance : has_top (filter α) :=
⟨{ sets := {s | ∀x, x ∈ s},
univ_sets := assume x, mem_univ x,
sets_of_superset := assume x y hx hxy a, hxy (hx a),
inter_sets := assume x y hx hy a, mem_inter (hx _) (hy _) }⟩
lemma mem_top_sets_iff_forall {s : set α} : s ∈ (⊤ : filter α).sets ↔ (∀x, x ∈ s) :=
iff.refl _
@[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α).sets ↔ s = univ :=
by rw [mem_top_sets_iff_forall, eq_univ_iff_forall]
section complete_lattice
/- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately,
we want to have different definitional equalities for the lattice operations. So we define them
upfront and change the lattice operations for the complete lattice instance. -/
private def original_complete_lattice : complete_lattice (filter α) :=
@order_dual.lattice.complete_lattice _ (gi_generate α).lift_complete_lattice
local attribute [instance] original_complete_lattice
instance : complete_lattice (filter α) := original_complete_lattice.copy
/- le -/ filter.partial_order.le rfl
/- top -/ (filter.lattice.has_top).1
(top_unique $ assume s hs, (eq_univ_of_forall hs).symm ▸ univ_mem_sets)
/- bot -/ _ rfl
/- sup -/ _ rfl
/- inf -/ (filter.lattice.has_inf).1
begin
ext f g : 2,
exact le_antisymm
(le_inf (assume s, mem_inf_sets_of_left) (assume s, mem_inf_sets_of_right))
(assume s ⟨a, ha, b, hb, hs⟩, mem_sets_of_superset (inter_mem_sets
(@inf_le_left (filter α) _ _ _ _ ha)
(@inf_le_right (filter α) _ _ _ _ hb)) hs)
end
/- Sup -/ (join ∘ principal) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm)
/- Inf -/ _ rfl
end complete_lattice
lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl
lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets :=
(gi_generate α).gc.u_inf
lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂f∈s, (f:filter α).sets) :=
(gi_generate α).gc.u_Inf
lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) :=
(gi_generate α).gc.u_infi
lemma generate_empty : filter.generate ∅ = (⊤ : filter α) :=
(gi_generate α).gc.l_bot
lemma generate_univ : filter.generate univ = (⊥ : filter α) :=
mk_of_closure_sets.symm
lemma generate_union {s t : set (set α)} :
filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t :=
(gi_generate α).gc.l_sup
lemma generate_Union {s : ι → set (set α)} :
filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) :=
(gi_generate α).gc.l_supr
@[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α).sets :=
trivial
@[simp] lemma mem_sup_sets {f g : filter α} {s : set α} :
s ∈ (f ⊔ g).sets ↔ s ∈ f.sets ∧ s ∈ g.sets :=
iff.rfl
@[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} :
x ∈ (Sup s).sets ↔ (∀f∈s, x ∈ (f:filter α).sets) :=
iff.rfl
@[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} :
x ∈ (supr f).sets ↔ (∀i, x ∈ (f i).sets) :=
by simp only [supr_sets_eq, iff_self, mem_Inter]
@[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ principal s ↔ s ∈ f.sets :=
show (∀{t}, s ⊆ t → t ∈ f.sets) ↔ s ∈ f.sets,
from ⟨assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht⟩
lemma principal_mono {s t : set α} : principal s ≤ principal t ↔ s ⊆ t :=
by simp only [le_principal_iff, iff_self, mem_principal_sets]
lemma monotone_principal : monotone (principal : set α → filter α) :=
by simp only [monotone, principal_mono]; exact assume a b h, h
@[simp] lemma principal_eq_iff_eq {s t : set α} : principal s = principal t ↔ s = t :=
by simp only [le_antisymm_iff, le_principal_iff, mem_principal_sets]; refl
@[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (principal s) = Sup s := rfl
/- lattice equations -/
lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f.sets ↔ f = ⊥ :=
⟨assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s),
assume : f = ⊥, this.symm ▸ mem_bot_sets⟩
lemma inhabited_of_mem_sets {f : filter α} {s : set α} (hf : f ≠ ⊥) (hs : s ∈ f.sets) :
∃x, x ∈ s :=
have ∅ ∉ f.sets, from assume h, hf $ empty_in_sets_eq_bot.mp h,
have s ≠ ∅, from assume h, this (h ▸ hs),
exists_mem_of_ne_empty this
lemma filter_eq_bot_of_not_nonempty {f : filter α} (ne : ¬ nonempty α) : f = ⊥ :=
empty_in_sets_eq_bot.mp $ univ_mem_sets' $ assume x, false.elim (ne ⟨x⟩)
lemma forall_sets_neq_empty_iff_neq_bot {f : filter α} :
(∀ (s : set α), s ∈ f.sets → s ≠ ∅) ↔ f ≠ ⊥ :=
by
simp only [(@empty_in_sets_eq_bot α f).symm, ne.def];
exact ⟨assume h hs, h _ hs rfl, assume h s hs eq, h $ eq ▸ hs⟩
lemma mem_sets_of_neq_bot {f : filter α} {s : set α} (h : f ⊓ principal (-s) = ⊥) : s ∈ f.sets :=
have ∅ ∈ (f ⊓ principal (- s)).sets, from h.symm ▸ mem_bot_sets,
let ⟨s₁, hs₁, s₂, (hs₂ : -s ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in
by filter_upwards [hs₁] assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩
lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) (ne : nonempty ι) :
(infi f).sets = (⋃ i, (f i).sets) :=
let ⟨i⟩ := ne, u := { filter .
sets := (⋃ i, (f i).sets),
univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem_sets⟩,
sets_of_superset := by simp only [mem_Union, exists_imp_distrib];
intros x y i hx hxy; exact ⟨i, mem_sets_of_superset hx hxy⟩,
inter_sets :=
begin
simp only [mem_Union, exists_imp_distrib],
assume x y a hx b hy,
rcases h a b with ⟨c, ha, hb⟩,
exact ⟨c, inter_mem_sets (ha hx) (hb hy)⟩
end } in
subset.antisymm
(show u ≤ infi f, from le_infi $ assume i, le_supr (λi, (f i).sets) i)
(Union_subset $ assume i, infi_le f i)
lemma infi_sets_eq' {f : β → filter α} {s : set β}
(h : directed_on (f ⁻¹'o (≥)) s) (ne : ∃i, i ∈ s) :
(⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) :=
let ⟨i, hi⟩ := ne in
calc (⨅ i ∈ s, f i).sets = (⨅ t : {t // t ∈ s}, (f t.val)).sets : by rw [infi_subtype]; refl
... = (⨆ t : {t // t ∈ s}, (f t.val).sets) : infi_sets_eq
(assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end)
⟨⟨i, hi⟩⟩
... = (⨆ t ∈ {t | t ∈ s}, (f t).sets) : by rw [supr_subtype]; refl
lemma infi_sets_eq_finite (f : ι → filter α) :
(⨅i, f i).sets = (⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets) :=
begin
rw [infi_eq_infi_finset, infi_sets_eq],
exact (directed_of_sup $ λs₁ s₂ hs, infi_le_infi $ λi, infi_le_infi_const $ λh, hs h),
apply_instance
end
@[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) :=
filter_eq $ set.ext $ assume x,
by simp only [supr_sets_eq, join, mem_sup_sets, iff_self, mem_set_of_eq]
@[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} :
(⨆x, join (f x)) = join (⨆x, f x) :=
filter_eq $ set.ext $ assume x,
by simp only [supr_sets_eq, join, iff_self, mem_Inter, mem_set_of_eq]
instance : bounded_distrib_lattice (filter α) :=
{ le_sup_inf :=
begin
assume x y z s,
simp only [and_assoc, mem_inf_sets, mem_sup_sets, exists_prop, exists_imp_distrib, and_imp],
intros hs t₁ ht₁ t₂ ht₂ hts,
exact ⟨s ∪ t₁,
x.sets_of_superset hs $ subset_union_left _ _,
y.sets_of_superset ht₁ $ subset_union_right _ _,
s ∪ t₂,
x.sets_of_superset hs $ subset_union_left _ _,
z.sets_of_superset ht₂ $ subset_union_right _ _,
subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hts)⟩
end,
..filter.lattice.complete_lattice }
/- the complementary version with ⨆i, f ⊓ g i does not hold! -/
lemma infi_sup_eq {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g :=
begin
refine le_antisymm _ (le_infi $ assume i, sup_le_sup (le_refl f) $ infi_le _ _),
rintros t ⟨h₁, h₂⟩,
rw [infi_sets_eq_finite] at h₂,
simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂,
rcases h₂ with ⟨s, hs⟩,
suffices : (⨅i, f ⊔ g i) ≤ f ⊔ s.inf (λi, g i.down), { exact this ⟨h₁, hs⟩ },
refine finset.induction_on s _ _,
{ exact le_sup_right_of_le le_top },
{ rintros ⟨i⟩ s his ih,
rw [finset.inf_insert, sup_inf_left],
exact le_inf (infi_le _ _) ih }
end
lemma mem_infi_sets_finset {s : finset α} {f : α → filter β} :
∀t, t ∈ (⨅a∈s, f a).sets ↔ (∃p:α → set β, (∀a∈s, p a ∈ (f a).sets) ∧ (⋂a∈s, p a) ⊆ t) :=
show ∀t, t ∈ (⨅a∈s, f a).sets ↔ (∃p:α → set β, (∀a∈s, p a ∈ (f a).sets) ∧ (⨅a∈s, p a) ≤ t),
begin
simp only [(finset.inf_eq_infi _ _).symm],
refine finset.induction_on s _ _,
{ simp only [finset.not_mem_empty, false_implies_iff, finset.inf_empty, top_le_iff,
imp_true_iff, mem_top_sets, true_and, exists_const],
intros; refl },
{ intros a s has ih t,
simp only [ih, finset.forall_mem_insert, finset.inf_insert, mem_inf_sets,
exists_prop, iff_iff_implies_and_implies, exists_imp_distrib, and_imp, and_assoc] {contextual := tt},
split,
{ intros t₁ ht₁ t₂ p hp ht₂ ht,
existsi function.update p a t₁,
have : ∀a'∈s, function.update p a t₁ a' = p a',
from assume a' ha',
have a' ≠ a, from assume h, has $ h ▸ ha',
function.update_noteq this,
have eq : s.inf (λj, function.update p a t₁ j) = s.inf (λj, p j) :=
finset.inf_congr rfl this,
simp only [this, ht₁, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt},
exact subset.trans (inter_subset_inter (subset.refl _) ht₂) ht },
assume p hpa hp ht,
exact ⟨p a, hpa, (s.inf p), ⟨⟨p, hp, le_refl _⟩, ht⟩⟩ }
end
/- principal equations -/
@[simp] lemma inf_principal {s t : set α} : principal s ⊓ principal t = principal (s ∩ t) :=
le_antisymm
(by simp; exact ⟨s, subset.refl s, t, subset.refl t, by simp⟩)
(by simp [le_inf_iff, inter_subset_left, inter_subset_right])
@[simp] lemma sup_principal {s t : set α} : principal s ⊔ principal t = principal (s ∪ t) :=
filter_eq $ set.ext $
by simp only [union_subset_iff, union_subset_iff, mem_sup_sets, forall_const, iff_self, mem_principal_sets]
@[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, principal (s x)) = principal (⋃i, s i) :=
filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, mem_principal_sets, mem_Inter];
exact (@supr_le_iff (set α) _ _ _ _).symm
lemma principal_univ : principal (univ : set α) = ⊤ :=
top_unique $ by simp only [le_principal_iff, mem_top_sets, eq_self_iff_true]
lemma principal_empty : principal (∅ : set α) = ⊥ :=
bot_unique $ assume s _, empty_subset _
@[simp] lemma principal_eq_bot_iff {s : set α} : principal s = ⊥ ↔ s = ∅ :=
⟨assume h, principal_eq_iff_eq.mp $ by simp only [principal_empty, h, eq_self_iff_true],
assume h, by simp only [h, principal_empty, eq_self_iff_true]⟩
lemma inf_principal_eq_bot {f : filter α} {s : set α} (hs : -s ∈ f.sets) : f ⊓ principal s = ⊥ :=
empty_in_sets_eq_bot.mp ⟨_, hs, s, mem_principal_self s, assume x ⟨h₁, h₂⟩, h₁ h₂⟩
theorem mem_inf_principal (f : filter α) (s t : set α) :
s ∈ (f ⊓ principal t).sets ↔ { x | x ∈ t → x ∈ s } ∈ f.sets :=
begin
simp only [mem_inf_sets, mem_principal_sets, exists_prop], split,
{ rintros ⟨u, ul, v, tsubv, uvinter⟩,
apply filter.mem_sets_of_superset ul,
intros x xu xt, exact uvinter ⟨xu, tsubv xt⟩ },
intro h, refine ⟨_, h, t, set.subset.refl t, _⟩,
rintros x ⟨hx, xt⟩,
exact hx xt
end
end lattice
section map
/-- The forward map of a filter -/
def map (m : α → β) (f : filter α) : filter β :=
{ sets := preimage m ⁻¹' f.sets,
univ_sets := univ_mem_sets,
sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ preimage_mono st,
inter_sets := assume s t hs ht, inter_mem_sets hs ht }
@[simp] lemma map_principal {s : set α} {f : α → β} :
map f (principal s) = principal (set.image f s) :=
filter_eq $ set.ext $ assume a, image_subset_iff.symm
variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β}
@[simp] lemma mem_map : t ∈ (map m f).sets ↔ {x | m x ∈ t} ∈ f.sets := iff.rfl
lemma image_mem_map (hs : s ∈ f.sets) : m '' s ∈ (map m f).sets :=
f.sets_of_superset hs $ subset_preimage_image m s
lemma range_mem_map : range m ∈ (map m f).sets :=
by rw ←image_univ; exact image_mem_map univ_mem_sets
lemma mem_map_sets_iff : t ∈ (map m f).sets ↔ (∃s∈f.sets, m '' s ⊆ t) :=
iff.intro
(assume ht, ⟨set.preimage m t, ht, image_preimage_subset _ _⟩)
(assume ⟨s, hs, ht⟩, mem_sets_of_superset (image_mem_map hs) ht)
@[simp] lemma map_id : filter.map id f = f :=
filter_eq $ rfl
@[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) :=
funext $ assume _, filter_eq $ rfl
@[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f :=
congr_fun (@@filter.map_compose m m') f
end map
section comap
/-- The inverse map of a filter -/
def comap (m : α → β) (f : filter β) : filter α :=
{ sets := { s | ∃t∈f.sets, m ⁻¹' t ⊆ s },
univ_sets := ⟨univ, univ_mem_sets, by simp only [subset_univ, preimage_univ]⟩,
sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab,
⟨a', ha', subset.trans ma'a ab⟩,
inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩,
⟨a' ∩ b', inter_mem_sets ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ }
end comap
/-- The cofinite filter is the filter of subsets whose complements are finite. -/
def cofinite : filter α :=
{ sets := {s | finite (- s)},
univ_sets := by simp only [compl_univ, finite_empty, mem_set_of_eq],
sets_of_superset := assume s t (hs : finite (-s)) (st: s ⊆ t),
finite_subset hs $ @lattice.neg_le_neg (set α) _ _ _ st,
inter_sets := assume s t (hs : finite (-s)) (ht : finite (-t)),
by simp only [compl_inter, finite_union, ht, hs, mem_set_of_eq] }
/-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`.
Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the
applicative instance. -/
def bind (f : filter α) (m : α → filter β) : filter β := join (map m f)
/-- The applicative sequentiation operation. This is not induced by the bind operation. -/
def seq (f : filter (α → β)) (g : filter α) : filter β :=
⟨{ s | ∃u∈f.sets, ∃t∈g.sets, (∀m∈u, ∀x∈t, (m : α → β) x ∈ s) },
⟨univ, univ_mem_sets, univ, univ_mem_sets, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩,
assume s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, assume x hx y hy, hst $ h _ hx _ hy⟩,
assume s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩,
⟨t₀ ∩ u₀, inter_mem_sets ht₀ hu₀, t₁ ∩ u₁, inter_mem_sets ht₁ hu₁,
assume x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩
instance : has_pure filter := ⟨λ(α : Type u) x, principal {x}⟩
instance : has_bind filter := ⟨@filter.bind⟩
instance : has_seq filter := ⟨@filter.seq⟩
instance : functor filter := { map := @filter.map }
section
-- this section needs to be before applicative, otherwise the wrong instance will be chosen
protected def monad : monad filter := { map := @filter.map }
local attribute [instance] filter.monad
protected def is_lawful_monad : is_lawful_monad filter :=
{ id_map := assume α f, filter_eq rfl,
pure_bind := assume α β a f, by simp only [bind, Sup_image, image_singleton,
join_principal_eq_Sup, lattice.Sup_singleton, map_principal, eq_self_iff_true],
bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl,
bind_pure_comp_eq_map := assume α β f x, filter_eq $
by simp only [bind, join, map, preimage, principal, set.subset_univ, eq_self_iff_true,
function.comp_app, mem_set_of_eq, singleton_subset_iff] }
end
instance : applicative filter := { map := @filter.map, seq := @filter.seq }
instance : alternative filter :=
{ failure := λα, ⊥,
orelse := λα x y, x ⊔ y }
@[simp] lemma pure_def (x : α) : pure x = principal {x} := rfl
@[simp] lemma mem_pure {a : α} {s : set α} : a ∈ s → s ∈ (pure a : filter α).sets :=
by simp only [imp_self, pure_def, mem_principal_sets, singleton_subset_iff]; exact id
@[simp] lemma mem_pure_iff {a : α} {s : set α} : s ∈ (pure a : filter α).sets ↔ a ∈ s :=
by rw [pure_def, mem_principal_sets, set.singleton_subset_iff]
@[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl
@[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl
/- map and comap equations -/
section map
variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β}
@[simp] theorem mem_comap_sets : s ∈ (comap m g).sets ↔ ∃t∈g.sets, m ⁻¹' t ⊆ s := iff.rfl
theorem preimage_mem_comap (ht : t ∈ g.sets) : m ⁻¹' t ∈ (comap m g).sets :=
⟨t, ht, subset.refl _⟩
lemma comap_id : comap id f = f :=
le_antisymm (assume s, preimage_mem_comap) (assume s ⟨t, ht, hst⟩, mem_sets_of_superset ht hst)
lemma comap_comap_comp {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f :=
le_antisymm
(assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩)
(assume c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩,
⟨a, ha, show preimage m (preimage n a) ⊆ c, from subset.trans (preimage_mono h₁) h₂⟩)
@[simp] theorem comap_principal {t : set β} : comap m (principal t) = principal (m ⁻¹' t) :=
filter_eq $ set.ext $ assume s,
⟨assume ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, subset.trans (preimage_mono hu) b,
assume : preimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩
lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g :=
⟨assume h s ⟨t, ht, hts⟩, mem_sets_of_superset (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩
lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) :=
assume f g, map_le_iff_le_comap
lemma map_mono (h : f₁ ≤ f₂) : map m f₁ ≤ map m f₂ := (gc_map_comap m).monotone_l h
lemma monotone_map : monotone (map m) | a b := map_mono
lemma comap_mono (h : g₁ ≤ g₂) : comap m g₁ ≤ comap m g₂ := (gc_map_comap m).monotone_u h
lemma monotone_comap : monotone (comap m) | a b := comap_mono
@[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot
@[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup
@[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) :=
(gc_map_comap m).l_supr
@[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top
@[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf
@[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅i, f i) = (⨅i, comap m (f i)) :=
(gc_map_comap m).u_infi
lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _
lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _
@[simp] lemma comap_bot : comap m ⊥ = ⊥ :=
bot_unique $ assume s _, ⟨∅, by simp only [mem_bot_sets], by simp only [empty_subset, preimage_empty]⟩
lemma comap_supr {ι} {f : ι → filter β} {m : α → β} :
comap m (supr f) = (⨆i, comap m (f i)) :=
le_antisymm
(assume s hs,
have ∀i, ∃t, t ∈ (f i).sets ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap_sets, exists_prop, mem_supr_sets] using mem_supr_sets.1 hs,
let ⟨t, ht⟩ := classical.axiom_of_choice this in
⟨⋃i, t i, mem_supr_sets.2 $ assume i, (f i).sets_of_superset (ht i).1 (subset_Union _ _),
begin
rw [preimage_Union, Union_subset_iff],
assume i,
exact (ht i).2
end⟩)
(supr_le $ assume i, monotone_comap $ le_supr _ _)
lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆f∈s, comap m f) :=
by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true]
lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ :=
le_antisymm
(assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩,
⟨t₁ ∪ t₂,
⟨g₁.sets_of_superset ht₁ (subset_union_left _ _), g₂.sets_of_superset ht₂ (subset_union_right _ _)⟩,
union_subset hs₁ hs₂⟩)
(sup_le (comap_mono le_sup_left) (comap_mono le_sup_right))
lemma map_comap {f : filter β} {m : α → β} (hf : range m ∈ f.sets) : (f.comap m).map m = f :=
le_antisymm
map_comap_le
(assume t' ⟨t, ht, sub⟩, by filter_upwards [ht, hf]; rintros x hxt ⟨y, rfl⟩; exact sub hxt)
lemma comap_map {f : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) :
comap m (map m f) = f :=
have ∀s, preimage m (image m s) = s,
from assume s, preimage_image_eq s h,
le_antisymm
(assume s hs, ⟨
image m s,
f.sets_of_superset hs $ by simp only [this, subset.refl],
by simp only [this, subset.refl]⟩)
le_comap_map
lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α}
(hsf : s ∈ f.sets) (hsg : s ∈ g.sets) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y)
(h : map m f ≤ map m g) : f ≤ g :=
assume t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem_sets hsg ht)]
assume a has ⟨b, ⟨hbs, hb⟩, h⟩,
have b = a, from hm _ hbs _ has h,
this ▸ hb
lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α}
(hsf : s ∈ f.sets) (hsg : s ∈ g.sets) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) :
map m f ≤ map m g ↔ f ≤ g :=
iff.intro (le_of_map_le_map_inj' hsf hsg hm) map_mono
lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α}
(hsf : s ∈ f.sets) (hsg : s ∈ g.sets) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y)
(h : map m f = map m g) : f = g :=
le_antisymm
(le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h)
(le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm)
lemma map_inj {f g : filter α} {m : α → β} (hm : ∀ x y, m x = m y → x = y) (h : map m f = map m g) :
f = g :=
have comap m (map m f) = comap m (map m g), by rw h,
by rwa [comap_map hm, comap_map hm] at this
theorem le_map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l.sets)
(hf : ∀ y ∈ u, ∃ x, f x = y) :
l ≤ map f (comap f l) :=
assume s ⟨t, tl, ht⟩,
have t ∩ u ⊆ s, from
assume x ⟨xt, xu⟩,
exists.elim (hf x xu) $ λ a faeq,
by { rw ←faeq, apply ht, change f a ∈ t, rw faeq, exact xt },
mem_sets_of_superset (inter_mem_sets tl ul) this
theorem map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l.sets)
(hf : ∀ y ∈ u, ∃ x, f x = y) :
map f (comap f l) = l :=
le_antisymm map_comap_le (le_map_comap_of_surjective' ul hf)
theorem le_map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) :
l ≤ map f (comap f l) :=
le_map_comap_of_surjective' univ_mem_sets (λ y _, hf y)
theorem map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) :
map f (comap f l) = l :=
le_antisymm map_comap_le (le_map_comap_of_surjective hf l)
lemma comap_neq_bot {f : filter β} {m : α → β}
(hm : ∀t∈f.sets, ∃a, m a ∈ t) : comap m f ≠ ⊥ :=
forall_sets_neq_empty_iff_neq_bot.mp $ assume s ⟨t, ht, t_s⟩,
let ⟨a, (ha : a ∈ preimage m t)⟩ := hm t ht in
neq_bot_of_le_neq_bot (ne_empty_of_mem ha) t_s
lemma comap_neq_bot_of_surj {f : filter β} {m : α → β}
(hf : f ≠ ⊥) (hm : ∀b, ∃a, m a = b) : comap m f ≠ ⊥ :=
comap_neq_bot $ assume t ht,
let
⟨b, (hx : b ∈ t)⟩ := inhabited_of_mem_sets hf ht,
⟨a, (ha : m a = b)⟩ := hm b
in ⟨a, ha.symm ▸ hx⟩
@[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ :=
⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id,
assume h, by simp only [h, eq_self_iff_true, map_bot]⟩
lemma map_ne_bot (hf : f ≠ ⊥) : map m f ≠ ⊥ :=
assume h, hf $ by rwa [map_eq_bot_iff] at h
lemma sInter_comap_sets (f : α → β) (F : filter β) :
⋂₀(comap f F).sets = ⋂ U ∈ F.sets, f ⁻¹' U :=
begin
ext x,
suffices : (∀ (A : set α) (B : set β), B ∈ F.sets → f ⁻¹' B ⊆ A → x ∈ A) ↔
∀ (B : set β), B ∈ F.sets → f x ∈ B,
by simp only [mem_sInter, mem_Inter, mem_comap_sets, this, and_imp, mem_comap_sets, exists_prop, mem_sInter,
iff_self, mem_Inter, mem_preimage_eq, exists_imp_distrib],
split,
{ intros h U U_in,
simpa only [set.subset.refl, forall_prop_of_true, mem_preimage_eq] using h (f ⁻¹' U) U U_in },
{ intros h V U U_in f_U_V,
exact f_U_V (h U U_in) },
end
end map
lemma map_cong {m₁ m₂ : α → β} {f : filter α} (h : {x | m₁ x = m₂ x} ∈ f.sets) :
map m₁ f = map m₂ f :=
have ∀(m₁ m₂ : α → β) (h : {x | m₁ x = m₂ x} ∈ f.sets), map m₁ f ≤ map m₂ f,
begin
intros m₁ m₂ h s hs,
show {x | m₁ x ∈ s} ∈ f.sets,
filter_upwards [h, hs],
simp only [subset_def, mem_preimage_eq, mem_set_of_eq, forall_true_iff] {contextual := tt}
end,
le_antisymm (this m₁ m₂ h) (this m₂ m₁ $ mem_sets_of_superset h $ assume x, eq.symm)
-- this is a generic rule for monotone functions:
lemma map_infi_le {f : ι → filter α} {m : α → β} :
map m (infi f) ≤ (⨅ i, map m (f i)) :=
le_infi $ assume i, map_mono $ infi_le _ _
lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) (hι : nonempty ι) :
map m (infi f) = (⨅ i, map m (f i)) :=
le_antisymm
map_infi_le
(assume s (hs : preimage m s ∈ (infi f).sets),
have ∃i, preimage m s ∈ (f i).sets,
by simp only [infi_sets_eq hf hι, mem_Union] at hs; assumption,
let ⟨i, hi⟩ := this in
have (⨅ i, map m (f i)) ≤ principal s, from
infi_le_of_le i $ by simp only [le_principal_iff, mem_map]; assumption,
by simp only [filter.le_principal_iff] at this; assumption)
lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop}
(h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃i, p i) :
map m (⨅i (h : p i), f i) = (⨅i (h: p i), map m (f i)) :=
let ⟨i, hi⟩ := ne in
calc map m (⨅i (h : p i), f i) = map m (⨅i:subtype p, f i.val) : by simp only [infi_subtype, eq_self_iff_true]
... = (⨅i:subtype p, map m (f i.val)) : map_infi_eq
(assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end)
⟨⟨i, hi⟩⟩
... = (⨅i (h : p i), map m (f i)) : by simp only [infi_subtype, eq_self_iff_true]
lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f.sets) (htg : t ∈ g.sets)
(h : ∀x∈t, ∀y∈t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g :=
begin
refine le_antisymm
(le_inf (map_mono inf_le_left) (map_mono inf_le_right))
(assume s hs, _),
simp only [map, mem_inf_sets, exists_prop, mem_map, mem_preimage_eq, mem_inf_sets] at hs ⊢,
rcases hs with ⟨t₁, h₁, t₂, h₂, hs⟩,
refine ⟨m '' (t₁ ∩ t), _, m '' (t₂ ∩ t), _, _⟩,
{ filter_upwards [h₁, htf] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ },
{ filter_upwards [h₂, htg] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ },
{ rw [image_inter_on],
{ refine image_subset_iff.2 _,
exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, hs ⟨h₁, h₂⟩ },
{ exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } }
end
lemma map_inf {f g : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) :
map m (f ⊓ g) = map m f ⊓ map m g :=
map_inf' univ_mem_sets univ_mem_sets (assume x _ y _, h x y)
lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α}
(h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f :=
le_antisymm
(assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $
calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true]
... ⊆ preimage m b : preimage_mono h)
(assume b (hb : preimage m b ∈ f.sets),
⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩)
lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f :=
map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq
lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀s∈f.sets, m '' s ∈ g.sets) :
g ≤ f.map m :=
assume s hs, mem_sets_of_superset (h _ hs) $ image_preimage_subset _ _
section applicative
@[simp] lemma mem_pure_sets {a : α} {s : set α} :
s ∈ (pure a : filter α).sets ↔ a ∈ s :=
by simp only [iff_self, pure_def, mem_principal_sets, singleton_subset_iff]
lemma singleton_mem_pure_sets {a : α} : {a} ∈ (pure a : filter α).sets :=
by simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff]
@[simp] lemma pure_neq_bot {α : Type u} {a : α} : pure a ≠ (⊥ : filter α) :=
by simp only [pure, has_pure.pure, ne.def, not_false_iff, singleton_ne_empty, principal_eq_bot_iff]
lemma mem_seq_sets_def {f : filter (α → β)} {g : filter α} {s : set β} :
s ∈ (f.seq g).sets ↔ (∃u∈f.sets, ∃t∈g.sets, ∀x∈u, ∀y∈t, (x : α → β) y ∈ s) :=
iff.refl _
lemma mem_seq_sets_iff {f : filter (α → β)} {g : filter α} {s : set β} :
s ∈ (f.seq g).sets ↔ (∃u∈f.sets, ∃t∈g.sets, set.seq u t ⊆ s) :=
by simp only [mem_seq_sets_def, seq_subset, exists_prop, iff_self]
lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} :
s ∈ ((f.map m).seq g).sets ↔ (∃t u, t ∈ g.sets ∧ u ∈ f.sets ∧ ∀x∈u, ∀y∈t, m x y ∈ s) :=
iff.intro
(assume ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, assume a, hts _⟩)
(assume ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, assume f ⟨a, has, eq⟩, eq ▸ hts _ has⟩)
lemma seq_mem_seq_sets {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α}
(hs : s ∈ f.sets) (ht : t ∈ g.sets): s.seq t ∈ (f.seq g).sets :=
⟨s, hs, t, ht, assume f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩
lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β}
(hh : ∀t∈f.sets, ∀u∈g.sets, set.seq t u ∈ h.sets) : h ≤ seq f g :=
assume s ⟨t, ht, u, hu, hs⟩, mem_sets_of_superset (hh _ ht _ hu) $
assume b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha
lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α}
(hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ :=
le_seq $ assume s hs t ht, seq_mem_seq_sets (hf hs) (hg ht)
@[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g :=
begin
refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _),
{ rw ← singleton_seq, apply seq_mem_seq_sets _ hs,
simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff] },
{ rw mem_pure_sets at hs,
refine sets_of_superset (map g f) (image_mem_map ht) _,
rintros b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ }
end
@[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) :=
le_antisymm
(le_principal_iff.2 $ sets_of_superset (map f (pure a)) (image_mem_map singleton_mem_pure_sets) $
by simp only [image_singleton, mem_singleton, singleton_subset_iff])
(le_map $ assume s, begin
simp only [mem_image, pure_def, mem_principal_sets, singleton_subset_iff],
exact assume has, ⟨a, has, rfl⟩
end)
@[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λg:α → β, g a) f :=
begin
refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _),
{ rw ← seq_singleton, exact seq_mem_seq_sets hs
(by simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff]) },
{ rw mem_pure_sets at ht,
refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _,
rintros b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ }
end
@[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) :
seq h (seq g x) = seq (seq (map (∘) h) g) x :=
begin
refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _),
{ rcases mem_seq_sets_iff.1 hs with ⟨u, hu, v, hv, hs⟩,
rcases mem_map_sets_iff.1 hu with ⟨w, hw, hu⟩,
refine mem_sets_of_superset _
(set.seq_mono (subset.trans (set.seq_mono hu (subset.refl _)) hs) (subset.refl _)),
rw ← set.seq_seq,
exact seq_mem_seq_sets hw (seq_mem_seq_sets hv ht) },
{ rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩,
refine mem_sets_of_superset _ (set.seq_mono (subset.refl _) ht),
rw set.seq_seq,
exact seq_mem_seq_sets (seq_mem_seq_sets (image_mem_map hs) hu) hv }
end
lemma prod_map_seq_comm (f : filter α) (g : filter β) :
(map prod.mk f).seq g = seq (map (λb a, (a, b)) g) f :=
begin
refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _),
{ rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩,
refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)),
rw ← set.prod_image_seq_comm,
exact seq_mem_seq_sets (image_mem_map ht) hu },
{ rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩,
refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)),
rw set.prod_image_seq_comm,
exact seq_mem_seq_sets (image_mem_map ht) hu }
end
instance : is_lawful_functor (filter : Type u → Type u) :=
{ id_map := assume α f, map_id,
comp_map := assume α β γ f g a, map_map.symm }
instance : is_lawful_applicative (filter : Type u → Type u) :=
{ pure_seq_eq_map := assume α β, pure_seq_eq_map,
map_pure := assume α β, map_pure,
seq_pure := assume α β, seq_pure,
seq_assoc := assume α β γ, seq_assoc }
instance : is_comm_applicative (filter : Type u → Type u) :=
⟨assume α β f g, prod_map_seq_comm f g⟩
lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) :
f <*> g = seq f g := rfl
end applicative
/- bind equations -/
section bind
@[simp] lemma mem_bind_sets {s : set β} {f : filter α} {m : α → filter β} :
s ∈ (bind f m).sets ↔ ∃t ∈ f.sets, ∀x ∈ t, s ∈ (m x).sets :=
calc s ∈ (bind f m).sets ↔ {a | s ∈ (m a).sets} ∈ f.sets : by simp only [bind, mem_map, iff_self, mem_join_sets, mem_set_of_eq]
... ↔ (∃t ∈ f.sets, t ⊆ {a | s ∈ (m a).sets}) : exists_sets_subset_iff.symm
... ↔ (∃t ∈ f.sets, ∀x ∈ t, s ∈ (m x).sets) : iff.refl _
lemma bind_mono {f : filter α} {g h : α → filter β} (h₁ : {a | g a ≤ h a} ∈ f.sets) :
bind f g ≤ bind f h :=
assume x h₂, show (_ ∈ f.sets), by filter_upwards [h₁, h₂] assume s gh' h', gh' h'
lemma bind_sup {f g : filter α} {h : α → filter β} :
bind (f ⊔ g) h = bind f h ⊔ bind g h :=
by simp only [bind, sup_join, map_sup, eq_self_iff_true]
lemma bind_mono2 {f g : filter α} {h : α → filter β} (h₁ : f ≤ g) :
bind f h ≤ bind g h :=
assume s h', h₁ h'
lemma principal_bind {s : set α} {f : α → filter β} :
(bind (principal s) f) = (⨆x ∈ s, f x) :=
show join (map f (principal s)) = (⨆x ∈ s, f x),
by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true]
end bind
lemma infi_neq_bot_of_directed {f : ι → filter α}
(hn : nonempty α) (hd : directed (≥) f) (hb : ∀i, f i ≠ ⊥) : (infi f) ≠ ⊥ :=
let ⟨x⟩ := hn in
assume h, have he: ∅ ∈ (infi f).sets, from h.symm ▸ mem_bot_sets,
classical.by_cases
(assume : nonempty ι,
have ∃i, ∅ ∈ (f i).sets,
by rw [infi_sets_eq hd this] at he; simp only [mem_Union] at he; assumption,
let ⟨i, hi⟩ := this in
hb i $ bot_unique $
assume s _, (f i).sets_of_superset hi $ empty_subset _)
(assume : ¬ nonempty ι,
have univ ⊆ (∅ : set α),
begin
rw [←principal_mono, principal_univ, principal_empty, ←h],
exact (le_infi $ assume i, false.elim $ this ⟨i⟩)
end,
this $ mem_univ x)
lemma infi_neq_bot_iff_of_directed {f : ι → filter α}
(hn : nonempty α) (hd : directed (≥) f) : (infi f) ≠ ⊥ ↔ (∀i, f i ≠ ⊥) :=
⟨assume neq_bot i eq_bot, neq_bot $ bot_unique $ infi_le_of_le i $ eq_bot ▸ le_refl _,
infi_neq_bot_of_directed hn hd⟩
lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ (f i).sets → s ∈ (⨅i, f i).sets :=
show (⨅i, f i) ≤ f i, from infi_le _ _
@[elab_as_eliminator]
lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ (infi f).sets) {p : set α → Prop}
(uni : p univ)
(ins : ∀{i s₁ s₂}, s₁ ∈ (f i).sets → p s₂ → p (s₁ ∩ s₂))
(upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s :=
begin
rw [infi_sets_eq_finite] at hs,
simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at hs,
rcases hs with ⟨is, his⟩,
revert s,
refine finset.induction_on is _ _,
{ assume s hs, rwa [mem_top_sets.1 hs] },
{ rintros ⟨i⟩ js his ih s hs,
rw [finset.inf_insert, mem_inf_sets] at hs,
rcases hs with ⟨s₁, hs₁, s₂, hs₂, hs⟩,
exact upw hs (ins hs₁ (ih hs₂)) }
end
/- tendsto -/
/-- `tendsto` is the generic "limit of a function" predicate.
`tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`,
the `f`-preimage of `a` is an `l₁` neighborhood. -/
def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂
lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} :
tendsto f l₁ l₂ ↔ ∀ s ∈ l₂.sets, f ⁻¹' s ∈ l₁.sets := iff.rfl
lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} :
tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f :=
map_le_iff_le_comap
lemma tendsto_cong {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β}
(h : tendsto f₁ l₁ l₂) (hl : {x | f₁ x = f₂ x} ∈ l₁.sets) : tendsto f₂ l₁ l₂ :=
by rwa [tendsto, ←map_cong hl]
lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y :=
by simp only [tendsto, map_id, forall_true_iff] {contextual := tt}
lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x
lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ}
(hf : tendsto f x y) (hg : tendsto g y z) : tendsto (g ∘ f) x z :=
calc map (g ∘ f) x = map g (map f x) : by rw [map_map]
... ≤ map g y : map_mono hf
... ≤ z : hg
lemma tendsto_le_left {f : α → β} {x y : filter α} {z : filter β}
(h : y ≤ x) : tendsto f x z → tendsto f y z :=
le_trans (map_mono h)
lemma tendsto_le_right {f : α → β} {x : filter α} {y z : filter β}
(h₁ : y ≤ z) (h₂ : tendsto f x y) : tendsto f x z :=
le_trans h₂ h₁
lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x)
lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ}
(h : tendsto (f ∘ g) x y) : tendsto f (map g x) y :=
by rwa [tendsto, map_map]
lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} :
tendsto f (map g x) y ↔ tendsto (f ∘ g) x y :=
by rw [tendsto, map_map]; refl
lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x :=
map_comap_le
lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} :
tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c :=
⟨assume h, h.comp tendsto_comap, assume h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩
lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α}
(h : range i ∈ f.sets) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g :=
by rw [tendsto, ← map_compose]; simp only [(∘), map_comap h, tendsto]
lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α)
(eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f :=
begin
refine le_antisymm (le_trans (comap_mono $ map_le_iff_le_comap.1 hψ) _) (map_le_iff_le_comap.1 hφ),
rw [comap_comap_comp, eq, comap_id],
exact le_refl _
end
lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α)
(eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g :=
begin
refine le_antisymm hφ (le_trans _ (map_mono hψ)),
rw [map_map, eq, map_id],
exact le_refl _
end
lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} :
tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ :=
by simp only [tendsto, lattice.le_inf_iff, iff_self]
lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β}
(h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y :=
le_trans (map_mono inf_le_left) h
lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β}
(h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y :=
le_trans (map_mono inf_le_right) h
lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} :
tendsto f x (⨅i, y i) ↔ ∀i, tendsto f x (y i) :=
by simp only [tendsto, iff_self, lattice.le_infi_iff]
lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) :
tendsto f (x i) y → tendsto f (⨅i, x i) y :=
tendsto_le_left (infi_le _ _)
lemma tendsto_principal {f : α → β} {a : filter α} {s : set β} :
tendsto f a (principal s) ↔ {a | f a ∈ s} ∈ a.sets :=
by simp only [tendsto, le_principal_iff, mem_map, iff_self]
lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} :
tendsto f (principal s) (principal t) ↔ ∀a∈s, f a ∈ t :=
by simp only [tendsto, image_subset_iff, le_principal_iff, map_principal, mem_principal_sets]; refl
lemma tendsto_pure_pure (f : α → β) (a : α) :
tendsto f (pure a) (pure (f a)) :=
show filter.map f (pure a) ≤ pure (f a),
by rw [filter.map_pure]; exact le_refl _
lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λa, b) a (pure b) :=
by simp [tendsto]; exact univ_mem_sets
lemma tendsto_if {l₁ : filter α} {l₂ : filter β}
{f g : α → β} {p : α → Prop} [decidable_pred p]
(h₀ : tendsto f (l₁ ⊓ principal p) l₂)
(h₁ : tendsto g (l₁ ⊓ principal { x | ¬ p x }) l₂) :
tendsto (λ x, if p x then f x else g x) l₁ l₂ :=
begin
revert h₀ h₁, simp only [tendsto_def, mem_inf_principal],
intros h₀ h₁ s hs,
apply mem_sets_of_superset (inter_mem_sets (h₀ s hs) (h₁ s hs)),
rintros x ⟨hp₀, hp₁⟩, dsimp,
by_cases h : p x,
{ rw if_pos h, exact hp₀ h },
rw if_neg h, exact hp₁ h
end
section prod
variables {s : set α} {t : set β} {f : filter α} {g : filter β}
/- The product filter cannot be defined using the monad structure on filters. For example:
F := do {x <- seq, y <- top, return (x, y)}
hence:
s ∈ F <-> ∃n, [n..∞] × univ ⊆ s
G := do {y <- top, x <- seq, return (x, y)}
hence:
s ∈ G <-> ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s
Now ⋃i, [i..∞] × {i} is in G but not in F.
As product filter we want to have F as result.
-/
/-- Product of filters. This is the filter generated by cartesian products
of elements of the component filters. -/
protected def prod (f : filter α) (g : filter β) : filter (α × β) :=
f.comap prod.fst ⊓ g.comap prod.snd
lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β}
(hs : s ∈ f.sets) (ht : t ∈ g.sets) : set.prod s t ∈ (filter.prod f g).sets :=
inter_mem_inf_sets (preimage_mem_comap hs) (preimage_mem_comap ht)
lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} :
s ∈ (filter.prod f g).sets ↔ (∃t₁∈f.sets, ∃t₂∈g.sets, set.prod t₁ t₂ ⊆ s) :=
begin
simp only [filter.prod],
split,
exact assume ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, h⟩,
⟨s₁, hs₁, s₂, hs₂, subset.trans (inter_subset_inter hts₁ hts₂) h⟩,
exact assume ⟨t₁, ht₁, t₂, ht₂, h⟩,
⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, ⟨t₂, ht₂, subset.refl _⟩, h⟩
end
lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (filter.prod f g) f :=
tendsto_inf_left tendsto_comap
lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (filter.prod f g) g :=
tendsto_inf_right tendsto_comap
lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ}
(h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λx, (m₁ x, m₂ x)) f (filter.prod g h) :=
tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩
lemma prod_infi_left {f : ι → filter α} {g : filter β} (i : ι) :
filter.prod (⨅i, f i) g = (⨅i, filter.prod (f i) g) :=
by rw [filter.prod, comap_infi, infi_inf i]; simp only [filter.prod, eq_self_iff_true]
lemma prod_infi_right {f : filter α} {g : ι → filter β} (i : ι) :
filter.prod f (⨅i, g i) = (⨅i, filter.prod f (g i)) :=
by rw [filter.prod, comap_infi, inf_infi i]; simp only [filter.prod, eq_self_iff_true]
lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) :
filter.prod f₁ g₁ ≤ filter.prod f₂ g₂ :=
inf_le_inf (comap_mono hf) (comap_mono hg)
lemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} :
filter.prod (comap m₁ f₁) (comap m₂ f₂) = comap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) :=
by simp only [filter.prod, comap_comap_comp, eq_self_iff_true, comap_inf]
lemma prod_comm' : filter.prod f g = comap (prod.swap) (filter.prod g f) :=
by simp only [filter.prod, comap_comap_comp, (∘), inf_comm, prod.fst_swap,
eq_self_iff_true, prod.snd_swap, comap_inf]
lemma prod_comm : filter.prod f g = map (λp:β×α, (p.2, p.1)) (filter.prod g f) :=
by rw [prod_comm', ← map_swap_eq_comap_swap]; refl
lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} :
filter.prod (map m₁ f₁) (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) :=
le_antisymm
(assume s hs,
let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in
filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $
calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ :
set.prod_image_image_eq
... ⊆ _ : by rwa [image_subset_iff])
((tendsto_fst.comp (le_refl _)).prod_mk (tendsto_snd.comp (le_refl _)))
lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) :
map m (f.prod g) = (f.map (λa b, m (a, b))).seq g :=
begin
simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff],
assume s,
split,
exact assume ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, assume x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩,
exact assume ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, assume ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩
end
lemma prod_eq {f : filter α} {g : filter β} : f.prod g = (f.map prod.mk).seq g :=
have h : _ := map_prod id f g, by rwa [map_id] at h
lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} :
filter.prod f₁ g₁ ⊓ filter.prod f₂ g₂ = filter.prod (f₁ ⊓ f₂) (g₁ ⊓ g₂) :=
by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, lattice.inf_left_comm]
@[simp] lemma prod_bot {f : filter α} : filter.prod f (⊥ : filter β) = ⊥ := by simp [filter.prod]
@[simp] lemma bot_prod {g : filter β} : filter.prod (⊥ : filter α) g = ⊥ := by simp [filter.prod]
@[simp] lemma prod_principal_principal {s : set α} {t : set β} :
filter.prod (principal s) (principal t) = principal (set.prod s t) :=
by simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl
@[simp] lemma prod_pure_pure {a : α} {b : β} : filter.prod (pure a) (pure b) = pure (a, b) :=
by simp
lemma prod_eq_bot {f : filter α} {g : filter β} : filter.prod f g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) :=
begin
split,
{ assume h,
rcases mem_prod_iff.1 (empty_in_sets_eq_bot.2 h) with ⟨s, hs, t, ht, hst⟩,
rw [subset_empty_iff, set.prod_eq_empty_iff] at hst,
cases hst with s_eq t_eq,
{ left, exact empty_in_sets_eq_bot.1 (s_eq ▸ hs) },
{ right, exact empty_in_sets_eq_bot.1 (t_eq ▸ ht) } },
{ rintros (rfl | rfl),
exact bot_prod,
exact prod_bot }
end
lemma prod_neq_bot {f : filter α} {g : filter β} : filter.prod f g ≠ ⊥ ↔ (f ≠ ⊥ ∧ g ≠ ⊥) :=
by rw [(≠), prod_eq_bot, not_or_distrib]
lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} :
filter.tendsto f (filter.prod x y) z ↔
∀ W ∈ z.sets, ∃ U ∈ x.sets, ∃ V ∈ y.sets, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W :=
by simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self]
end prod
/- at_top and at_bot -/
/-- `at_top` is the filter representing the limit `→ ∞` on an ordered set.
It is generated by the collection of up-sets `{b | a ≤ b}`.
(The preorder need not have a top element for this to be well defined,
and indeed is trivial when a top element exists.) -/
def at_top [preorder α] : filter α := ⨅ a, principal {b | a ≤ b}
/-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set.
It is generated by the collection of down-sets `{b | b ≤ a}`.
(The preorder need not have a bottom element for this to be well defined,
and indeed is trivial when a bottom element exists.) -/
def at_bot [preorder α] : filter α := ⨅ a, principal {b | b ≤ a}
lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ (@at_top α _).sets :=
mem_infi_sets a $ subset.refl _
@[simp] lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : (at_top : filter α) ≠ ⊥ :=
infi_neq_bot_of_directed (by apply_instance)
(assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of,
mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩)
(assume a, by simp only [principal_eq_bot_iff, ne.def, principal_eq_bot_iff]; exact ne_empty_of_mem (le_refl a))
@[simp] lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} :
s ∈ (at_top : filter α).sets ↔ ∃a:α, ∀b≥a, b ∈ s :=
let ⟨a⟩ := ‹nonempty α› in
iff.intro
(assume h, infi_sets_induct h ⟨a, by simp only [forall_const, mem_univ, forall_true_iff]⟩
(assume a s₁ s₂ ha ⟨b, hb⟩, ⟨a ⊔ b,
assume c hc, ⟨ha $ le_trans le_sup_left hc, hb _ $ le_trans le_sup_right hc⟩⟩)
(assume s₁ s₂ h ⟨a, ha⟩, ⟨a, assume b hb, h $ ha _ hb⟩))
(assume ⟨a, h⟩, mem_infi_sets a $ assume x, h x)
lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} :
at_top.map f = (⨅a, principal $ f '' {a' | a ≤ a'}) :=
calc map f (⨅a, principal {a' | a ≤ a'}) = (⨅a, map f $ principal {a' | a ≤ a'}) :
map_infi_eq (assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of,
mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩)
(by apply_instance)
... = (⨅a, principal $ f '' {a' | a ≤ a'}) : by simp only [map_principal, eq_self_iff_true]
lemma tendsto_at_top [preorder β] (m : α → β) (f : filter α) :
tendsto m f at_top ↔ (∀b, {a | b ≤ m a} ∈ f.sets) :=
by simp only [at_top, tendsto_infi, tendsto_principal]; refl
lemma tendsto_at_top' [nonempty α] [semilattice_sup α] (f : α → β) (l : filter β) :
tendsto f at_top l ↔ (∀s∈l.sets, ∃a, ∀b≥a, f b ∈ s) :=
by simp only [tendsto_def, mem_at_top_sets]; refl
theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} :
tendsto f at_top (principal s) ↔ ∃N, ∀n≥N, f n ∈ s :=
by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl
/-- A function `f` grows to infinity independent of an order-preserving embedding `e`. -/
lemma tendsto_at_top_embedding {α β γ : Type*} [preorder β] [preorder γ]
{f : α → β} {e : β → γ} {l : filter α}
(hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) :
tendsto (e ∘ f) l at_top ↔ tendsto f l at_top :=
begin
rw [tendsto_at_top, tendsto_at_top],
split,
{ assume hc b,
filter_upwards [hc (e b)] assume a, (hm b (f a)).1 },
{ assume hb c,
rcases hu c with ⟨b, hc⟩,
filter_upwards [hb b] assume a ha, le_trans hc ((hm b (f a)).2 ha) }
end
lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] (f : α → β) :
tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a :=
iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal
lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : ∀x, j (i x) = x) :
tendsto (λs:finset γ, s.image j) at_top at_top :=
tendsto_infi.2 $ assume s, tendsto_infi' (s.image i) $ tendsto_principal_principal.2 $
assume t (ht : s.image i ⊆ t),
calc s = (s.image i).image j :
by simp only [finset.image_image, (∘), h]; exact finset.image_id.symm
... ⊆ t.image j : finset.image_subset_image ht
lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [inhabited β₁] [inhabited β₂] [semilattice_sup β₁]
[semilattice_sup β₂] : filter.prod (@at_top β₁ _) (@at_top β₂ _) = @at_top (β₁ × β₂) _ :=
by simp [at_top, prod_infi_left (default β₁), prod_infi_right (default β₂), infi_prod];
exact infi_comm
lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [inhabited β₁] [inhabited β₂]
[semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) :
filter.prod (map u₁ at_top) (map u₂ at_top) = map (prod.map u₁ u₂) at_top :=
by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def]
/-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a
Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an
insertion and a connetion above `b'`. -/
lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β)(hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) :
map f at_top = at_top :=
begin
rw [@map_at_top_eq α _ ⟨g b'⟩],
refine le_antisymm
(le_infi $ assume b, infi_le_of_le (g (b ⊔ b')) $ principal_mono.2 $ image_subset_iff.2 _)
(le_infi $ assume a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 _),
{ assume a ha, exact (le_trans le_sup_left $ le_trans (hgi _ le_sup_right) $ hf ha) },
{ assume b hb,
have hb' : b' ≤ b := le_trans le_sup_right hb,
exact ⟨g b, (gc _ _ hb').1 (le_trans le_sup_left hb),
le_antisymm ((gc _ _ hb').2 (le_refl _)) (hgi _ hb')⟩ }
end
lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top :=
map_at_top_eq_of_gc (λa, a - k) k
(assume a b h, add_le_add_right h k)
(assume a b h, (nat.le_sub_right_iff_add_le h).symm)
(assume a h, by rw [nat.sub_add_cancel h])
lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top :=
map_at_top_eq_of_gc (λa, a + k) 0
(assume a b h, nat.sub_le_sub_right h _)
(assume a b _, nat.sub_le_right_iff_le_add)
(assume b _, by rw [nat.add_sub_cancel])
lemma tendso_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top :=
le_of_eq (map_add_at_top_eq_nat k)
lemma tendso_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top :=
le_of_eq (map_sub_at_top_eq_nat k)
lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) :
tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l :=
show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l,
by rw [← tendsto_map'_iff, map_add_at_top_eq_nat]
lemma map_div_at_top_eq_nat (k : ℕ) (hk : k > 0) : map (λa, a / k) at_top = at_top :=
map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1
(assume a b h, nat.div_le_div_right h)
(assume a b _,
calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff]
... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk
... ↔ _ :
begin
cases k,
exact (lt_irrefl _ hk).elim,
simp [mul_add, add_mul, nat.succ_add, nat.lt_succ_iff]
end)
(assume b _,
calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk]
... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _)
/- ultrafilter -/
section ultrafilter
open zorn
variables {f g : filter α}
/-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/
def is_ultrafilter (f : filter α) := f ≠ ⊥ ∧ ∀g, g ≠ ⊥ → g ≤ f → f ≤ g
lemma ultrafilter_unique (hg : is_ultrafilter g) (hf : f ≠ ⊥) (h : f ≤ g) : f = g :=
le_antisymm h (hg.right _ hf h)
lemma le_of_ultrafilter {g : filter α} (hf : is_ultrafilter f) (h : f ⊓ g ≠ ⊥) :
f ≤ g :=
le_of_inf_eq $ ultrafilter_unique hf h inf_le_left
/-- Equivalent characterization of ultrafilters:
A filter f is an ultrafilter if and only if for each set s,
-s belongs to f if and only if s does not belong to f. -/
lemma ultrafilter_iff_compl_mem_iff_not_mem :
is_ultrafilter f ↔ (∀ s, -s ∈ f.sets ↔ s ∉ f.sets) :=
⟨assume hf s,
⟨assume hns hs,
hf.1 $ empty_in_sets_eq_bot.mp $ by convert f.inter_sets hs hns; rw [inter_compl_self],
assume hs,
have f ≤ principal (-s), from
le_of_ultrafilter hf $ assume h, hs $ mem_sets_of_neq_bot $
by simp only [h, eq_self_iff_true, lattice.neg_neg],
by simp only [le_principal_iff] at this; assumption⟩,
assume hf,
⟨mt empty_in_sets_eq_bot.mpr ((hf ∅).mp (by convert f.univ_sets; rw [compl_empty])),
assume g hg g_le s hs, classical.by_contradiction $ mt (hf s).mpr $
assume : - s ∈ f.sets,
have s ∩ -s ∈ g.sets, from inter_mem_sets hs (g_le this),
by simp only [empty_in_sets_eq_bot, hg, inter_compl_self] at this; contradiction⟩⟩
lemma mem_or_compl_mem_of_ultrafilter (hf : is_ultrafilter f) (s : set α) :
s ∈ f.sets ∨ - s ∈ f.sets :=
classical.or_iff_not_imp_left.2 (ultrafilter_iff_compl_mem_iff_not_mem.mp hf s).mpr
lemma mem_or_mem_of_ultrafilter {s t : set α} (hf : is_ultrafilter f) (h : s ∪ t ∈ f.sets) :
s ∈ f.sets ∨ t ∈ f.sets :=
(mem_or_compl_mem_of_ultrafilter hf s).imp_right
(assume : -s ∈ f.sets, by filter_upwards [this, h] assume x hnx hx, hx.resolve_left hnx)
lemma mem_of_finite_sUnion_ultrafilter {s : set (set α)} (hf : is_ultrafilter f) (hs : finite s)
: ⋃₀ s ∈ f.sets → ∃t∈s, t ∈ f.sets :=
finite.induction_on hs (by simp only [empty_in_sets_eq_bot, hf.left, mem_empty_eq, sUnion_empty,
forall_prop_of_false, exists_false, not_false_iff, exists_prop_of_false]) $
λ t s' ht' hs' ih, by simp only [exists_prop, mem_insert_iff, set.sUnion_insert]; exact
assume h, (mem_or_mem_of_ultrafilter hf h).elim
(assume : t ∈ f.sets, ⟨t, or.inl rfl, this⟩)
(assume h, let ⟨t, hts', ht⟩ := ih h in ⟨t, or.inr hts', ht⟩)
lemma mem_of_finite_Union_ultrafilter {is : set β} {s : β → set α}
(hf : is_ultrafilter f) (his : finite is) (h : (⋃i∈is, s i) ∈ f.sets) : ∃i∈is, s i ∈ f.sets :=
have his : finite (image s is), from finite_image s his,
have h : (⋃₀ image s is) ∈ f.sets, from by simp only [sUnion_image, set.sUnion_image]; assumption,
let ⟨t, ⟨i, hi, h_eq⟩, (ht : t ∈ f.sets)⟩ := mem_of_finite_sUnion_ultrafilter hf his h in
⟨i, hi, h_eq.symm ▸ ht⟩
lemma ultrafilter_map {f : filter α} {m : α → β} (h : is_ultrafilter f) : is_ultrafilter (map m f) :=
by rw ultrafilter_iff_compl_mem_iff_not_mem at ⊢ h; exact assume s, h (m ⁻¹' s)
lemma ultrafilter_pure {a : α} : is_ultrafilter (pure a) :=
begin
rw ultrafilter_iff_compl_mem_iff_not_mem, intro s,
rw [mem_pure_sets, mem_pure_sets], exact iff.rfl
end
lemma ultrafilter_bind {f : filter α} (hf : is_ultrafilter f) {m : α → filter β}
(hm : ∀ a, is_ultrafilter (m a)) : is_ultrafilter (f.bind m) :=
begin
simp only [ultrafilter_iff_compl_mem_iff_not_mem] at ⊢ hf hm, intro s,
dsimp [bind, join, map],
simp only [hm], apply hf
end
/-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/
lemma exists_ultrafilter (h : f ≠ ⊥) : ∃u, u ≤ f ∧ is_ultrafilter u :=
let
τ := {f' // f' ≠ ⊥ ∧ f' ≤ f},
r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val,
⟨a, ha⟩ := inhabited_of_mem_sets h univ_mem_sets,
top : τ := ⟨f, h, le_refl f⟩,
sup : Π(c:set τ), chain r c → τ :=
λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.val.val,
infi_neq_bot_of_directed ⟨a⟩
(directed_of_chain $ chain_insert hc $ assume ⟨b, _, hb⟩ _ _, or.inl hb)
(assume ⟨⟨a, ha, _⟩, _⟩, ha),
infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩
in
have ∀c (hc: chain r c) a (ha : a ∈ c), r a (sup c hc),
from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _),
have (∃ (u : τ), ∀ (a : τ), r u a → r a u),
from zorn (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁),
let ⟨uτ, hmin⟩ := this in
⟨uτ.val, uτ.property.right, uτ.property.left, assume g hg₁ hg₂,
hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩
/-- Construct an ultrafilter extending a given filter.
The ultrafilter lemma is the assertion that such a filter exists;
we use the axiom of choice to pick one. -/
noncomputable def ultrafilter_of (f : filter α) : filter α :=
if h : f = ⊥ then ⊥ else classical.epsilon (λu, u ≤ f ∧ is_ultrafilter u)
lemma ultrafilter_of_spec (h : f ≠ ⊥) : ultrafilter_of f ≤ f ∧ is_ultrafilter (ultrafilter_of f) :=
begin
have h' := classical.epsilon_spec (exists_ultrafilter h),
simp only [ultrafilter_of, dif_neg, h, dif_neg, not_false_iff],
simp only at h',
assumption
end
lemma ultrafilter_of_le : ultrafilter_of f ≤ f :=
if h : f = ⊥ then by simp only [ultrafilter_of, dif_pos, h, dif_pos, eq_self_iff_true, le_bot_iff]; exact le_refl _
else (ultrafilter_of_spec h).left
lemma ultrafilter_ultrafilter_of (h : f ≠ ⊥) : is_ultrafilter (ultrafilter_of f) :=
(ultrafilter_of_spec h).right
lemma ultrafilter_of_ultrafilter (h : is_ultrafilter f) : ultrafilter_of f = f :=
ultrafilter_unique h (ultrafilter_ultrafilter_of h.left).left ultrafilter_of_le
/-- A filter equals the intersection of all the ultrafilters which contain it. -/
lemma sup_of_ultrafilters (f : filter α) : f = ⨆ (g) (u : is_ultrafilter g) (H : g ≤ f), g :=
begin
refine le_antisymm _ (supr_le $ λ g, supr_le $ λ u, supr_le $ λ H, H),
intros s hs,
-- If s ∉ f.sets, we'll apply the ultrafilter lemma to the restriction of f to -s.
by_contradiction hs',
let j : (-s) → α := subtype.val,
have j_inv_s : j ⁻¹' s = ∅, by
erw [←preimage_inter_range, subtype.val_range, inter_compl_self, preimage_empty],
let f' := comap j f,
have : f' ≠ ⊥,
{ apply mt empty_in_sets_eq_bot.mpr,
rintro ⟨t, htf, ht⟩,
suffices : t ⊆ s, from absurd (f.sets_of_superset htf this) hs',
rw [subset_empty_iff] at ht,
have : j '' (j ⁻¹' t) = ∅, by rw [ht, image_empty],
erw [image_preimage_eq_inter_range, subtype.val_range, ←subset_compl_iff_disjoint,
set.compl_compl] at this,
exact this },
rcases exists_ultrafilter this with ⟨g', g'f', u'⟩,
simp only [supr_sets_eq, mem_Inter] at hs,
have := hs (g'.map subtype.val) (ultrafilter_map u') (map_le_iff_le_comap.mpr g'f'),
rw [←le_principal_iff, map_le_iff_le_comap, comap_principal, j_inv_s, principal_empty,
le_bot_iff] at this,
exact absurd this u'.1
end
/-- The `tendsto` relation can be checked on ultrafilters. -/
lemma tendsto_iff_ultrafilter (f : α → β) (l₁ : filter α) (l₂ : filter β) :
tendsto f l₁ l₂ ↔ ∀ g, is_ultrafilter g → g ≤ l₁ → g.map f ≤ l₂ :=
⟨assume h g u gx, le_trans (map_mono gx) h,
assume h, by rw [sup_of_ultrafilters l₁]; simpa only [tendsto, map_supr, supr_le_iff]⟩
/- The ultrafilter monad. The monad structure on ultrafilters is the
restriction of the one on filters. -/
def ultrafilter (α : Type u) : Type u := {f : filter α // is_ultrafilter f}
def ultrafilter.map (m : α → β) (u : ultrafilter α) : ultrafilter β :=
⟨u.val.map m, ultrafilter_map u.property⟩
def ultrafilter.pure (x : α) : ultrafilter α := ⟨pure x, ultrafilter_pure⟩
def ultrafilter.bind (u : ultrafilter α) (m : α → ultrafilter β) : ultrafilter β :=
⟨u.val.bind (λ a, (m a).val), ultrafilter_bind u.property (λ a, (m a).property)⟩
instance ultrafilter.has_pure : has_pure ultrafilter := ⟨@ultrafilter.pure⟩
instance ultrafilter.has_bind : has_bind ultrafilter := ⟨@ultrafilter.bind⟩
instance ultrafilter.functor : functor ultrafilter := { map := @ultrafilter.map }
instance ultrafilter.monad : monad ultrafilter := { map := @ultrafilter.map }
section
local attribute [instance] filter.monad filter.is_lawful_monad
instance ultrafilter.is_lawful_monad : is_lawful_monad ultrafilter :=
{ id_map := assume α f, subtype.eq (id_map f.val),
pure_bind := assume α β a f, subtype.eq (pure_bind a (subtype.val ∘ f)),
bind_assoc := assume α β γ f m₁ m₂, subtype.eq (filter_eq rfl),
bind_pure_comp_eq_map := assume α β f x, subtype.eq (bind_pure_comp_eq_map _ f x.val) }
end
lemma ultrafilter.eq_iff_val_le_val {u v : ultrafilter α} : u = v ↔ u.val ≤ v.val :=
⟨assume h, by rw h; exact le_refl _,
assume h, by rw subtype.ext; apply ultrafilter_unique v.property u.property.1 h⟩
lemma exists_ultrafilter_iff (f : filter α) : (∃ (u : ultrafilter α), u.val ≤ f) ↔ f ≠ ⊥ :=
⟨assume ⟨u, uf⟩, lattice.neq_bot_of_le_neq_bot u.property.1 uf,
assume h, let ⟨u, uf, hu⟩ := exists_ultrafilter h in ⟨⟨u, hu⟩, uf⟩⟩
end ultrafilter
end filter
namespace filter
variables {α β γ : Type u} {f : β → filter α} {s : γ → set α}
open list
lemma mem_traverse_sets :
∀(fs : list β) (us : list γ),
forall₂ (λb c, s c ∈ (f b).sets) fs us → traverse s us ∈ (traverse f fs).sets
| [] [] forall₂.nil := mem_pure_sets.2 $ mem_singleton _
| (f::fs) (u::us) (forall₂.cons h hs) := seq_mem_seq_sets (image_mem_map h) (mem_traverse_sets fs us hs)
lemma mem_traverse_sets_iff (fs : list β) (t : set (list α)) :
t ∈ (traverse f fs).sets ↔
(∃us:list (set α), forall₂ (λb (s : set α), s ∈ (f b).sets) fs us ∧ sequence us ⊆ t) :=
begin
split,
{ induction fs generalizing t,
case nil { simp only [sequence, pure_def, imp_self, forall₂_nil_left_iff, pure_def,
exists_eq_left, mem_principal_sets, set.pure_def, singleton_subset_iff, traverse_nil] },
case cons : b fs ih t {
assume ht,
rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩,
rcases mem_map_sets_iff.1 hu with ⟨w, hw, hwu⟩,
rcases ih v hv with ⟨us, hus, hu⟩,
exact ⟨w :: us, forall₂.cons hw hus, subset.trans (set.seq_mono hwu hu) ht⟩ } },
{ rintros ⟨us, hus, hs⟩,
exact mem_sets_of_superset (mem_traverse_sets _ _ hus) hs }
end
lemma sequence_mono :
∀(as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs
| [] [] forall₂.nil := le_refl _
| (a::as) (b::bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs)
end filter
|
201cf95cfd0d3171dd0215320e30064058a440aa
|
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
|
/tests/lean/var2.lean
|
836f1151e628586304f1d5d1d79efbf2822ad68b
|
[
"Apache-2.0"
] |
permissive
|
respu/lean
|
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
|
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
|
refs/heads/master
| 1,610,882,451,231
| 1,427,747,084,000
| 1,427,747,429,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 186
|
lean
|
import logic
context
universe l
variable A : Type.{l}
variable a : A
parameter B : Type.{l}
parameter b : B
definition foo := fun (H : A = B), cast H a = b
end
check foo
|
4ca6f906e6b6e98d9b75af8904d36b0754167b10
|
cf39355caa609c0f33405126beee2739aa3cb77e
|
/library/init/data/nat/lemmas.lean
|
93231a9b8e28b95a62c00b815c29304a4b565a6e
|
[
"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
| 48,955
|
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, Jeremy Avigad
-/
prelude
import init.data.nat.basic init.data.nat.div init.meta init.algebra.functions
universes u
namespace nat
attribute [pre_smt] nat_zero_eq_zero
/-! addition -/
protected lemma add_comm : ∀ n m : ℕ, n + m = m + n
| n 0 := eq.symm (nat.zero_add n)
| n (m+1) :=
suffices succ (n + m) = succ (m + n), from
eq.symm (succ_add m n) ▸ this,
congr_arg succ (add_comm n m)
protected lemma add_assoc : ∀ n m k : ℕ, (n + m) + k = n + (m + k)
| n m 0 := rfl
| n m (succ k) := by rw [add_succ, add_succ, add_assoc]; refl
protected lemma add_left_comm : ∀ (n m k : ℕ), n + (m + k) = m + (n + k) :=
left_comm nat.add nat.add_comm nat.add_assoc
protected lemma add_left_cancel : ∀ {n m k : ℕ}, n + m = n + k → m = k
| 0 m k := by simp [nat.zero_add] {contextual := tt}
| (succ n) m k := λ h,
have n+m = n+k, by { simp [succ_add] at h, assumption },
add_left_cancel this
protected lemma add_right_cancel {n m k : ℕ} (h : n + m = k + m) : n = k :=
have m + n = m + k, by rwa [nat.add_comm n m, nat.add_comm k m] at h,
nat.add_left_cancel this
lemma succ_ne_zero (n : ℕ) : succ n ≠ 0 :=
assume h, nat.no_confusion h
lemma succ_ne_self : ∀ n : ℕ, succ n ≠ n
| 0 h := absurd h (nat.succ_ne_zero 0)
| (n+1) h := succ_ne_self n (nat.no_confusion h (λ h, h))
protected lemma one_ne_zero : 1 ≠ (0 : ℕ) :=
assume h, nat.no_confusion h
protected lemma zero_ne_one : 0 ≠ (1 : ℕ) :=
assume h, nat.no_confusion h
protected lemma eq_zero_of_add_eq_zero_right : ∀ {n m : ℕ}, n + m = 0 → n = 0
| 0 m := by simp [nat.zero_add]
| (n+1) m := λ h,
begin
exfalso,
rw [add_one, succ_add] at h,
apply succ_ne_zero _ h
end
protected lemma eq_zero_of_add_eq_zero_left {n m : ℕ} (h : n + m = 0) : m = 0 :=
@nat.eq_zero_of_add_eq_zero_right m n (nat.add_comm n m ▸ h)
protected theorem add_right_comm : ∀ (n m k : ℕ), n + m + k = n + k + m :=
right_comm nat.add nat.add_comm nat.add_assoc
theorem eq_zero_of_add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 ∧ m = 0 :=
⟨nat.eq_zero_of_add_eq_zero_right H, nat.eq_zero_of_add_eq_zero_left H⟩
/-! multiplication -/
protected lemma mul_zero (n : ℕ) : n * 0 = 0 :=
rfl
lemma mul_succ (n m : ℕ) : n * succ m = n * m + n :=
rfl
protected theorem zero_mul : ∀ (n : ℕ), 0 * n = 0
| 0 := rfl
| (succ n) := by rw [mul_succ, zero_mul]
private meta def sort_add :=
`[simp [nat.add_assoc, nat.add_comm, nat.add_left_comm]]
lemma succ_mul : ∀ (n m : ℕ), (succ n) * m = (n * m) + m
| n 0 := rfl
| n (succ m) :=
begin
simp [mul_succ, add_succ, succ_mul n m],
sort_add
end
protected lemma right_distrib : ∀ (n m k : ℕ), (n + m) * k = n * k + m * k
| n m 0 := rfl
| n m (succ k) :=
begin simp [mul_succ, right_distrib n m k], sort_add end
protected lemma left_distrib : ∀ (n m k : ℕ), n * (m + k) = n * m + n * k
| 0 m k := by simp [nat.zero_mul]
| (succ n) m k :=
begin simp [succ_mul, left_distrib n m k], sort_add end
protected lemma mul_comm : ∀ (n m : ℕ), n * m = m * n
| n 0 := by rw [nat.zero_mul, nat.mul_zero]
| n (succ m) := by simp [mul_succ, succ_mul, mul_comm n m]
protected lemma mul_assoc : ∀ (n m k : ℕ), (n * m) * k = n * (m * k)
| n m 0 := rfl
| n m (succ k) := by simp [mul_succ, nat.left_distrib, mul_assoc n m k]
protected lemma mul_one : ∀ (n : ℕ), n * 1 = n := nat.zero_add
protected lemma one_mul (n : ℕ) : 1 * n = n :=
by rw [nat.mul_comm, nat.mul_one]
theorem succ_add_eq_succ_add (n m : ℕ) : succ n + m = n + succ m :=
by simp [succ_add, add_succ]
theorem eq_zero_of_mul_eq_zero : ∀ {n m : ℕ}, n * m = 0 → n = 0 ∨ m = 0
| 0 m := λ h, or.inl rfl
| (succ n) m :=
begin
rw succ_mul, intro h,
exact or.inr (nat.eq_zero_of_add_eq_zero_left h)
end
/-! properties of inequality -/
protected lemma le_of_eq {n m : ℕ} (p : n = m) : n ≤ m :=
p ▸ less_than_or_equal.refl
lemma le_succ_of_le {n m : ℕ} (h : n ≤ m) : n ≤ succ m :=
nat.le_trans h (le_succ m)
lemma le_of_succ_le {n m : ℕ} (h : succ n ≤ m) : n ≤ m :=
nat.le_trans (le_succ n) h
protected lemma le_of_lt {n m : ℕ} (h : n < m) : n ≤ m :=
le_of_succ_le h
lemma lt.step {n m : ℕ} : n < m → n < succ m := less_than_or_equal.step
protected lemma eq_zero_or_pos (n : ℕ) : n = 0 ∨ 0 < n :=
by {cases n, exact or.inl rfl, exact or.inr (succ_pos _)}
protected lemma pos_of_ne_zero {n : nat} : n ≠ 0 → 0 < n :=
or.resolve_left n.eq_zero_or_pos
protected lemma lt_trans {n m k : ℕ} (h₁ : n < m) : m < k → n < k :=
nat.le_trans (less_than_or_equal.step h₁)
protected lemma lt_of_le_of_lt {n m k : ℕ} (h₁ : n ≤ m) : m < k → n < k :=
nat.le_trans (succ_le_succ h₁)
lemma lt.base (n : ℕ) : n < succ n := nat.le_refl (succ n)
lemma lt_succ_self (n : ℕ) : n < succ n := lt.base n
protected lemma le_antisymm {n m : ℕ} (h₁ : n ≤ m) : m ≤ n → n = m :=
less_than_or_equal.cases_on h₁ (λ a, rfl) (λ a b c, absurd (nat.lt_of_le_of_lt b c) (nat.lt_irrefl n))
protected lemma lt_or_ge : ∀ (a b : ℕ), a < b ∨ b ≤ a
| a 0 := or.inr a.zero_le
| a (b+1) :=
match lt_or_ge a b with
| or.inl h := or.inl (le_succ_of_le h)
| or.inr h :=
match nat.eq_or_lt_of_le h with
| or.inl h1 := or.inl (h1 ▸ lt_succ_self b)
| or.inr h1 := or.inr h1
end
end
protected lemma le_total {m n : ℕ} : m ≤ n ∨ n ≤ m :=
or.imp_left nat.le_of_lt (nat.lt_or_ge m n)
protected lemma lt_of_le_and_ne {m n : ℕ} (h1 : m ≤ n) : m ≠ n → m < n :=
or.resolve_right (or.swap (nat.eq_or_lt_of_le h1))
protected lemma lt_iff_le_not_le {m n : ℕ} : m < n ↔ (m ≤ n ∧ ¬ n ≤ m) :=
⟨λ hmn, ⟨nat.le_of_lt hmn, λ hnm, nat.lt_irrefl _ (nat.lt_of_le_of_lt hnm hmn)⟩,
λ ⟨hmn, hnm⟩, nat.lt_of_le_and_ne hmn (λ heq, hnm (heq ▸ nat.le_refl _))⟩
instance : linear_order ℕ :=
{ le := nat.less_than_or_equal,
le_refl := @nat.le_refl,
le_trans := @nat.le_trans,
le_antisymm := @nat.le_antisymm,
le_total := @nat.le_total,
lt := nat.lt,
lt_iff_le_not_le := @nat.lt_iff_le_not_le,
decidable_lt := nat.decidable_lt,
decidable_le := nat.decidable_le,
decidable_eq := nat.decidable_eq }
protected lemma eq_zero_of_le_zero {n : nat} (h : n ≤ 0) : n = 0 :=
le_antisymm h n.zero_le
lemma succ_lt_succ {a b : ℕ} : a < b → succ a < succ b :=
succ_le_succ
lemma lt_of_succ_lt {a b : ℕ} : succ a < b → a < b :=
le_of_succ_le
lemma lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b :=
le_of_succ_le_succ
lemma pred_lt_pred : ∀ {n m : ℕ}, n ≠ 0 → n < m → pred n < pred m
| 0 _ h₁ h := absurd rfl h₁
| n 0 h₁ h := absurd h n.not_lt_zero
| (succ n) (succ m) _ h := lt_of_succ_lt_succ h
lemma lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h
lemma succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h
protected lemma le_add_right : ∀ (n k : ℕ), n ≤ n + k
| n 0 := nat.le_refl n
| n (k+1) := le_succ_of_le (le_add_right n k)
protected lemma le_add_left (n m : ℕ): n ≤ m + n :=
nat.add_comm n m ▸ n.le_add_right m
lemma le.dest : ∀ {n m : ℕ}, n ≤ m → ∃ k, n + k = m
| n _ less_than_or_equal.refl := ⟨0, rfl⟩
| n _ (less_than_or_equal.step h) :=
match le.dest h with
| ⟨w, hw⟩ := ⟨succ w, hw ▸ add_succ n w⟩
end
protected lemma le.intro {n m k : ℕ} (h : n + k = m) : n ≤ m :=
h ▸ n.le_add_right k
protected lemma add_le_add_left {n m : ℕ} (h : n ≤ m) (k : ℕ) : k + n ≤ k + m :=
match le.dest h with
| ⟨w, hw⟩ := @le.intro _ _ w begin rw [nat.add_assoc, hw] end
end
protected lemma add_le_add_right {n m : ℕ} (h : n ≤ m) (k : ℕ) : n + k ≤ m + k :=
begin rw [nat.add_comm n k, nat.add_comm m k], apply nat.add_le_add_left h end
protected lemma le_of_add_le_add_left {k n m : ℕ} (h : k + n ≤ k + m) : n ≤ m :=
match le.dest h with
| ⟨w, hw⟩ := @le.intro _ _ w
begin
rw [nat.add_assoc] at hw,
apply nat.add_left_cancel hw
end
end
protected lemma le_of_add_le_add_right {k n m : ℕ} : n + k ≤ m + k → n ≤ m :=
begin
rw [nat.add_comm _ k, nat.add_comm _ k],
apply nat.le_of_add_le_add_left
end
protected lemma add_le_add_iff_right {k n m : ℕ} : n + k ≤ m + k ↔ n ≤ m :=
⟨ nat.le_of_add_le_add_right , assume h, nat.add_le_add_right h _ ⟩
protected theorem lt_of_add_lt_add_left {k n m : ℕ} (h : k + n < k + m) : n < m :=
let h' := nat.le_of_lt h in
nat.lt_of_le_and_ne
(nat.le_of_add_le_add_left h')
(λ heq, nat.lt_irrefl (k + m) begin rw heq at h, assumption end)
protected lemma lt_of_add_lt_add_right {a b c : ℕ} (h : a + b < c + b) : a < c :=
nat.lt_of_add_lt_add_left $
show b + a < b + c, by rwa [nat.add_comm b a, nat.add_comm b c]
protected lemma add_lt_add_left {n m : ℕ} (h : n < m) (k : ℕ) : k + n < k + m :=
lt_of_succ_le (add_succ k n ▸ nat.add_le_add_left (succ_le_of_lt h) k)
protected lemma add_lt_add_right {n m : ℕ} (h : n < m) (k : ℕ) : n + k < m + k :=
nat.add_comm k m ▸ nat.add_comm k n ▸ nat.add_lt_add_left h k
protected lemma lt_add_of_pos_right {n k : ℕ} (h : 0 < k) : n < n + k :=
nat.add_lt_add_left h n
protected lemma lt_add_of_pos_left {n k : ℕ} (h : 0 < k) : n < k + n :=
by rw nat.add_comm; exact nat.lt_add_of_pos_right h
protected lemma add_lt_add {a b c d : ℕ} (h₁ : a < b) (h₂ : c < d) : a + c < b + d :=
lt_trans (nat.add_lt_add_right h₁ c) (nat.add_lt_add_left h₂ b)
protected lemma add_le_add {a b c d : ℕ} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d :=
le_trans (nat.add_le_add_right h₁ c) (nat.add_le_add_left h₂ b)
protected lemma zero_lt_one : 0 < (1:nat) :=
zero_lt_succ 0
protected lemma mul_le_mul_left {n m : ℕ} (k : ℕ) (h : n ≤ m) : k * n ≤ k * m :=
match le.dest h with
| ⟨l, hl⟩ :=
have k * n + k * l = k * m, by rw [← nat.left_distrib, hl],
le.intro this
end
protected lemma mul_le_mul_right {n m : ℕ} (k : ℕ) (h : n ≤ m) : n * k ≤ m * k :=
nat.mul_comm k m ▸ nat.mul_comm k n ▸ k.mul_le_mul_left h
protected lemma mul_lt_mul_of_pos_left {n m k : ℕ} (h : n < m) (hk : 0 < k) : k * n < k * m :=
nat.lt_of_lt_of_le (nat.lt_add_of_pos_right hk)
(mul_succ k n ▸ nat.mul_le_mul_left k (succ_le_of_lt h))
protected lemma mul_lt_mul_of_pos_right {n m k : ℕ} (h : n < m) (hk : 0 < k) : n * k < m * k :=
nat.mul_comm k m ▸ nat.mul_comm k n ▸ nat.mul_lt_mul_of_pos_left h hk
protected lemma le_of_mul_le_mul_left {a b c : ℕ} (h : c * a ≤ c * b) (hc : 0 < c) : a ≤ b :=
not_lt.1
(assume h1 : b < a,
have h2 : c * b < c * a, from nat.mul_lt_mul_of_pos_left h1 hc,
not_le_of_gt h2 h)
lemma le_of_lt_succ {m n : nat} : m < succ n → m ≤ n :=
le_of_succ_le_succ
protected theorem eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : 0 < n) (H : n * m = n * k) : m = k :=
le_antisymm (nat.le_of_mul_le_mul_left (le_of_eq H) Hn)
(nat.le_of_mul_le_mul_left (le_of_eq H.symm) Hn)
protected lemma mul_pos {a b : ℕ} (ha : 0 < a) (hb : 0 < b) : 0 < a * b :=
have h : 0 * b < a * b, from nat.mul_lt_mul_of_pos_right ha hb,
by rwa nat.zero_mul at h
theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m :=
nat.cases_on n less_than_or_equal.step (λ a, succ_le_succ)
theorem le_lt_antisymm {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n) : false :=
nat.lt_irrefl n (nat.lt_of_le_of_lt h₁ h₂)
theorem lt_le_antisymm {n m : ℕ} (h₁ : n < m) (h₂ : m ≤ n) : false :=
le_lt_antisymm h₂ h₁
protected theorem lt_asymm {n m : ℕ} (h₁ : n < m) : ¬ m < n :=
le_lt_antisymm (nat.le_of_lt h₁)
protected def lt_ge_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : b ≤ a → C) : C :=
decidable.by_cases h₁ (λ h, h₂ (or.elim (nat.lt_or_ge a b) (λ a, absurd a h) (λ a, a)))
protected def lt_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a = b → C)
(h₃ : b < a → C) : C :=
nat.lt_ge_by_cases h₁ (λ h₁,
nat.lt_ge_by_cases h₃ (λ h, h₂ (nat.le_antisymm h h₁)))
protected theorem lt_trichotomy (a b : ℕ) : a < b ∨ a = b ∨ b < a :=
nat.lt_by_cases (λ h, or.inl h) (λ h, or.inr (or.inl h)) (λ h, or.inr (or.inr h))
protected theorem eq_or_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ∨ b < a :=
(nat.lt_trichotomy a b).resolve_left hnlt
theorem lt_succ_of_lt {a b : nat} (h : a < b) : a < succ b := le_succ_of_le h
lemma one_pos : 0 < 1 := nat.zero_lt_one
protected lemma mul_le_mul_of_nonneg_left {a b c : ℕ} (h₁ : a ≤ b) : c * a ≤ c * b :=
begin
by_cases hba : b ≤ a, { simp [le_antisymm hba h₁] },
by_cases hc0 : c ≤ 0, { simp [le_antisymm hc0 c.zero_le, nat.zero_mul] },
exact (le_not_le_of_lt
(nat.mul_lt_mul_of_pos_left (lt_of_le_not_le h₁ hba) (lt_of_le_not_le c.zero_le hc0))).left,
end
protected lemma mul_le_mul_of_nonneg_right {a b c : ℕ} (h₁ : a ≤ b) : a * c ≤ b * c :=
begin
by_cases hba : b ≤ a, { simp [le_antisymm hba h₁] },
by_cases hc0 : c ≤ 0, { simp [le_antisymm hc0 c.zero_le, nat.mul_zero] },
exact (le_not_le_of_lt
(nat.mul_lt_mul_of_pos_right (lt_of_le_not_le h₁ hba) (lt_of_le_not_le c.zero_le hc0))).left,
end
protected lemma mul_lt_mul {a b c d : ℕ} (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) :
a * b < c * d :=
calc
a * b < c * b : nat.mul_lt_mul_of_pos_right hac pos_b
... ≤ c * d : nat.mul_le_mul_of_nonneg_left hbd
protected lemma mul_lt_mul' {a b c d : ℕ} (h1 : a ≤ c) (h2 : b < d) (h3 : 0 < c) :
a * b < c * d :=
calc
a * b ≤ c * b : nat.mul_le_mul_of_nonneg_right h1
... < c * d : nat.mul_lt_mul_of_pos_left h2 h3
-- 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) : a * b ≤ c * d :=
calc
a * b ≤ c * b : nat.mul_le_mul_of_nonneg_right hac
... ≤ c * d : nat.mul_le_mul_of_nonneg_left hbd
/-! bit0/bit1 properties -/
protected lemma bit1_eq_succ_bit0 (n : ℕ) : bit1 n = succ (bit0 n) :=
rfl
protected lemma bit1_succ_eq (n : ℕ) : bit1 (succ n) = succ (succ (bit1 n)) :=
eq.trans (nat.bit1_eq_succ_bit0 (succ n)) (congr_arg succ (nat.bit0_succ_eq n))
protected lemma bit1_ne_one : ∀ {n : ℕ}, n ≠ 0 → bit1 n ≠ 1
| 0 h h1 := absurd rfl h
| (n+1) h h1 := nat.no_confusion h1 (λ h2, absurd h2 (succ_ne_zero _))
protected lemma bit0_ne_one : ∀ n : ℕ, bit0 n ≠ 1
| 0 h := absurd h (ne.symm nat.one_ne_zero)
| (n+1) h :=
have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h,
nat.no_confusion h1
(λ h2, absurd h2 (succ_ne_zero (n + n)))
protected lemma add_self_ne_one : ∀ (n : ℕ), n + n ≠ 1
| 0 h := nat.no_confusion h
| (n+1) h :=
have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h,
nat.no_confusion h1 (λ h2, absurd h2 (nat.succ_ne_zero (n + n)))
protected lemma bit1_ne_bit0 : ∀ (n m : ℕ), bit1 n ≠ bit0 m
| 0 m h := absurd h (ne.symm (nat.add_self_ne_one m))
| (n+1) 0 h :=
have h1 : succ (bit0 (succ n)) = 0, from h,
absurd h1 (nat.succ_ne_zero _)
| (n+1) (m+1) h :=
have h1 : succ (succ (bit1 n)) = succ (succ (bit0 m)), from
nat.bit0_succ_eq m ▸ nat.bit1_succ_eq n ▸ h,
have h2 : bit1 n = bit0 m, from
nat.no_confusion h1 (λ h2', nat.no_confusion h2' (λ h2'', h2'')),
absurd h2 (bit1_ne_bit0 n m)
protected lemma bit0_ne_bit1 : ∀ (n m : ℕ), bit0 n ≠ bit1 m :=
λ n m : nat, ne.symm (nat.bit1_ne_bit0 m n)
protected lemma bit0_inj : ∀ {n m : ℕ}, bit0 n = bit0 m → n = m
| 0 0 h := rfl
| 0 (m+1) h := by contradiction
| (n+1) 0 h := by contradiction
| (n+1) (m+1) h :=
have succ (succ (n + n)) = succ (succ (m + m)),
by { unfold bit0 at h, simp [add_one, add_succ, succ_add] at h,
have aux : n + n = m + m := h, rw aux },
have n + n = m + m, by iterate { injection this with this },
have n = m, from bit0_inj this,
by rw this
protected lemma bit1_inj : ∀ {n m : ℕ}, bit1 n = bit1 m → n = m :=
λ n m h,
have succ (bit0 n) = succ (bit0 m), begin simp [nat.bit1_eq_succ_bit0] at h, rw h end,
have bit0 n = bit0 m, by injection this,
nat.bit0_inj this
protected lemma bit0_ne {n m : ℕ} : n ≠ m → bit0 n ≠ bit0 m :=
λ h₁ h₂, absurd (nat.bit0_inj h₂) h₁
protected lemma bit1_ne {n m : ℕ} : n ≠ m → bit1 n ≠ bit1 m :=
λ h₁ h₂, absurd (nat.bit1_inj h₂) h₁
protected lemma zero_ne_bit0 {n : ℕ} : n ≠ 0 → 0 ≠ bit0 n :=
λ h, ne.symm (nat.bit0_ne_zero h)
protected lemma zero_ne_bit1 (n : ℕ) : 0 ≠ bit1 n :=
ne.symm (nat.bit1_ne_zero n)
protected lemma one_ne_bit0 (n : ℕ) : 1 ≠ bit0 n :=
ne.symm (nat.bit0_ne_one n)
protected lemma one_ne_bit1 {n : ℕ} : n ≠ 0 → 1 ≠ bit1 n :=
λ h, ne.symm (nat.bit1_ne_one h)
protected lemma one_lt_bit1 : ∀ {n : nat}, n ≠ 0 → 1 < bit1 n
| 0 h := by contradiction
| (succ n) h :=
begin
rw nat.bit1_succ_eq,
apply succ_lt_succ,
apply zero_lt_succ
end
protected lemma one_lt_bit0 : ∀ {n : nat}, n ≠ 0 → 1 < bit0 n
| 0 h := by contradiction
| (succ n) h :=
begin
rw nat.bit0_succ_eq,
apply succ_lt_succ,
apply zero_lt_succ
end
protected lemma bit0_lt {n m : nat} (h : n < m) : bit0 n < bit0 m :=
nat.add_lt_add h h
protected lemma bit1_lt {n m : nat} (h : n < m) : bit1 n < bit1 m :=
succ_lt_succ (nat.add_lt_add h h)
protected lemma bit0_lt_bit1 {n m : nat} (h : n ≤ m) : bit0 n < bit1 m :=
lt_succ_of_le (nat.add_le_add h h)
protected lemma bit1_lt_bit0 : ∀ {n m : nat}, n < m → bit1 n < bit0 m
| n 0 h := absurd h n.not_lt_zero
| n (succ m) h :=
have n ≤ m, from le_of_lt_succ h,
have succ (n + n) ≤ succ (m + m), from succ_le_succ (nat.add_le_add this this),
have succ (n + n) ≤ succ m + m, {rw succ_add, assumption},
show succ (n + n) < succ (succ m + m), from lt_succ_of_le this
protected lemma one_le_bit1 (n : ℕ) : 1 ≤ bit1 n :=
show 1 ≤ succ (bit0 n), from
succ_le_succ (bit0 n).zero_le
protected lemma one_le_bit0 : ∀ (n : ℕ), n ≠ 0 → 1 ≤ bit0 n
| 0 h := absurd rfl h
| (n+1) h :=
suffices 1 ≤ succ (succ (bit0 n)), from
eq.symm (nat.bit0_succ_eq n) ▸ this,
succ_le_succ (bit0 n).succ.zero_le
/-! successor and predecessor -/
@[simp]
lemma pred_zero : pred 0 = 0 :=
rfl
@[simp]
lemma pred_succ (n : ℕ) : pred (succ n) = n :=
rfl
theorem add_one_ne_zero (n : ℕ) : n + 1 ≠ 0 := succ_ne_zero _
theorem eq_zero_or_eq_succ_pred (n : ℕ) : n = 0 ∨ n = succ (pred n) :=
by cases n; simp
theorem exists_eq_succ_of_ne_zero {n : ℕ} (H : n ≠ 0) : ∃k : ℕ, n = succ k :=
⟨_, (eq_zero_or_eq_succ_pred _).resolve_left H⟩
def discriminate {B : Sort u} {n : ℕ} (H1: n = 0 → B) (H2 : ∀m, n = succ m → B) : B :=
by induction h : n; [exact H1 h, exact H2 _ h]
theorem one_succ_zero : 1 = succ 0 := rfl
theorem pred_inj : ∀ {a b : nat}, 0 < a → 0 < b → nat.pred a = nat.pred b → a = b
| (succ a) (succ b) ha hb h := have a = b, from h, by rw this
| (succ a) 0 ha hb h := absurd hb (lt_irrefl _)
| 0 (succ b) ha hb h := absurd ha (lt_irrefl _)
| 0 0 ha hb h := rfl
/-! subtraction
Many lemmas are proven more generally in mathlib `algebra/order/sub` -/
@[simp] protected lemma zero_sub : ∀ a : ℕ, 0 - a = 0
| 0 := rfl
| (a+1) := congr_arg pred (zero_sub a)
lemma sub_lt_succ (a b : ℕ) : a - b < succ a :=
lt_succ_of_le (a.sub_le b)
protected theorem sub_le_sub_right {n m : ℕ} (h : n ≤ m) : ∀ k, n - k ≤ m - k
| 0 := h
| (succ z) := pred_le_pred (sub_le_sub_right z)
@[simp]
protected theorem sub_zero (n : ℕ) : n - 0 = n :=
rfl
theorem sub_succ (n m : ℕ) : n - succ m = pred (n - m) :=
rfl
theorem succ_sub_succ (n m : ℕ) : succ n - succ m = n - m :=
succ_sub_succ_eq_sub n m
protected theorem sub_self : ∀ (n : ℕ), n - n = 0
| 0 := by rw nat.sub_zero
| (succ n) := by rw [succ_sub_succ, sub_self n]
/- TODO(Leo): remove the following ematch annotations as soon as we have
arithmetic theory in the smt_stactic -/
@[ematch_lhs]
protected theorem add_sub_add_right : ∀ (n k m : ℕ), (n + k) - (m + k) = n - m
| n 0 m := by rw [nat.add_zero, nat.add_zero]
| n (succ k) m := by rw [add_succ, add_succ, succ_sub_succ, add_sub_add_right n k m]
@[ematch_lhs]
protected theorem add_sub_add_left (k n m : ℕ) : (k + n) - (k + m) = n - m :=
by rw [nat.add_comm k n, nat.add_comm k m, nat.add_sub_add_right]
@[ematch_lhs]
protected theorem add_sub_cancel (n m : ℕ) : n + m - m = n :=
suffices n + m - (0 + m) = n, from
by rwa [nat.zero_add] at this,
by rw [nat.add_sub_add_right, nat.sub_zero]
@[ematch_lhs]
protected theorem add_sub_cancel_left (n m : ℕ) : n + m - n = m :=
show n + m - (n + 0) = m, from
by rw [nat.add_sub_add_left, nat.sub_zero]
protected theorem sub_sub : ∀ (n m k : ℕ), n - m - k = n - (m + k)
| n m 0 := by rw [nat.add_zero, nat.sub_zero]
| n m (succ k) := by rw [add_succ, nat.sub_succ, nat.sub_succ, sub_sub n m k]
protected theorem le_of_le_of_sub_le_sub_right {n m k : ℕ}
(h₀ : k ≤ m)
(h₁ : n - k ≤ m - k)
: n ≤ m :=
begin
revert k m,
induction n with n ; intros k m h₀ h₁,
{ exact m.zero_le },
{ cases k with k,
{ apply h₁ },
cases m with m,
{ cases not_succ_le_zero _ h₀ },
{ simp [succ_sub_succ] at h₁,
apply succ_le_succ,
apply n_ih _ h₁,
apply le_of_succ_le_succ h₀ }, }
end
protected theorem sub_le_sub_iff_right {n m k : ℕ} (h : k ≤ m) : n - k ≤ m - k ↔ n ≤ m :=
⟨ nat.le_of_le_of_sub_le_sub_right h , assume h, nat.sub_le_sub_right h k ⟩
protected theorem sub_self_add (n m : ℕ) : n - (n + m) = 0 :=
show (n + 0) - (n + m) = 0, from
by rw [nat.add_sub_add_left, nat.zero_sub]
protected theorem le_sub_iff_right {x y k : ℕ} (h : k ≤ y) : x ≤ y - k ↔ x + k ≤ y :=
by rw [← nat.add_sub_cancel x k, nat.sub_le_sub_iff_right h, nat.add_sub_cancel]
protected lemma sub_lt_of_pos_le (a b : ℕ) (h₀ : 0 < a) (h₁ : a ≤ b)
: b - a < b :=
begin
apply nat.sub_lt _ h₀,
apply lt_of_lt_of_le h₀ h₁
end
protected theorem sub_one (n : ℕ) : n - 1 = pred n :=
rfl
theorem succ_sub_one (n : ℕ) : succ n - 1 = n :=
rfl
theorem succ_pred_eq_of_pos : ∀ {n : ℕ}, 0 < n → succ (pred n) = n
| 0 h := absurd h (lt_irrefl 0)
| (succ k) h := rfl
protected theorem sub_eq_zero_of_le {n m : ℕ} (h : n ≤ m) : n - m = 0 :=
exists.elim (nat.le.dest h)
(assume k, assume hk : n + k = m, by rw [← hk, nat.sub_self_add])
protected theorem le_of_sub_eq_zero : ∀{n m : ℕ}, n - m = 0 → n ≤ m
| n 0 H := begin rw [nat.sub_zero] at H, simp [H] end
| 0 (m+1) H := (m + 1).zero_le
| (n+1) (m+1) H := nat.add_le_add_right
(le_of_sub_eq_zero begin simp [nat.add_sub_add_right] at H, exact H end) _
protected theorem sub_eq_zero_iff_le {n m : ℕ} : n - m = 0 ↔ n ≤ m :=
⟨nat.le_of_sub_eq_zero, nat.sub_eq_zero_of_le⟩
protected theorem add_sub_of_le {n m : ℕ} (h : n ≤ m) : n + (m - n) = m :=
exists.elim (nat.le.dest h)
(assume k, assume hk : n + k = m,
by rw [← hk, nat.add_sub_cancel_left])
protected theorem sub_add_cancel {n m : ℕ} (h : m ≤ n) : n - m + m = n :=
by rw [nat.add_comm, nat.add_sub_of_le h]
protected theorem add_sub_assoc {m k : ℕ} (h : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) :=
exists.elim (nat.le.dest h)
(assume l, assume hl : k + l = m,
by rw [← hl, nat.add_sub_cancel_left, nat.add_comm k, ← nat.add_assoc, nat.add_sub_cancel])
protected lemma sub_eq_iff_eq_add {a b c : ℕ} (ab : b ≤ a) : a - b = c ↔ a = c + b :=
⟨assume c_eq, begin rw [c_eq.symm, nat.sub_add_cancel ab] end,
assume a_eq, begin rw [a_eq, nat.add_sub_cancel] end⟩
protected lemma lt_of_sub_eq_succ {m n l : ℕ} (H : m - n = nat.succ l) : n < m :=
not_le.1
(assume (H' : n ≥ m), begin simp [nat.sub_eq_zero_of_le H'] at H, contradiction end)
protected theorem sub_le_sub_left {n m : ℕ} (k) (h : n ≤ m) : k - m ≤ k - n :=
by induction h; [refl, exact le_trans (pred_le _) h_ih]
theorem succ_sub_sub_succ (n m k : ℕ) : succ n - m - succ k = n - m - k :=
by rw [nat.sub_sub, nat.sub_sub, add_succ, succ_sub_succ]
protected theorem sub.right_comm (m n k : ℕ) : m - n - k = m - k - n :=
by rw [nat.sub_sub, nat.sub_sub, nat.add_comm]
theorem succ_sub {m n : ℕ} (h : n ≤ m) : succ m - n = succ (m - n) :=
exists.elim (nat.le.dest h)
(assume k, assume hk : n + k = m,
by rw [← hk, nat.add_sub_cancel_left, ← add_succ, nat.add_sub_cancel_left])
protected theorem sub_pos_of_lt {m n : ℕ} (h : m < n) : 0 < n - m :=
have 0 + m < n - m + m, begin rw [nat.zero_add, nat.sub_add_cancel (le_of_lt h)], exact h end,
nat.lt_of_add_lt_add_right this
protected theorem sub_sub_self {n m : ℕ} (h : m ≤ n) : n - (n - m) = m :=
(nat.sub_eq_iff_eq_add (nat.sub_le _ _)).2 (nat.add_sub_of_le h).symm
protected theorem sub_add_comm {n m k : ℕ} (h : k ≤ n) : n + m - k = n - k + m :=
(nat.sub_eq_iff_eq_add (nat.le_trans h (nat.le_add_right _ _))).2
(by rwa [nat.add_right_comm, nat.sub_add_cancel])
theorem sub_one_sub_lt {n i} (h : i < n) : n - 1 - i < n :=
begin
rw nat.sub_sub,
apply nat.sub_lt,
apply lt_of_lt_of_le (nat.zero_lt_succ _) h,
rw nat.add_comm,
apply nat.zero_lt_succ
end
theorem mul_pred_left : ∀ (n m : ℕ), pred n * m = n * m - m
| 0 m := by simp [nat.zero_sub, pred_zero, nat.zero_mul]
| (succ n) m := by rw [pred_succ, succ_mul, nat.add_sub_cancel]
theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n :=
by rw [nat.mul_comm, mul_pred_left, nat.mul_comm]
protected theorem mul_sub_right_distrib : ∀ (n m k : ℕ), (n - m) * k = n * k - m * k
| n 0 k := by simp [nat.sub_zero, nat.zero_mul]
| n (succ m) k := by rw [nat.sub_succ, mul_pred_left, mul_sub_right_distrib, succ_mul, nat.sub_sub]
protected theorem mul_sub_left_distrib (n m k : ℕ) : n * (m - k) = n * m - n * k :=
by rw [nat.mul_comm, nat.mul_sub_right_distrib, nat.mul_comm m n, nat.mul_comm n k]
protected theorem mul_self_sub_mul_self_eq (a b : nat) : a * a - b * b = (a + b) * (a - b) :=
by rw [nat.mul_sub_left_distrib, nat.right_distrib, nat.right_distrib, nat.mul_comm b a, nat.add_comm (a*a) (a*b),
nat.add_sub_add_left]
theorem succ_mul_succ_eq (a b : nat) : succ a * succ b = a * b + a + b + 1 :=
begin
rw [← add_one, ← add_one],
simp [nat.right_distrib, nat.left_distrib, nat.add_left_comm, nat.mul_one, nat.one_mul, nat.add_assoc],
end
/-! min -/
protected lemma zero_min (a : ℕ) : min 0 a = 0 :=
min_eq_left a.zero_le
protected lemma min_zero (a : ℕ) : min a 0 = 0 :=
min_eq_right a.zero_le
-- Distribute succ over min
theorem min_succ_succ (x y : ℕ) : min (succ x) (succ y) = succ (min x y) :=
have f : x ≤ y → min (succ x) (succ y) = succ (min x y), from λp,
calc min (succ x) (succ y)
= succ x : if_pos (succ_le_succ p)
... = succ (min x y) : congr_arg succ (eq.symm (if_pos p)),
have g : ¬ (x ≤ y) → min (succ x) (succ y) = succ (min x y), from λp,
calc min (succ x) (succ y)
= succ y : if_neg (λeq, p (pred_le_pred eq))
... = succ (min x y) : congr_arg succ (eq.symm (if_neg p)),
decidable.by_cases f g
theorem sub_eq_sub_min (n m : ℕ) : n - m = n - min n m :=
if h : n ≥ m then by rewrite [min_eq_right h]
else by rewrite [nat.sub_eq_zero_of_le (le_of_not_ge h), min_eq_left (le_of_not_ge h), nat.sub_self]
@[simp] protected theorem sub_add_min_cancel (n m : ℕ) : n - m + min n m = n :=
by rw [sub_eq_sub_min, nat.sub_add_cancel (min_le_left n m)]
/-! induction principles -/
def two_step_induction {P : ℕ → Sort u} (H1 : P 0) (H2 : P 1)
(H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : Π (a : ℕ), P a
| 0 := H1
| 1 := H2
| (succ (succ n)) := H3 _ (two_step_induction _) (two_step_induction _)
def sub_induction {P : ℕ → ℕ → Sort u} (H1 : ∀m, P 0 m)
(H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : Π (n m : ℕ), P n m
| 0 m := H1 _
| (succ n) 0 := H2 _
| (succ n) (succ m) := H3 _ _ (sub_induction n m)
protected def strong_rec_on {p : nat → Sort u} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n :=
suffices ∀ n m, m < n → p m, from this (succ n) n (lt_succ_self _),
begin
intros n, induction n with n ih,
{intros m h₁, exact absurd h₁ m.not_lt_zero},
{intros m h₁,
apply or.by_cases (decidable.lt_or_eq_of_le (le_of_lt_succ h₁)),
{intros, apply ih, assumption},
{intros, subst m, apply h _ ih}}
end
protected lemma strong_induction_on {p : nat → Prop} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n :=
nat.strong_rec_on n h
protected lemma case_strong_induction_on {p : nat → Prop} (a : nat)
(hz : p 0)
(hi : ∀ n, (∀ m, m ≤ n → p m) → p (succ n)) : p a :=
nat.strong_induction_on a $ λ n,
match n with
| 0 := λ _, hz
| (n+1) := λ h₁, hi n (λ m h₂, h₁ _ (lt_succ_of_le h₂))
end
/-! mod -/
private lemma mod_core_congr {x y f1 f2} (h1 : x ≤ f1) (h2 : x ≤ f2) :
nat.mod_core y f1 x = nat.mod_core y f2 x :=
begin
cases y, { cases f1; cases f2; refl },
induction f1 with f1 ih generalizing x f2, { cases h1, cases f2; refl },
cases x, { cases f1; cases f2; refl },
cases f2, { cases h2 },
refine if_congr iff.rfl _ rfl,
simp only [succ_sub_succ],
exact ih
(le_trans (nat.sub_le _ _) (le_of_succ_le_succ h1))
(le_trans (nat.sub_le _ _) (le_of_succ_le_succ h2))
end
lemma mod_def (x y : nat) : x % y = if 0 < y ∧ y ≤ x then (x - y) % y else x :=
begin
cases x, { cases y; refl },
cases y, { refl },
refine if_congr iff.rfl (mod_core_congr _ _) rfl; simp [nat.sub_le]
end
@[simp] lemma mod_zero (a : nat) : a % 0 = a :=
begin
rw mod_def,
have h : ¬ (0 < 0 ∧ 0 ≤ a),
simp [lt_irrefl],
simp [if_neg, h]
end
lemma mod_eq_of_lt {a b : nat} (h : a < b) : a % b = a :=
begin
rw mod_def,
have h' : ¬(0 < b ∧ b ≤ a),
simp [not_le_of_gt h],
simp [if_neg, h']
end
@[simp] lemma zero_mod (b : nat) : 0 % b = 0 :=
begin
rw mod_def,
have h : ¬(0 < b ∧ b ≤ 0),
{intro hn, cases hn with l r, exact absurd (lt_of_lt_of_le l r) (lt_irrefl 0)},
simp [if_neg, h]
end
lemma mod_eq_sub_mod {a b : nat} (h : b ≤ a) : a % b = (a - b) % b :=
or.elim b.eq_zero_or_pos
(λb0, by rw [b0, nat.sub_zero])
(λh₂, by rw [mod_def, if_pos (and.intro h₂ h)])
lemma mod_lt (x : nat) {y : nat} (h : 0 < y) : x % y < y :=
begin
induction x using nat.case_strong_induction_on with x ih,
{ rw zero_mod, assumption },
{ by_cases h₁ : succ x < y,
{ rwa [mod_eq_of_lt h₁] },
{ have h₁ : succ x % y = (succ x - y) % y := mod_eq_sub_mod (not_lt.1 h₁),
have : succ x - y ≤ x := le_of_lt_succ (nat.sub_lt (succ_pos x) h),
have h₂ : (succ x - y) % y < y := ih _ this,
rwa [← h₁] at h₂ } }
end
@[simp] theorem mod_self (n : nat) : n % n = 0 :=
by rw [mod_eq_sub_mod (le_refl _), nat.sub_self, zero_mod]
@[simp] lemma mod_one (n : ℕ) : n % 1 = 0 :=
have n % 1 < 1, from (mod_lt n) (succ_pos 0),
nat.eq_zero_of_le_zero (le_of_lt_succ this)
lemma mod_two_eq_zero_or_one (n : ℕ) : n % 2 = 0 ∨ n % 2 = 1 :=
match n % 2, @nat.mod_lt n 2 dec_trivial with
| 0, _ := or.inl rfl
| 1, _ := or.inr rfl
| k+2, h := absurd h dec_trivial
end
theorem mod_le (x y : ℕ) : x % y ≤ x :=
or.elim (lt_or_le x y)
(λxlty, by rw mod_eq_of_lt xlty; refl)
(λylex, or.elim y.eq_zero_or_pos
(λy0, by rw [y0, mod_zero]; refl)
(λypos, le_trans (le_of_lt (mod_lt _ ypos)) ylex))
@[simp] theorem add_mod_right (x z : ℕ) : (x + z) % z = x % z :=
by rw [mod_eq_sub_mod (nat.le_add_left _ _), nat.add_sub_cancel]
@[simp] theorem add_mod_left (x z : ℕ) : (x + z) % x = z % x :=
by rw [nat.add_comm, add_mod_right]
@[simp] theorem add_mul_mod_self_left (x y z : ℕ) : (x + y * z) % y = x % y :=
by {induction z with z ih, rw [nat.mul_zero, nat.add_zero], rw [mul_succ, ← nat.add_assoc, add_mod_right, ih]}
@[simp] theorem add_mul_mod_self_right (x y z : ℕ) : (x + y * z) % z = x % z :=
by rw [nat.mul_comm, add_mul_mod_self_left]
@[simp] theorem mul_mod_right (m n : ℕ) : (m * n) % m = 0 :=
by rw [← nat.zero_add (m*n), add_mul_mod_self_left, zero_mod]
@[simp] theorem mul_mod_left (m n : ℕ) : (m * n) % n = 0 :=
by rw [nat.mul_comm, mul_mod_right]
theorem mul_mod_mul_left (z x y : ℕ) : (z * x) % (z * y) = z * (x % y) :=
if y0 : y = 0 then
by rw [y0, nat.mul_zero, mod_zero, mod_zero]
else if z0 : z = 0 then
by rw [z0, nat.zero_mul, nat.zero_mul, nat.zero_mul, mod_zero]
else x.strong_induction_on $ λn IH,
have y0 : y > 0, from nat.pos_of_ne_zero y0,
have z0 : z > 0, from nat.pos_of_ne_zero z0,
or.elim (le_or_lt y n)
(λyn, by rw [
mod_eq_sub_mod yn,
mod_eq_sub_mod (nat.mul_le_mul_left z yn),
← nat.mul_sub_left_distrib];
exact IH _ (nat.sub_lt (lt_of_lt_of_le y0 yn) y0))
(λyn, by rw [mod_eq_of_lt yn, mod_eq_of_lt (nat.mul_lt_mul_of_pos_left yn z0)])
theorem mul_mod_mul_right (z x y : ℕ) : (x * z) % (y * z) = (x % y) * z :=
by rw [nat.mul_comm x z, nat.mul_comm y z, nat.mul_comm (x % y) z]; apply mul_mod_mul_left
theorem cond_to_bool_mod_two (x : ℕ) [d : decidable (x % 2 = 1)]
: cond (@to_bool (x % 2 = 1) d) 1 0 = x % 2 :=
begin
by_cases h : x % 2 = 1,
{ simp! [*] },
{ cases mod_two_eq_zero_or_one x; simp! [*, nat.zero_ne_one]; contradiction }
end
theorem sub_mul_mod (x k n : ℕ) (h₁ : n*k ≤ x) : (x - n*k) % n = x % n :=
begin
induction k with k,
{ rw [nat.mul_zero, nat.sub_zero] },
{ have h₂ : n * k ≤ x,
{ rw [mul_succ] at h₁,
apply nat.le_trans _ h₁,
apply nat.le_add_right _ n },
have h₄ : x - n * k ≥ n,
{ apply @nat.le_of_add_le_add_right (n*k),
rw [nat.sub_add_cancel h₂],
simp [mul_succ, nat.add_comm] at h₁, simp [h₁] },
rw [mul_succ, ← nat.sub_sub, ← mod_eq_sub_mod h₄, k_ih h₂] }
end
/-! div -/
private lemma div_core_congr {x y f1 f2} (h1 : x ≤ f1) (h2 : x ≤ f2) :
nat.div_core y f1 x = nat.div_core y f2 x :=
begin
cases y, { cases f1; cases f2; refl },
induction f1 with f1 ih generalizing x f2, { cases h1, cases f2; refl },
cases x, { cases f1; cases f2; refl },
cases f2, { cases h2 },
refine if_congr iff.rfl _ rfl,
simp only [succ_sub_succ],
refine congr_arg (+1) _,
exact ih
(le_trans (nat.sub_le _ _) (le_of_succ_le_succ h1))
(le_trans (nat.sub_le _ _) (le_of_succ_le_succ h2))
end
lemma div_def (x y : nat) : x / y = if 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 :=
begin
cases x, { cases y; refl },
cases y, { refl },
refine if_congr iff.rfl (congr_arg (+1) _) rfl,
refine div_core_congr _ _; simp [nat.sub_le]
end
lemma mod_add_div (m k : ℕ)
: m % k + k * (m / k) = m :=
begin
apply nat.strong_induction_on m,
clear m,
intros m IH,
cases decidable.em (0 < k ∧ k ≤ m) with h h',
-- 0 < k ∧ k ≤ m
{ have h' : m - k < m,
{ apply nat.sub_lt _ h.left,
apply lt_of_lt_of_le h.left h.right },
rw [div_def, mod_def, if_pos h, if_pos h],
simp [nat.left_distrib, IH _ h', nat.add_comm, nat.add_left_comm],
rw [nat.add_comm, ← nat.add_sub_assoc h.right, nat.mul_one, nat.add_sub_cancel_left] },
-- ¬ (0 < k ∧ k ≤ m)
{ rw [div_def, mod_def, if_neg h', if_neg h', nat.mul_zero, nat.add_zero] },
end
@[simp] protected lemma div_one (n : ℕ) : n / 1 = n :=
have n % 1 + 1 * (n / 1) = n, from mod_add_div _ _,
by { rwa [mod_one, nat.zero_add, nat.one_mul] at this }
@[simp] protected lemma div_zero (n : ℕ) : n / 0 = 0 :=
begin rw [div_def], simp [lt_irrefl] end
@[simp] protected lemma zero_div (b : ℕ) : 0 / b = 0 :=
eq.trans (div_def 0 b) $ if_neg (and.rec not_le_of_gt)
protected lemma div_le_of_le_mul {m n : ℕ} : ∀ {k}, m ≤ k * n → m / k ≤ n
| 0 h := by simp [nat.div_zero, n.zero_le]
| (succ k) h :=
suffices succ k * (m / succ k) ≤ succ k * n, from nat.le_of_mul_le_mul_left this (zero_lt_succ _),
calc
succ k * (m / succ k) ≤ m % succ k + succ k * (m / succ k) : nat.le_add_left _ _
... = m : by rw mod_add_div
... ≤ succ k * n : h
protected lemma div_le_self : ∀ (m n : ℕ), m / n ≤ m
| m 0 := by simp [nat.div_zero, m.zero_le]
| m (succ n) :=
have m ≤ succ n * m, from calc
m = 1 * m : by rw nat.one_mul
... ≤ succ n * m : m.mul_le_mul_right (succ_le_succ n.zero_le),
nat.div_le_of_le_mul this
lemma div_eq_sub_div {a b : nat} (h₁ : 0 < b) (h₂ : b ≤ a) : a / b = (a - b) / b + 1 :=
begin
rw [div_def a, if_pos],
split ; assumption
end
lemma div_eq_of_lt {a b : ℕ} (h₀ : a < b) : a / b = 0 :=
begin
rw [div_def a, if_neg],
intro h₁,
apply not_le_of_gt h₀ h₁.right
end
-- this is a Galois connection
-- f x ≤ y ↔ x ≤ g y
-- with
-- f x = x * k
-- g y = y / k
theorem le_div_iff_mul_le {x y k : ℕ} (Hk : 0 < k) : x ≤ y / k ↔ x * k ≤ y :=
begin
-- Hk is needed because, despite div being made total, y / 0 := 0
-- x * 0 ≤ y ↔ x ≤ y / 0
-- ↔ 0 ≤ y ↔ x ≤ 0
-- ↔ true ↔ x = 0
-- ↔ x = 0
revert x,
apply nat.strong_induction_on y _,
clear y,
intros y IH x,
cases lt_or_le y k with h h,
-- base case: y < k
{ rw [div_eq_of_lt h],
cases x with x,
{ simp [nat.zero_mul, y.zero_le] },
{ simp [succ_mul, not_succ_le_zero, nat.add_comm],
apply lt_of_lt_of_le h,
apply nat.le_add_right } },
-- step: k ≤ y
{ rw [div_eq_sub_div Hk h],
cases x with x,
{ simp [nat.zero_mul, nat.zero_le] },
{ rw [←add_one, nat.add_le_add_iff_right, IH (y - k) (nat.sub_lt_of_pos_le _ _ Hk h), add_one,
succ_mul, nat.le_sub_iff_right h] } }
end
theorem div_lt_iff_lt_mul {x y k : ℕ} (Hk : 0 < k) : x / k < y ↔ x < y * k :=
by rw [←not_le, not_congr (le_div_iff_mul_le Hk), not_le]
theorem sub_mul_div (x n p : ℕ) (h₁ : n*p ≤ x) : (x - n*p) / n = x / n - p :=
begin
cases nat.eq_zero_or_pos n with h₀ h₀,
{ rw [h₀, nat.div_zero, nat.div_zero, nat.zero_sub] },
{ induction p with p,
{ rw [nat.mul_zero, nat.sub_zero, nat.sub_zero] },
{ have h₂ : n*p ≤ x,
{ transitivity,
{ apply nat.mul_le_mul_left, apply le_succ },
{ apply h₁ } },
have h₃ : x - n * p ≥ n,
{ apply nat.le_of_add_le_add_right,
rw [nat.sub_add_cancel h₂, nat.add_comm],
rw [mul_succ] at h₁,
apply h₁ },
rw [sub_succ, ← p_ih h₂],
rw [@div_eq_sub_div (x - n*p) _ h₀ h₃],
simp [add_one, pred_succ, mul_succ, nat.sub_sub] } }
end
theorem div_mul_le_self : ∀ (m n : ℕ), m / n * n ≤ m
| m 0 := by simp [m.zero_le, nat.zero_mul]
| m (succ n) := (le_div_iff_mul_le $ nat.succ_pos _).1 (le_refl _)
@[simp] theorem add_div_right (x : ℕ) {z : ℕ} (H : 0 < z) : (x + z) / z = succ (x / z) :=
by rw [div_eq_sub_div H (nat.le_add_left _ _), nat.add_sub_cancel]
@[simp] theorem add_div_left (x : ℕ) {z : ℕ} (H : 0 < z) : (z + x) / z = succ (x / z) :=
by rw [nat.add_comm, add_div_right x H]
@[simp] theorem mul_div_right (n : ℕ) {m : ℕ} (H : 0 < m) : m * n / m = n :=
by {induction n; simp [*, mul_succ, nat.mul_zero] }
@[simp] theorem mul_div_left (m : ℕ) {n : ℕ} (H : 0 < n) : m * n / n = m :=
by rw [nat.mul_comm, mul_div_right _ H]
protected theorem div_self {n : ℕ} (H : 0 < n) : n / n = 1 :=
let t := add_div_right 0 H in by rwa [nat.zero_add, nat.zero_div] at t
theorem add_mul_div_left (x z : ℕ) {y : ℕ} (H : 0 < y) : (x + y * z) / y = x / y + z :=
begin
induction z with z ih,
{ rw [nat.mul_zero, nat.add_zero, nat.add_zero] },
{ rw [mul_succ, ← nat.add_assoc, add_div_right _ H, ih], refl }
end
theorem add_mul_div_right (x y : ℕ) {z : ℕ} (H : 0 < z) : (x + y * z) / z = x / z + y :=
by rw [nat.mul_comm, add_mul_div_left _ _ H]
protected theorem mul_div_cancel (m : ℕ) {n : ℕ} (H : 0 < n) : m * n / n = m :=
let t := add_mul_div_right 0 m H in by rwa [nat.zero_add, nat.zero_div, nat.zero_add] at t
protected theorem mul_div_cancel_left (m : ℕ) {n : ℕ} (H : 0 < n) : n * m / n = m :=
by rw [nat.mul_comm, nat.mul_div_cancel _ H]
protected theorem div_eq_of_eq_mul_left {m n k : ℕ} (H1 : 0 < n) (H2 : m = k * n) :
m / n = k :=
by rw [H2, nat.mul_div_cancel _ H1]
protected theorem div_eq_of_eq_mul_right {m n k : ℕ} (H1 : 0 < n) (H2 : m = n * k) :
m / n = k :=
by rw [H2, nat.mul_div_cancel_left _ H1]
protected theorem div_eq_of_lt_le {m n k : ℕ}
(lo : k * n ≤ m) (hi : m < succ k * n) :
m / n = k :=
have npos : 0 < n, from n.eq_zero_or_pos.resolve_left $ λ hn,
by rw [hn, nat.mul_zero] at hi lo; exact absurd lo (not_le_of_gt hi),
le_antisymm
(le_of_lt_succ $ (nat.div_lt_iff_lt_mul npos).2 hi)
((nat.le_div_iff_mul_le npos).2 lo)
theorem mul_sub_div (x n p : ℕ) (h₁ : x < n*p) : (n * p - succ x) / n = p - succ (x / n) :=
begin
have npos : 0 < n := n.eq_zero_or_pos.resolve_left (λ n0,
by rw [n0, nat.zero_mul] at h₁; exact nat.not_lt_zero _ h₁),
apply nat.div_eq_of_lt_le,
{ rw [nat.mul_sub_right_distrib, nat.mul_comm],
apply nat.sub_le_sub_left,
exact (div_lt_iff_lt_mul npos).1 (lt_succ_self _) },
{ change succ (pred (n * p - x)) ≤ (succ (pred (p - x / n))) * n,
rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h₁),
succ_pred_eq_of_pos (nat.sub_pos_of_lt _)],
{ rw [nat.mul_sub_right_distrib, nat.mul_comm],
apply nat.sub_le_sub_left, apply div_mul_le_self },
{ apply (div_lt_iff_lt_mul npos).2, rwa nat.mul_comm } }
end
protected theorem div_div_eq_div_mul (m n k : ℕ) : m / n / k = m / (n * k) :=
begin
cases k.eq_zero_or_pos with k0 kpos, {rw [k0, nat.mul_zero, nat.div_zero, nat.div_zero]},
cases n.eq_zero_or_pos with n0 npos, {rw [n0, nat.zero_mul, nat.div_zero, nat.zero_div]},
apply le_antisymm,
{ apply (le_div_iff_mul_le $ nat.mul_pos npos kpos).2,
rw [nat.mul_comm n k, ← nat.mul_assoc],
apply (le_div_iff_mul_le npos).1,
apply (le_div_iff_mul_le kpos).1,
refl },
{ apply (le_div_iff_mul_le kpos).2,
apply (le_div_iff_mul_le npos).2,
rw [nat.mul_assoc, nat.mul_comm n k],
apply (le_div_iff_mul_le (nat.mul_pos kpos npos)).1,
refl }
end
protected theorem mul_div_mul {m : ℕ} (n k : ℕ) (H : 0 < m) : m * n / (m * k) = n / k :=
by rw [← nat.div_div_eq_div_mul, nat.mul_div_cancel_left _ H]
lemma div_lt_self {n m : nat} : 0 < n → 1 < m → n / m < n :=
begin
intros h₁ h₂,
have := nat.mul_lt_mul h₂ (le_refl _) h₁,
rw [nat.one_mul, nat.mul_comm] at this,
exact (nat.div_lt_iff_lt_mul $ lt_trans (by comp_val) h₂).2 this,
end
/-! dvd -/
protected theorem dvd_mul_right (a b : ℕ) : a ∣ a * b := ⟨b, rfl⟩
protected theorem dvd_trans {a b c : ℕ} (h₁ : a ∣ b) (h₂ : b ∣ c) : a ∣ c :=
match h₁, h₂ with
| ⟨d, (h₃ : b = a * d)⟩, ⟨e, (h₄ : c = b * e)⟩ :=
⟨d * e, show c = a * (d * e), by simp [h₃, h₄, nat.mul_assoc]⟩
end
protected theorem eq_zero_of_zero_dvd {a : ℕ} (h : 0 ∣ a) : a = 0 :=
exists.elim h (assume c, assume H' : a = 0 * c, eq.trans H' (nat.zero_mul c))
protected theorem dvd_add {a b c : ℕ} (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c :=
exists.elim h₁ (λ d hd, exists.elim h₂ (λ e he, ⟨d + e, by simp [nat.left_distrib, hd, he]⟩))
protected theorem dvd_add_iff_right {k m n : ℕ} (h : k ∣ m) : k ∣ n ↔ k ∣ m + n :=
⟨nat.dvd_add h, exists.elim h $ λd hd, match m, hd with
| ._, rfl := λh₂, exists.elim h₂ $ λe he, ⟨e - d,
by rw [nat.mul_sub_left_distrib, ← he, nat.add_sub_cancel_left]⟩
end⟩
protected theorem dvd_add_iff_left {k m n : ℕ} (h : k ∣ n) : k ∣ m ↔ k ∣ m + n :=
by rw nat.add_comm; exact nat.dvd_add_iff_right h
theorem dvd_sub {k m n : ℕ} (H : n ≤ m) (h₁ : k ∣ m) (h₂ : k ∣ n) : k ∣ m - n :=
(nat.dvd_add_iff_left h₂).2 $ by rw nat.sub_add_cancel H; exact h₁
theorem dvd_mod_iff {k m n : ℕ} (h : k ∣ n) : k ∣ m % n ↔ k ∣ m :=
let t := @nat.dvd_add_iff_left _ (m % n) _ (nat.dvd_trans h (nat.dvd_mul_right n (m / n))) in
by rwa mod_add_div at t
theorem le_of_dvd {m n : ℕ} (h : 0 < n) : m ∣ n → m ≤ n :=
λ⟨k, e⟩, by {
revert h, rw e, refine k.cases_on _ _,
exact λhn, absurd hn (lt_irrefl _),
exact λk _, let t := m.mul_le_mul_left (succ_pos k) in by rwa nat.mul_one at t }
theorem dvd_antisymm : Π {m n : ℕ}, m ∣ n → n ∣ m → m = n
| m 0 h₁ h₂ := nat.eq_zero_of_zero_dvd h₂
| 0 n h₁ h₂ := (nat.eq_zero_of_zero_dvd h₁).symm
| (succ m) (succ n) h₁ h₂ := le_antisymm (le_of_dvd (succ_pos _) h₁) (le_of_dvd (succ_pos _) h₂)
theorem pos_of_dvd_of_pos {m n : ℕ} (H1 : m ∣ n) (H2 : 0 < n) : 0 < m :=
nat.pos_of_ne_zero $ λm0, by rw m0 at H1; rw nat.eq_zero_of_zero_dvd H1 at H2; exact lt_irrefl _ H2
theorem eq_one_of_dvd_one {n : ℕ} (H : n ∣ 1) : n = 1 :=
le_antisymm (le_of_dvd dec_trivial H) (pos_of_dvd_of_pos H dec_trivial)
theorem dvd_of_mod_eq_zero {m n : ℕ} (H : n % m = 0) : m ∣ n :=
⟨n / m, by { have t := (mod_add_div n m).symm, rwa [H, nat.zero_add] at t }⟩
theorem mod_eq_zero_of_dvd {m n : ℕ} (H : m ∣ n) : n % m = 0 :=
exists.elim H (λ z H1, by rw [H1, mul_mod_right])
theorem dvd_iff_mod_eq_zero {m n : ℕ} : m ∣ n ↔ n % m = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩
instance decidable_dvd : @decidable_rel ℕ (∣) :=
λm n, decidable_of_decidable_of_iff (by apply_instance) dvd_iff_mod_eq_zero.symm
protected theorem mul_div_cancel' {m n : ℕ} (H : n ∣ m) : n * (m / n) = m :=
let t := mod_add_div m n in by rwa [mod_eq_zero_of_dvd H, nat.zero_add] at t
protected theorem div_mul_cancel {m n : ℕ} (H : n ∣ m) : m / n * n = m :=
by rw [nat.mul_comm, nat.mul_div_cancel' H]
protected theorem mul_div_assoc (m : ℕ) {n k : ℕ} (H : k ∣ n) : m * n / k = m * (n / k) :=
or.elim k.eq_zero_or_pos
(λh, by rw [h, nat.div_zero, nat.div_zero, nat.mul_zero])
(λh, have m * n / k = m * (n / k * k) / k, by rw nat.div_mul_cancel H,
by rw[this, ← nat.mul_assoc, nat.mul_div_cancel _ h])
theorem dvd_of_mul_dvd_mul_left {m n k : ℕ} (kpos : 0 < k) (H : k * m ∣ k * n) : m ∣ n :=
exists.elim H (λl H1, by rw nat.mul_assoc at H1; exact ⟨_, nat.eq_of_mul_eq_mul_left kpos H1⟩)
theorem dvd_of_mul_dvd_mul_right {m n k : ℕ} (kpos : 0 < k) (H : m * k ∣ n * k) : m ∣ n :=
by rw [nat.mul_comm m k, nat.mul_comm n k] at H; exact dvd_of_mul_dvd_mul_left kpos H
/-! iterate -/
def iterate {α : Sort u} (op : α → α) : ℕ → α → α
| 0 a := a
| (succ k) a := iterate k (op a)
notation f`^[`n`]` := iterate f n
/-! find -/
section find
parameter {p : ℕ → Prop}
private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ¬p k
parameters [decidable_pred p] (H : ∃n, p n)
private def wf_lbp : well_founded lbp :=
⟨let ⟨n, pn⟩ := H in
suffices ∀m k, n ≤ k + m → acc lbp k, from λa, this _ _ (nat.le_add_left _ _),
λm, nat.rec_on m
(λk kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := absurd pn (a _ kn) end⟩)
(λm IH k kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := IH _ (by rw nat.add_right_comm; exact kn) end⟩)⟩
protected def find_x : {n // p n ∧ ∀m < n, ¬p m} :=
@well_founded.fix _ (λk, (∀n < k, ¬p n) → {n // p n ∧ ∀m < n, ¬p m}) lbp wf_lbp
(λm IH al, if pm : p m then ⟨m, pm, al⟩ else
have ∀ n ≤ m, ¬p n, from λn h, or.elim (decidable.lt_or_eq_of_le h) (al n) (λe, by rw e; exact pm),
IH _ ⟨rfl, this⟩ (λn h, this n $ nat.le_of_succ_le_succ h))
0 (λn h, absurd h (nat.not_lt_zero _))
/--
If `p` is a (decidable) predicate on `ℕ` and `hp : ∃ (n : ℕ), p n` is a proof that
there exists some natural number satisfying `p`, then `nat.find hp` is the
smallest natural number satisfying `p`. Note that `nat.find` is protected,
meaning that you can't just write `find`, even if the `nat` namespace is open.
The API for `nat.find` is:
* `nat.find_spec` is the proof that `nat.find hp` satisfies `p`.
* `nat.find_min` is the proof that if `m < nat.find hp` then `m` does not satisfy `p`.
* `nat.find_min'` is the proof that if `m` does satisfy `p` then `nat.find hp ≤ m`.
-/
protected def find : ℕ := nat.find_x.1
protected theorem find_spec : p nat.find := nat.find_x.2.left
protected theorem find_min : ∀ {m : ℕ}, m < nat.find → ¬p m := nat.find_x.2.right
protected theorem find_min' {m : ℕ} (h : p m) : nat.find ≤ m :=
le_of_not_lt (λ l, find_min l h)
end find
end nat
|
1063e5b6df717f78c166abc15b4cfb053add1504
|
8cae430f0a71442d02dbb1cbb14073b31048e4b0
|
/src/algebra/char_p/quotient.lean
|
d6257701ef9c1a215c155fa1e6e2a067a8b6aa91
|
[
"Apache-2.0"
] |
permissive
|
leanprover-community/mathlib
|
56a2cadd17ac88caf4ece0a775932fa26327ba0e
|
442a83d738cb208d3600056c489be16900ba701d
|
refs/heads/master
| 1,693,584,102,358
| 1,693,471,902,000
| 1,693,471,902,000
| 97,922,418
| 1,595
| 352
|
Apache-2.0
| 1,694,693,445,000
| 1,500,624,130,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 1,985
|
lean
|
/-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Eric Wieser
-/
import algebra.char_p.basic
import ring_theory.ideal.quotient
/-!
# Characteristic of quotients rings
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
universes u v
namespace char_p
theorem quotient (R : Type u) [comm_ring R] (p : ℕ) [hp1 : fact p.prime] (hp2 : ↑p ∈ nonunits R) :
char_p (R ⧸ (ideal.span {p} : ideal R)) p :=
have hp0 : (p : R ⧸ (ideal.span {p} : ideal R)) = 0,
from map_nat_cast (ideal.quotient.mk (ideal.span {p} : ideal R)) p ▸
ideal.quotient.eq_zero_iff_mem.2 (ideal.subset_span $ set.mem_singleton _),
ring_char.of_eq $ or.resolve_left ((nat.dvd_prime hp1.1).1 $ ring_char.dvd hp0) $ λ h1,
hp2 $ is_unit_iff_dvd_one.2 $ ideal.mem_span_singleton.1 $ ideal.quotient.eq_zero_iff_mem.1 $
@@subsingleton.elim (@@char_p.subsingleton _ $ ring_char.of_eq h1) _ _
/-- If an ideal does not contain any coercions of natural numbers other than zero, then its quotient
inherits the characteristic of the underlying ring. -/
lemma quotient' {R : Type*} [comm_ring R] (p : ℕ) [char_p R p] (I : ideal R)
(h : ∀ x : ℕ, (x : R) ∈ I → (x : R) = 0) :
char_p (R ⧸ I) p :=
⟨λ x, begin
rw [←cast_eq_zero_iff R p x, ←map_nat_cast (ideal.quotient.mk I)],
refine ideal.quotient.eq.trans (_ : ↑x - 0 ∈ I ↔ _),
rw sub_zero,
exact ⟨h x, λ h', h'.symm ▸ I.zero_mem⟩,
end⟩
end char_p
lemma ideal.quotient.index_eq_zero {R : Type*} [comm_ring R] (I : ideal R) :
(I.to_add_subgroup.index : R ⧸ I) = 0 :=
begin
rw [add_subgroup.index, nat.card_eq],
split_ifs with hq, swap, simp,
by_contra h,
-- TODO: can we avoid rewriting the `I.to_add_subgroup` here?
letI : fintype (R ⧸ I) := @fintype.of_finite _ hq,
have h : (fintype.card (R ⧸ I) : R ⧸ I) ≠ 0 := h,
simpa using h
end
|
c49587b0e4742399525e8b90992db05e8529689c
|
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
|
/src/ring_theory/adjoin/basic.lean
|
fb83bd8cfc7f3c7cc687c0180d851cca1fd5a6be
|
[
"Apache-2.0"
] |
permissive
|
dexmagic/mathlib
|
ff48eefc56e2412429b31d4fddd41a976eb287ce
|
7a5d15a955a92a90e1d398b2281916b9c41270b2
|
refs/heads/master
| 1,693,481,322,046
| 1,633,360,193,000
| 1,633,360,193,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 9,436
|
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.algebra.subalgebra
import linear_algebra.prod
/-!
# Adjoining elements to form subalgebras
This file develops the basic theory of subalgebras of an R-algebra generated
by a set of elements. A basic interface for `adjoin` is set up, and various
results about finitely-generated subalgebras and submodules are proved.
## Definitions
* `fg (S : subalgebra R A)` : A predicate saying that the subalgebra is finitely-generated
as an A-algebra
## Tags
adjoin, algebra, finitely-generated algebra
-/
universes u v w
open submodule
open_locale pointwise
namespace algebra
variables {R : Type u} {A : Type v} {B : Type w}
section semiring
variables [comm_semiring R] [semiring A] [semiring B]
variables [algebra R A] [algebra R B] {s t : set A}
open subsemiring
theorem subset_adjoin : s ⊆ adjoin R s :=
algebra.gc.le_u_l s
theorem adjoin_le {S : subalgebra R A} (H : s ⊆ S) : adjoin R s ≤ S :=
algebra.gc.l_le H
theorem adjoin_le_iff {S : subalgebra R A} : adjoin R s ≤ S ↔ s ⊆ S:=
algebra.gc _ _
theorem adjoin_mono (H : s ⊆ t) : adjoin R s ≤ adjoin R t :=
algebra.gc.monotone_l H
theorem adjoin_eq_of_le (S : subalgebra R A) (h₁ : s ⊆ S) (h₂ : S ≤ adjoin R s) : adjoin R s = S :=
le_antisymm (adjoin_le h₁) h₂
theorem adjoin_eq (S : subalgebra R A) : adjoin R ↑S = S :=
adjoin_eq_of_le _ (set.subset.refl _) subset_adjoin
@[elab_as_eliminator] theorem adjoin_induction {p : A → Prop} {x : A} (h : x ∈ adjoin R s)
(Hs : ∀ x ∈ s, p x)
(Halg : ∀ r, p (algebra_map R A r))
(Hadd : ∀ x y, p x → p y → p (x + y))
(Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
let S : subalgebra R A :=
{ carrier := p, mul_mem' := Hmul, add_mem' := Hadd, algebra_map_mem' := Halg } in
adjoin_le (show s ≤ S, from Hs) h
lemma adjoin_union (s t : set A) : adjoin R (s ∪ t) = adjoin R s ⊔ adjoin R t :=
(algebra.gc : galois_connection _ (coe : subalgebra R A → set A)).l_sup
variables (R A)
@[simp] theorem adjoin_empty : adjoin R (∅ : set A) = ⊥ :=
show adjoin R ⊥ = ⊥, by { apply galois_connection.l_bot, exact algebra.gc }
@[simp] theorem adjoin_univ : adjoin R (set.univ : set A) = ⊤ :=
eq_top_iff.2 $ λ x, subset_adjoin $ set.mem_univ _
variables (R) {A} (s)
theorem adjoin_eq_span : (adjoin R s).to_submodule = span R (submonoid.closure s) :=
begin
apply le_antisymm,
{ intros r hr, rcases subsemiring.mem_closure_iff_exists_list.1 hr with ⟨L, HL, rfl⟩, clear hr,
induction L with hd tl ih, { exact zero_mem _ },
rw list.forall_mem_cons at HL,
rw [list.map_cons, list.sum_cons],
refine submodule.add_mem _ _ (ih HL.2),
replace HL := HL.1, clear ih tl,
suffices : ∃ z r (hr : r ∈ submonoid.closure s), has_scalar.smul z r = list.prod hd,
{ rcases this with ⟨z, r, hr, hzr⟩, rw ← hzr,
exact smul_mem _ _ (subset_span hr) },
induction hd with hd tl ih, { exact ⟨1, 1, (submonoid.closure s).one_mem', one_smul _ _⟩ },
rw list.forall_mem_cons at HL,
rcases (ih HL.2) with ⟨z, r, hr, hzr⟩, rw [list.prod_cons, ← hzr],
rcases HL.1 with ⟨hd, rfl⟩ | hs,
{ refine ⟨hd * z, r, hr, _⟩,
rw [algebra.smul_def, algebra.smul_def, (algebra_map _ _).map_mul, _root_.mul_assoc] },
{ exact ⟨z, hd * r, submonoid.mul_mem _ (submonoid.subset_closure hs) hr,
(mul_smul_comm _ _ _).symm⟩ } },
refine span_le.2 _,
change submonoid.closure s ≤ (adjoin R s).to_subsemiring.to_submonoid,
exact submonoid.closure_le.2 subset_adjoin
end
lemma span_le_adjoin (s : set A) : span R s ≤ (adjoin R s).to_submodule :=
span_le.mpr subset_adjoin
lemma adjoin_to_submodule_le {s : set A} {t : submodule R A} :
(adjoin R s).to_submodule ≤ t ↔ ↑(submonoid.closure s) ⊆ (t : set A) :=
by rw [adjoin_eq_span, span_le]
lemma adjoin_eq_span_of_subset {s : set A} (hs : ↑(submonoid.closure s) ⊆ (span R s : set A)) :
(adjoin R s).to_submodule = span R s :=
le_antisymm ((adjoin_to_submodule_le R).mpr hs) (span_le_adjoin R s)
lemma adjoin_image (f : A →ₐ[R] B) (s : set A) :
adjoin R (f '' s) = (adjoin R s).map f :=
le_antisymm (adjoin_le $ set.image_subset _ subset_adjoin) $
subalgebra.map_le.2 $ adjoin_le $ set.image_subset_iff.1 subset_adjoin
@[simp] lemma adjoin_insert_adjoin (x : A) :
adjoin R (insert x ↑(adjoin R s)) = adjoin R (insert x s) :=
le_antisymm
(adjoin_le (set.insert_subset.mpr
⟨subset_adjoin (set.mem_insert _ _), adjoin_mono (set.subset_insert _ _)⟩))
(algebra.adjoin_mono (set.insert_subset_insert algebra.subset_adjoin))
lemma adjoint_prod_le (s : set A) (t : set B) :
adjoin R (set.prod s t) ≤ (adjoin R s).prod (adjoin R t) :=
adjoin_le $ set.prod_mono subset_adjoin subset_adjoin
lemma adjoin_inl_union_inr_le_prod (s) (t) :
adjoin R (linear_map.inl R A B '' (s ∪ {1}) ∪
linear_map.inr R A B '' (t ∪ {1})) ≤ (adjoin R s).prod (adjoin R t) :=
begin
rw [set.image_union, set.image_union],
refine adjoin_le (λ x hx, subalgebra.mem_prod.2 _),
rcases hx with (⟨x₁, ⟨hx₁, rfl⟩⟩ | ⟨x₂, ⟨hx₂, rfl⟩⟩) | (⟨x₃, ⟨hx₃, rfl⟩⟩ | ⟨x₄, ⟨hx₄, rfl⟩⟩),
{ exact ⟨subset_adjoin hx₁, subalgebra.zero_mem _⟩ },
{ rw set.mem_singleton_iff.1 hx₂,
exact ⟨subalgebra.one_mem _, subalgebra.zero_mem _⟩ },
{ exact ⟨subalgebra.zero_mem _, subset_adjoin hx₃⟩ },
{ rw set.mem_singleton_iff.1 hx₄,
exact ⟨subalgebra.zero_mem _, subalgebra.one_mem _⟩ }
end
lemma mem_adjoin_of_map_mul {s} {x : A} {f : A →ₗ[R] B} (hf : ∀ a₁ a₂, f(a₁ * a₂) = f a₁ * f a₂)
(h : x ∈ adjoin R s) : f x ∈ adjoin R (f '' (s ∪ {1})) :=
begin
refine @adjoin_induction R A _ _ _ _ (λ a, f a ∈ adjoin R (f '' (s ∪ {1}))) x h
(λ a ha, subset_adjoin ⟨a, ⟨set.subset_union_left _ _ ha, rfl⟩⟩)
(λ r, _)
(λ y z hy hz, by simpa [hy, hz] using subalgebra.add_mem _ hy hz)
(λ y z hy hz, by simpa [hy, hz, hf y z] using subalgebra.mul_mem _ hy hz),
have : f 1 ∈ adjoin R (f '' (s ∪ {1})) :=
subset_adjoin ⟨1, ⟨set.subset_union_right _ _ $ set.mem_singleton 1, rfl⟩⟩,
replace this := subalgebra.smul_mem (adjoin R (f '' (s ∪ {1}))) this r,
convert this,
rw algebra_map_eq_smul_one,
exact f.map_smul _ _
end
lemma adjoin_inl_union_inr_eq_prod (s) (t) :
adjoin R (linear_map.inl R A B '' (s ∪ {1}) ∪
linear_map.inr R A B '' (t ∪ {1})) = (adjoin R s).prod (adjoin R t) :=
begin
let P := adjoin R (linear_map.inl R A B '' (s ∪ {1}) ∪ linear_map.inr R A B '' (t ∪ {1})),
refine le_antisymm (adjoin_inl_union_inr_le_prod R s t) _,
rintro ⟨a, b⟩ ⟨ha, hb⟩,
have Ha : (a, (0 : B)) ∈ adjoin R ((linear_map.inl R A B) '' (s ∪ {1})) :=
mem_adjoin_of_map_mul R (linear_map.inl_map_mul) ha,
have Hb : ((0 : A), b) ∈ adjoin R ((linear_map.inr R A B) '' (t ∪ {1})) :=
mem_adjoin_of_map_mul R (linear_map.inr_map_mul) hb,
replace Ha : (a, (0 : B)) ∈ P :=
adjoin_mono (set.subset_union_of_subset_left (set.subset.refl _) _) Ha,
replace Hb : ((0 : A), b) ∈ P :=
adjoin_mono (set.subset_union_of_subset_right (set.subset.refl _) _) Hb,
simpa using subalgebra.add_mem _ Ha Hb
end
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A]
variables [algebra R A] {s t : set A}
open subsemiring
variables (R s t)
theorem adjoin_union_eq_under : adjoin R (s ∪ t) = (adjoin R s).under (adjoin (adjoin R s) t) :=
le_antisymm
(closure_mono $ set.union_subset
(set.range_subset_iff.2 $ λ r, or.inl ⟨algebra_map R (adjoin R s) r, rfl⟩)
(set.union_subset_union_left _ $ λ x hxs, ⟨⟨_, subset_adjoin hxs⟩, rfl⟩))
(closure_le.2 $ set.union_subset
(set.range_subset_iff.2 $ λ x, adjoin_mono (set.subset_union_left _ _) x.2)
(set.subset.trans (set.subset_union_right _ _) subset_adjoin))
lemma adjoin_singleton_one : adjoin R ({1} : set A) = ⊥ :=
eq_bot_iff.2 $ adjoin_le $ set.singleton_subset_iff.2 $ set_like.mem_coe.2 $ one_mem _
theorem adjoin_union_coe_submodule : (adjoin R (s ∪ t)).to_submodule =
(adjoin R s).to_submodule * (adjoin R t).to_submodule :=
begin
rw [adjoin_eq_span, adjoin_eq_span, adjoin_eq_span, span_mul_span],
congr' 1 with z, simp [submonoid.closure_union, submonoid.mem_sup, set.mem_mul]
end
end comm_semiring
section ring
variables [comm_ring R] [ring A]
variables [algebra R A] {s t : set A}
variables {R s t}
theorem adjoin_int (s : set R) : adjoin ℤ s = subalgebra_of_subring (subring.closure s) :=
le_antisymm (adjoin_le subring.subset_closure)
(subring.closure_le.2 subset_adjoin : subring.closure s ≤ (adjoin ℤ s).to_subring)
theorem mem_adjoin_iff {s : set A} {x : A} :
x ∈ adjoin R s ↔ x ∈ subring.closure (set.range (algebra_map R A) ∪ s) :=
⟨λ hx, subsemiring.closure_induction hx subring.subset_closure (subring.zero_mem _)
(subring.one_mem _) (λ _ _, subring.add_mem _) ( λ _ _, subring.mul_mem _),
suffices subring.closure (set.range ⇑(algebra_map R A) ∪ s) ≤ (adjoin R s).to_subring,
from @this x, subring.closure_le.2 subsemiring.subset_closure⟩
theorem adjoin_eq_ring_closure (s : set A) :
(adjoin R s).to_subring = subring.closure (set.range (algebra_map R A) ∪ s) :=
subring.ext $ λ x, mem_adjoin_iff
end ring
end algebra
|
de4120c626a65c49318c3640d9383f536d43c5cf
|
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
|
/linear_algebra/multivariate_polynomial.lean
|
67371cb3350e9c8c9872eab0b197bd75dd9f4a64
|
[
"Apache-2.0"
] |
permissive
|
amswerdlow/mathlib
|
9af77a1f08486d8fa059448ae2d97795bd12ec0c
|
27f96e30b9c9bf518341705c99d641c38638dfd0
|
refs/heads/master
| 1,585,200,953,598
| 1,534,275,532,000
| 1,534,275,532,000
| 144,564,700
| 0
| 0
| null | 1,534,156,197,000
| 1,534,156,197,000
| null |
UTF-8
|
Lean
| false
| false
| 12,410
|
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, Johan Commelin, Mario Carneiro
Multivariate Polynomial
-/
import data.finsupp linear_algebra.basic algebra.ring
open set function finsupp lattice
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
/-- Multivariate polynomial, where `σ` is the index set of the variables and
`α` is the coefficient ring -/
def mv_polynomial (σ : Type*) (α : Type*) [comm_semiring α] := (σ →₀ ℕ) →₀ α
namespace mv_polynomial
variables {σ : Type*} {a a' a₁ a₂ : α} {e : ℕ} {n m : σ} {s : σ →₀ ℕ}
variables [decidable_eq σ] [decidable_eq α]
section comm_semiring
variables [comm_semiring α] {p q : mv_polynomial σ α}
instance : decidable_eq (mv_polynomial σ α) := finsupp.decidable_eq
instance : has_zero (mv_polynomial σ α) := finsupp.has_zero
instance : has_one (mv_polynomial σ α) := finsupp.has_one
instance : has_add (mv_polynomial σ α) := finsupp.has_add
instance : has_mul (mv_polynomial σ α) := finsupp.has_mul
instance : comm_semiring (mv_polynomial σ α) := finsupp.to_comm_semiring
/-- `monomial s a` is the monomial `a * X^s` -/
def monomial (s : σ →₀ ℕ) (a : α) : mv_polynomial σ α := single s a
/-- `C a` is the constant polynomial with value `a` -/
def C (a : α) : mv_polynomial σ α := monomial 0 a
/-- `X n` is the polynomial with value X_n -/
def X (n : σ) : mv_polynomial σ α := monomial (single n 1) 1
@[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ α) := by simp [C, monomial]; refl
@[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ α) := rfl
lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') :=
by simp [C, monomial, single_mul_single]
@[simp] lemma C_add : (C (a + a') : mv_polynomial σ α) = C a + C a' := single_add
@[simp] lemma C_mul : (C (a * a') : mv_polynomial σ α) = C a * C a' := C_mul_monomial.symm
instance : is_semiring_hom (C : α → mv_polynomial σ α) :=
{ map_zero := C_0,
map_one := C_1,
map_add := λ a a', C_add,
map_mul := λ a a', C_mul }
lemma X_pow_eq_single : X n ^ e = monomial (single n e) (1 : α) :=
begin
induction e,
{ simp [X], refl },
{ simp [pow_succ, e_ih],
simp [X, monomial, single_mul_single, nat.succ_eq_add_one] }
end
lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e):=
by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp
lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a):=
by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp
lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ α) :=
begin
apply @finsupp.induction σ ℕ _ _ _ _ s,
{ simp [C, prod_zero_index]; exact (mul_one _).symm },
{ assume n e s hns he ih,
simp [prod_add_index, prod_single_index, pow_zero, pow_add, (mul_assoc _ _ _).symm, ih.symm,
monomial_add_single] }
end
@[recursor 7]
lemma induction_on {M : mv_polynomial σ α → Prop} (p : mv_polynomial σ α)
(h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀p n, M p → M (p * X n)) :
M p :=
have ∀s a, M (monomial s a),
begin
assume s a,
apply @finsupp.induction σ ℕ _ _ _ _ s,
{ show M (monomial 0 a), from h_C a, },
{ assume n e p hpn he ih,
have : ∀e:ℕ, M (monomial p a * X n ^ e),
{ intro e,
induction e,
{ simp [ih] },
{ simp [ih, pow_succ', (mul_assoc _ _ _).symm, h_X, e_ih] } },
simp [monomial_add_single, this] }
end,
finsupp.induction p
(by have : M (C 0) := h_C 0; rwa [C_0] at this)
(assume s a p hsp ha hp, h_add _ _ (this s a) hp)
section eval₂
variables [comm_semiring β]
variables (f : α → β) [is_semiring_hom f] (g : σ → β)
/-- Evaluate a polynomial `p` given a valuation `g` of all the variables
and a ring hom `f` from the scalar ring to the target -/
def eval₂ (p : mv_polynomial σ α) : β :=
p.sum (λs a, f a * s.prod (λn e, g n ^ e))
@[simp] lemma eval₂_zero : (0 : mv_polynomial σ α).eval₂ f g = 0 :=
finsupp.sum_zero_index
@[simp] lemma eval₂_add : (p + q).eval₂ f g = p.eval₂ f g + q.eval₂ f g :=
finsupp.sum_add_index
(by simp [is_semiring_hom.map_zero f])
(by simp [add_mul, is_semiring_hom.map_add f])
@[simp] lemma eval₂_monomial : (monomial s a).eval₂ f g = f a * s.prod (λn e, g n ^ e) :=
finsupp.sum_single_index (by simp [is_semiring_hom.map_zero f])
@[simp] lemma eval₂_C (a) : (C a).eval₂ f g = f a :=
by simp [eval₂_monomial, C, prod_zero_index]
@[simp] lemma eval₂_one : (1 : mv_polynomial σ α).eval₂ f g = 1 :=
(eval₂_C _ _ _).trans (is_semiring_hom.map_one f)
@[simp] lemma eval₂_X (n) : (X n).eval₂ f g = g n :=
by simp [eval₂_monomial,
is_semiring_hom.map_one f, X, prod_single_index, pow_one]
lemma eval₂_mul_monomial :
∀{s a}, (p * monomial s a).eval₂ f g = p.eval₂ f g * f a * s.prod (λn e, g n ^ e) :=
begin
apply mv_polynomial.induction_on p,
{ assume a' s a,
simp [C_mul_monomial, eval₂_monomial, is_semiring_hom.map_mul f] },
{ assume p q ih_p ih_q, simp [add_mul, eval₂_add, ih_p, ih_q] },
{ assume p n ih s a,
from calc (p * X n * monomial s a).eval₂ f g = (p * monomial (single n 1 + s) a).eval₂ f g :
by simp [monomial_single_add, -add_comm, pow_one, mul_assoc]
... = (p * monomial (single n 1) 1).eval₂ f g * f a * s.prod (λn e, g n ^ e) :
by simp [ih, prod_single_index, prod_add_index, pow_one, pow_add, mul_assoc, mul_left_comm,
is_semiring_hom.map_one f, -add_comm] }
end
lemma eval₂_mul : ∀{p}, (p * q).eval₂ f g = p.eval₂ f g * q.eval₂ f g :=
begin
apply mv_polynomial.induction_on q,
{ simp [C, eval₂_monomial, eval₂_mul_monomial, prod_zero_index] },
{ simp [mul_add, eval₂_add] {contextual := tt} },
{ simp [X, eval₂_monomial, eval₂_mul_monomial, (mul_assoc _ _ _).symm] { contextual := tt} }
end
instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f g) :=
{ map_zero := eval₂_zero _ _,
map_one := eval₂_one _ _,
map_add := λ p q, eval₂_add _ _,
map_mul := λ p q, eval₂_mul _ _ }
lemma eval₂_comp_left {γ} [comm_semiring γ]
(k : β → γ) [is_semiring_hom k]
(f : α → β) [is_semiring_hom f] (g : σ → β)
(p) : k (eval₂ f g p) = eval₂ (k ∘ f) (k ∘ g) p :=
by apply mv_polynomial.induction_on p; simp [
eval₂_add, is_semiring_hom.map_add k,
eval₂_mul, is_semiring_hom.map_mul k] {contextual := tt}
lemma eval₂_eta (p : mv_polynomial σ α) : eval₂ C X p = p :=
by apply mv_polynomial.induction_on p;
simp [eval₂_add, eval₂_mul] {contextual := tt}
end eval₂
section eval
variables {f : σ → α}
/-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/
def eval (f : σ → α) : mv_polynomial σ α → α := eval₂ id f
@[simp] lemma eval_zero : (0 : mv_polynomial σ α).eval f = 0 := eval₂_zero _ _
@[simp] lemma eval_add : (p + q).eval f = p.eval f + q.eval f := eval₂_add _ _
lemma eval_monomial : (monomial s a).eval f = a * s.prod (λn e, f n ^ e) :=
eval₂_monomial _ _
@[simp] lemma eval_C : ∀ a, (C a).eval f = a := eval₂_C _ _
@[simp] lemma eval_X : ∀ n, (X n).eval f = f n := eval₂_X _ _
@[simp] lemma eval_mul : (p * q).eval f = p.eval f * q.eval f := eval₂_mul _ _
instance eval.is_semiring_hom : is_semiring_hom (eval f) :=
eval₂.is_semiring_hom _ _
theorem eval_assoc {τ} [decidable_eq τ]
(f : σ → mv_polynomial τ α) (g : τ → α)
(p : mv_polynomial σ α) :
p.eval (eval g ∘ f) = (eval₂ C f p).eval g :=
begin
rw eval₂_comp_left (eval g),
unfold eval, congr; funext a; simp
end
end eval
section map
variables [comm_semiring β] [decidable_eq β]
variables (f : α → β) [is_semiring_hom f]
-- `mv_polynomial σ` is a functor (incomplete)
def map : mv_polynomial σ α → mv_polynomial σ β := eval₂ (C ∘ f) X
@[simp] theorem map_monomial (s : σ →₀ ℕ) (a : α) : map f (monomial s a) = monomial s (f a) :=
(eval₂_monomial _ _).trans monomial_eq.symm
@[simp] theorem map_C : ∀ (a : α), map f (C a : mv_polynomial σ α) = C (f a) := map_monomial _ _
@[simp] theorem map_X : ∀ (n : σ), map f (X n : mv_polynomial σ α) = X n := eval₂_X _ _
@[simp] theorem map_one : map f (1 : mv_polynomial σ α) = 1 := eval₂_one _ _
@[simp] theorem map_add (p q : mv_polynomial σ α) :
map f (p + q) = map f p + map f q := eval₂_add _ _
@[simp] theorem map_mul (p q : mv_polynomial σ α) :
map f (p * q) = map f p * map f q := eval₂_mul _ _
instance map.is_semiring_hom :
is_semiring_hom (map f : mv_polynomial σ α → mv_polynomial σ β) :=
eval₂.is_semiring_hom _ _
theorem map_id : ∀ (p : mv_polynomial σ α), map id p = p := eval₂_eta
theorem map_map [comm_semiring γ] [decidable_eq γ]
(g : β → γ) [is_semiring_hom g]
(p : mv_polynomial σ α) :
map g (map f p) = map (g ∘ f) p :=
(eval₂_comp_left (map g) (C ∘ f) X p).trans $
by congr; funext a; simp
theorem eval₂_eq_eval_map (g : σ → β) (p : mv_polynomial σ α) :
p.eval₂ f g = (map f p).eval g :=
begin
unfold map eval,
rw eval₂_comp_left (eval₂ id g),
congr; funext a; simp
end
end map
section vars
/-- `vars p` is the set of variables appearing in the polynomial `p` -/
def vars (p : mv_polynomial σ α) : finset σ := p.support.bind finsupp.support
@[simp] lemma vars_0 : (0 : mv_polynomial σ α).vars = ∅ :=
show (0 : (σ →₀ ℕ) →₀ α).support.bind finsupp.support = ∅, by simp
@[simp] lemma vars_monomial (h : a ≠ 0) : (monomial s a).vars = s.support :=
show (single s a : (σ →₀ ℕ) →₀ α).support.bind finsupp.support = s.support,
by simp [support_single_ne_zero, h]
@[simp] lemma vars_C : (C a : mv_polynomial σ α).vars = ∅ :=
decidable.by_cases
(assume h : a = 0, by simp [h])
(assume h : a ≠ 0, by simp [C, h])
@[simp] lemma vars_X (h : 0 ≠ (1 : α)) : (X n : mv_polynomial σ α).vars = {n} :=
calc (X n : mv_polynomial σ α).vars = (single n 1).support : vars_monomial h.symm
... = {n} : by rw [support_single_ne_zero nat.zero_ne_one.symm]
end vars
section degree_of
/-- `degree_of n p` gives the highest power of X_n that appears in `p` -/
def degree_of (n : σ) (p : mv_polynomial σ α) : ℕ := p.support.sup (λs, s n)
end degree_of
section total_degree
/-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/
def total_degree (p : mv_polynomial σ α) : ℕ := p.support.sup (λs, s.sum $ λn e, e)
end total_degree
end comm_semiring
section comm_ring
variable [comm_ring α]
variables {p q : mv_polynomial σ α}
instance : ring (mv_polynomial σ α) := finsupp.to_ring
instance : comm_ring (mv_polynomial σ α) := finsupp.to_comm_ring
instance : has_scalar α (mv_polynomial σ α) := finsupp.to_has_scalar
instance : module α (mv_polynomial σ α) := finsupp.to_module
instance C.is_ring_hom : is_ring_hom (C : α → mv_polynomial σ α) :=
by apply is_ring_hom.of_semiring
lemma C_sub : (C (a - a') : mv_polynomial σ α) = C a - C a' := is_ring_hom.map_sub _
@[simp] lemma C_neg : (C (-a) : mv_polynomial σ α) = -C a := is_ring_hom.map_neg _
section eval₂
variables [decidable_eq β] [comm_ring β]
variables (f : α → β) [is_ring_hom f] (g : σ → β)
instance eval₂.is_ring_hom : is_ring_hom (eval₂ f g) :=
by apply is_ring_hom.of_semiring
lemma eval₂_sub : (p - q).eval₂ f g = p.eval₂ f g - q.eval₂ f g := is_ring_hom.map_sub _
@[simp] lemma eval₂_neg : (-p).eval₂ f g = -(p.eval₂ f g) := is_ring_hom.map_neg _
end eval₂
section eval
variables (f : σ → α)
instance eval.is_ring_hom : is_ring_hom (eval f) := eval₂.is_ring_hom _ _
lemma eval_sub : (p - q).eval f = p.eval f - q.eval f := is_ring_hom.map_sub _
@[simp] lemma eval_neg : (-p).eval f = -(p.eval f) := is_ring_hom.map_neg _
end eval
section map
variables [decidable_eq β] [comm_ring β]
variables (f : α → β) [is_ring_hom f]
instance map.is_ring_hom : is_ring_hom (map f : mv_polynomial σ α → mv_polynomial σ β) :=
eval₂.is_ring_hom _ _
lemma map_sub : (p - q).map f = p.map f - q.map f := is_ring_hom.map_sub _
@[simp] lemma map_neg : (-p).map f = -(p.map f) := is_ring_hom.map_neg _
end map
end comm_ring
end mv_polynomial
|
042f0c4243c5e54ab0518907059ce721b7e4533a
|
d406927ab5617694ec9ea7001f101b7c9e3d9702
|
/src/topology/sheaves/locally_surjective.lean
|
a1c6a63df1dd853d4ff6206d1feb82d1fac62e2d
|
[
"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,189
|
lean
|
/-
Copyright (c) 2022 Sam van Gool and Jake Levinson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sam van Gool, Jake Levinson
-/
import topology.sheaves.presheaf
import topology.sheaves.stalks
import category_theory.sites.surjective
/-!
# Locally surjective maps of presheaves.
Let `X` be a topological space, `ℱ` and `𝒢` presheaves on `X`, `T : ℱ ⟶ 𝒢` a map.
In this file we formulate two notions for what it means for
`T` to be locally surjective:
1. For each open set `U`, each section `t : 𝒢(U)` is in the image of `T`
after passing to some open cover of `U`.
2. For each `x : X`, the map of *stalks* `Tₓ : ℱₓ ⟶ 𝒢ₓ` is surjective.
We prove that these are equivalent.
-/
universes v u
noncomputable theory
open category_theory
open topological_space
open opposite
namespace Top.presheaf
section locally_surjective
local attribute [instance] concrete_category.has_coe_to_fun
local attribute [instance] concrete_category.has_coe_to_sort
open_locale algebraic_geometry
/-- Let `C` be a concrete category, `X` a topological space. -/
variables {C : Type u} [category.{v} C] [concrete_category.{v} C] {X : Top.{v}}
/-- Let `ℱ, 𝒢 : (opens X)ᵒᵖ ⥤ C` be `C`-valued presheaves on `X`. -/
variables {ℱ 𝒢 : X.presheaf C}
/--
A map of presheaves `T : ℱ ⟶ 𝒢` is **locally surjective** if for any open set `U`,
section `t` over `U`, and `x ∈ U`, there exists an open set `x ∈ V ⊆ U` and a section `s` over `V`
such that `$T_*(s_V) = t|_V$`.
See `is_locally_surjective_iff` below.
-/
def is_locally_surjective (T : ℱ ⟶ 𝒢) :=
category_theory.is_locally_surjective (opens.grothendieck_topology X) T
lemma is_locally_surjective_iff (T : ℱ ⟶ 𝒢) :
is_locally_surjective T ↔
∀ U t (x ∈ U), ∃ V (ι : V ⟶ U), (∃ s, T.app _ s = t |_ₕ ι) ∧ x ∈ V :=
iff.rfl
section surjective_on_stalks
variables [limits.has_colimits C] [limits.preserves_filtered_colimits (forget C)]
/-- An equivalent condition for a map of presheaves to be locally surjective
is for all the induced maps on stalks to be surjective. -/
lemma locally_surjective_iff_surjective_on_stalks (T : ℱ ⟶ 𝒢) :
is_locally_surjective T ↔
∀ (x : X), function.surjective ((stalk_functor C x).map T) :=
begin
split; intro hT,
{ /- human proof:
Let g ∈ Γₛₜ 𝒢 x be a germ. Represent it on an open set U ⊆ X
as ⟨t, U⟩. By local surjectivity, pass to a smaller open set V
on which there exists s ∈ Γ_ ℱ V mapping to t |_ V.
Then the germ of s maps to g -/
-- Let g ∈ Γₛₜ 𝒢 x be a germ.
intros x g,
-- Represent it on an open set U ⊆ X as ⟨t, U⟩.
obtain ⟨U, hxU, t, rfl⟩ := 𝒢.germ_exist x g,
-- By local surjectivity, pass to a smaller open set V
-- on which there exists s ∈ Γ_ ℱ V mapping to t |_ V.
rcases hT U t x hxU with ⟨V, ι, ⟨s, h_eq⟩, hxV⟩,
-- Then the germ of s maps to g.
use ℱ.germ ⟨x, hxV⟩ s,
convert stalk_functor_map_germ_apply V ⟨x, hxV⟩ T s,
simpa [h_eq] using germ_res_apply 𝒢 ι ⟨x,hxV⟩ t, },
{ /- human proof:
Let U be an open set, t ∈ Γ ℱ U a section, x ∈ U a point.
By surjectivity on stalks, the germ of t is the image of
some germ f ∈ Γₛₜ ℱ x. Represent f on some open set V ⊆ X as ⟨s, V⟩.
Then there is some possibly smaller open set x ∈ W ⊆ V ∩ U on which
we have T(s) |_ W = t |_ W. -/
intros U t x hxU,
set t_x := 𝒢.germ ⟨x, hxU⟩ t with ht_x,
obtain ⟨s_x, hs_x : ((stalk_functor C x).map T) s_x = t_x⟩ := hT x t_x,
obtain ⟨V, hxV, s, rfl⟩ := ℱ.germ_exist x s_x,
-- rfl : ℱ.germ x s = s_x
have key_W := 𝒢.germ_eq x hxV hxU (T.app _ s) t
(by { convert hs_x,
symmetry,
convert stalk_functor_map_germ_apply _ _ _ s, }),
obtain ⟨W, hxW, hWV, hWU, h_eq⟩ := key_W,
refine ⟨W, hWU, ⟨ℱ.map hWV.op s, _⟩, hxW⟩,
convert h_eq,
simp only [← comp_apply, T.naturality], },
end
end surjective_on_stalks
end locally_surjective
end Top.presheaf
|
49545241126d063722b0185145a62c9221b2f372
|
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
|
/stage0/src/Lean/Elab/Mixfix.lean
|
e74ef2a9be58fa64c2b6fe2272a58f2c4ccfcd2d
|
[
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"
] |
permissive
|
EdAyers/lean4
|
57ac632d6b0789cb91fab2170e8c9e40441221bd
|
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
|
refs/heads/master
| 1,676,463,245,298
| 1,660,619,433,000
| 1,660,619,433,000
| 183,433,437
| 1
| 0
|
Apache-2.0
| 1,657,612,672,000
| 1,556,196,574,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 2,121
|
lean
|
/-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Attributes
namespace Lean.Elab.Command
@[builtinMacro Lean.Parser.Command.mixfix] def expandMixfix : Macro := fun stx =>
withAttrKindGlobal stx fun stx => do
match stx with
| `($[$doc?:docComment]? $[@[$attrs?,*]]? infixl:$prec $[(name := $name)]? $[(priority := $prio)]? $op => $f) =>
let prec1 := quote <| (← evalPrec prec) + 1
`($[$doc?:docComment]? $[@[$attrs?,*]]? notation:$prec $[(name := $name)]? $[(priority := $prio)]? lhs:$prec $op:str rhs:$prec1 => $f lhs rhs)
| `($[$doc?:docComment]? $[@[$attrs?,*]]? infix:$prec $[(name := $name)]? $[(priority := $prio)]? $op => $f) =>
let prec1 := quote <| (← evalPrec prec) + 1
`($[$doc?:docComment]? $[@[$attrs?,*]]? notation:$prec $[(name := $name)]? $[(priority := $prio)]? lhs:$prec1 $op:str rhs:$prec1 => $f lhs rhs)
| `($[$doc?:docComment]? $[@[$attrs?,*]]? infixr:$prec $[(name := $name)]? $[(priority := $prio)]? $op => $f) =>
let prec1 := quote <| (← evalPrec prec) + 1
`($[$doc?:docComment]? $[@[$attrs?,*]]? notation:$prec $[(name := $name)]? $[(priority := $prio)]? lhs:$prec1 $op:str rhs:$prec => $f lhs rhs)
| `($[$doc?:docComment]? $[@[$attrs?,*]]? prefix:$prec $[(name := $name)]? $[(priority := $prio)]? $op => $f) =>
`($[$doc?:docComment]? $[@[$attrs?,*]]? notation:$prec $[(name := $name)]? $[(priority := $prio)]? $op:str arg:$prec => $f arg)
| `($[$doc?:docComment]? $[@[$attrs?,*]]? postfix:$prec $[(name := $name)]? $[(priority := $prio)]? $op => $f) =>
`($[$doc?:docComment]? $[@[$attrs?,*]]? notation:$prec $[(name := $name)]? $[(priority := $prio)]? arg:$prec $op:str => $f arg)
| _ => Macro.throwUnsupported
where
-- set "global" `attrKind`, apply `f`, and restore `attrKind` to result
withAttrKindGlobal stx f := do
let attrKind := stx[2]
let stx := stx.setArg 2 mkAttrKindGlobal
let stx ← f stx
return stx.raw.setArg 2 attrKind
end Lean.Elab.Command
|
073210850fc8ca67f7853f1bc4041f4203656252
|
9d00e4b237465921fb33aa10eed92a2495ca2e46
|
/orRules.lean
|
534ae5bef222b1cedc998021044895cbe2f78e09
|
[] |
no_license
|
Bpalkmim/LeanNatD
|
7756abf1ed7b0e7a3e3b9d16ad756018f5c70c7c
|
2e73bb44e44b955839e7a0874cd7013fbfb9c4e3
|
refs/heads/master
| 1,610,999,141,530
| 1,475,515,895,000
| 1,475,515,895,000
| 69,893,600
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 1,522
|
lean
|
namespace orRules
-- Requer o namespace de implicação
open implRules
print " "
print "Provas com OR - início"
print " "
constant or : Prop → Prop → Prop
constants A B C : Prop
-- Definições
-- or_intro_right introduz o operador ∨ com as proposições recebidas por parâmetro na ordem
constant or_intro_right {X Y : Prop} : Proof X → Proof Y → Proof (or X Y)
-- or_intro_left inverte a ordem dos parâmetros para inserir no ∨ introduzido
constant or_intro_left {X Y : Prop} : Proof X → Proof Y → Proof (or Y X)
constant or_elim {X Y Z : Prop} : Proof (or X Y) → (Π x : Proof X, Proof Z) → (Π x : Proof Y, Proof Z) → Proof Z → Proof Z → Proof Z
-- Termos úteis
variable a : Proof A
variable b : Proof B
variable c : Proof C
variable aORb : Proof (or A B)
variable aDEPc : Π x : Proof A, Proof C
variable bDEPc : Π x : Proof B, Proof C
variable concl : Π x : Proof (or A B), Proof (or B A)
-- Testes iniciais
check @or_intro_left
check @or_intro_right
check @or_elim
check or_intro_right a b
check or_intro_left b a
check or_elim aORb aDEPc bDEPc c c
print "------"
-- Testes parciais
check or_intro_left a -- (λx. x ∨ a)
check or_intro_right b -- (λx. b ∨ x)
check or_elim aORb (or_intro_right b) (or_intro_left a)
print "------"
-- Teste final (A ∨ B) → (B ∨ A)
check impl_intro
concl
(or_elim
aORb
(or_intro_right b)
(or_intro_left a)
(or_intro_right b a)
(or_intro_left a b)
)
print " "
print "Provas com OR - fim"
print " "
end orRules
|
3979206c27fa7b9227383c60ef3d5072bf0dcc35
|
5d166a16ae129621cb54ca9dde86c275d7d2b483
|
/library/init/meta/relation_tactics.lean
|
868a540a39d90127f6b67278591604a538d386a7
|
[
"Apache-2.0"
] |
permissive
|
jcarlson23/lean
|
b00098763291397e0ac76b37a2dd96bc013bd247
|
8de88701247f54d325edd46c0eed57aeacb64baf
|
refs/heads/master
| 1,611,571,813,719
| 1,497,020,963,000
| 1,497,021,515,000
| 93,882,536
| 1
| 0
| null | 1,497,029,896,000
| 1,497,029,896,000
| null |
UTF-8
|
Lean
| false
| false
| 1,850
|
lean
|
/-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.tactic init.function
namespace tactic
open expr
private meta def relation_tactic (md : transparency) (op_for : environment → name → option name) (tac_name : string) : tactic unit :=
do tgt ← target,
env ← get_env,
let r := get_app_fn tgt,
match (op_for env (const_name r)) with
| (some refl) := do r ← mk_const refl, apply_core r {md := md} >> return ()
| none := fail $ tac_name ++ " tactic failed, target is not a relation application with the expected property."
end
meta def reflexivity (md := semireducible) : tactic unit :=
relation_tactic md environment.refl_for "reflexivity"
meta def symmetry (md := semireducible) : tactic unit :=
relation_tactic md environment.symm_for "symmetry"
meta def transitivity (md := semireducible) : tactic unit :=
relation_tactic md environment.trans_for "transitivity"
meta def relation_lhs_rhs (e : expr) : tactic (name × expr × expr) :=
do (const c _) ← return e.get_app_fn,
env ← get_env,
(some (arity, lhs_pos, rhs_pos)) ← return $ env.relation_info c,
args ← return $ get_app_args e,
guard (args.length = arity),
(some lhs) ← return $ args.nth lhs_pos,
(some rhs) ← return $ args.nth rhs_pos,
return (c, lhs, rhs)
meta def target_lhs_rhs : tactic (name × expr × expr) :=
target >>= relation_lhs_rhs
meta def subst_vars_aux : list expr → tactic unit
| [] := failed
| (h::hs) := do
o ← try_core (subst h),
if o.is_none then subst_vars_aux hs
else return ()
/-- Try to apply subst exhaustively -/
meta def subst_vars : tactic unit :=
repeat (local_context >>= subst_vars_aux) >> try (reflexivity reducible)
end tactic
|
9c371f28af8f960fad4795039f4e5ba2903c5be1
|
9cb9db9d79fad57d80ca53543dc07efb7c4f3838
|
/src/normed_snake.lean
|
080d578b1dbfcc78775f4d87c57ffd843dbfed94
|
[] |
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,390
|
lean
|
import system_of_complexes.basic
universe variables u
noncomputable theory
open_locale nnreal
open category_theory opposite normed_group_hom system_of_complexes
variables (M M' N : system_of_complexes.{u}) (f : M ⟶ M') (g : M' ⟶ N)
/-- The normed snake lemma, weak version. See Proposition 9.10 from Analytic.pdf -/
--TODO Add the non weak version for complete system of complexes
lemma weak_normed_snake {k k' k'' K K' K'' : ℝ≥0}
[hk : fact (1 ≤ k)] [hk' : fact (1 ≤ k')] [hk'' : fact (1 ≤ k'')]
{m : ℤ} {c₀ : ℝ≥0}
(hM : M.is_weak_bounded_exact k K m c₀)
(hM' : M'.is_weak_bounded_exact k' K' m c₀)
(hM'_adm : M'.admissible)
(hf : ∀ c i, is_strict (f.apply : M c i ⟶ M' c i))
(Hf : ∀ (c : ℝ≥0) (i : ℤ) (hi : i ≤ m + 1) (x : M (k'' * c) i),
∥(res x : M c i)∥ ≤ K'' * ∥f x∥)
(hg : ∀ c i, (g.apply : M' c i ⟶ N c i).ker = f.apply.range)
(hgquot : system_of_complexes.is_quotient g) :
N.is_weak_bounded_exact (k''*k*k') (K'*(K*K'' + 1)) (m - 1) c₀ :=
begin
have bound_nonneg : (0 : ℝ) ≤ K' * (K * K'' + 1),
{ exact_mod_cast nnreal.zero_le_coe },
intros c hc i hi,
let c₁ := k'' * (k * (k' * c)),
suffices : ∀ n : N c₁ (i + 1), ∀ ε > 0,
∃ y : N c i, ∥res n - d y∥ ≤ K' * (K * K'' + 1) * ∥d n∥ + ε,
{ dsimp [c₁] at this,
intros n₁ ε hε,
haveI hc : fact (k'' * k * k' * c = c₁) := by { dsimp [fact, c₁], ring },
let n : ↥(N c₁ (i + 1)) := res n₁,
rcases this n ε hε with ⟨y, hy : ∥res (res n₁) - d y∥ ≤ K' * (K * K'' + 1) * ∥d (res n₁)∥ + ε⟩,
rw [res_res, d_res] at hy,
have : ∥(res (d n₁) : N (k'' * (k * (k' * c))) (i + 1 + 1))∥ ≤ ∥d n₁∥,
by { apply (admissible_of_quotient hgquot hM'_adm).res_norm_noninc, },
exact ⟨y, hy.trans (add_le_add_right (mul_le_mul_of_nonneg_left this bound_nonneg) ε)⟩ },
intros n ε hε,
let ε₁ := ε/(K' * (K * K'' + 2) + 1),
have honele : 1 ≤ K' * (K * K'' + 2) + 1, by { change fact _, apply_instance },
have hε₁_ε : (K' * (K * K'' + 2) + 1 : ℝ)*ε₁ = ε,
from mul_div_cancel' _ (by exact_mod_cast ne_of_gt (lt_of_lt_of_le zero_lt_one honele)),
have hε₁ : 0 < ε₁, from div_pos hε (lt_of_lt_of_le zero_lt_one honele),
let c₁ := k''*(k*(k'*c)),
obtain ⟨m' : M' c₁ (i + 1), hm' : g m' = n⟩ := (hgquot _ _).surjective _,
let m₁' := d m',
have hm₁' : g m₁' = d n := by simpa [hm'] using (d_apply _ _ g m').symm,
obtain ⟨m₁'' : M' c₁ (i + 1 + 1), hgm₁'' : g m₁'' = d n, hnorm_m₁'' : ∥m₁''∥ < ∥d n∥ + ε₁⟩ :=
quotient_norm_lift (hgquot _ _) hε₁ (d n),
obtain ⟨m₁, hm₁⟩ : ∃ m₁ : M c₁ (i + 1 + 1), f m₁ + m₁'' = m₁',
{ have hrange : m₁' - m₁'' ∈ f.apply.range,
{ rw [← hg _ _, mem_ker _ _, normed_group_hom.map_sub],
change g m₁' - g m₁'' = 0,
rw [hm₁', hgm₁'', sub_self] },
obtain ⟨m₁, hm₁ : f m₁ = m₁' - m₁''⟩ := (mem_range _ _).1 hrange,
exact ⟨m₁, by rw [hm₁, sub_add_cancel]⟩ },
have hm₂ : f (d m₁) = -d m₁'',
{ rw [← d_apply, eq_sub_of_add_eq hm₁, normed_group_hom.map_sub, ← coe_comp,
d, d, homological_complex.d_squared, coe_zero, ← neg_inj, pi.zero_apply, zero_sub], },
have hle : ∥res (d m₁)∥ ≤ K'' * ∥m₁''∥,
calc ∥res (d m₁)∥ ≤ K'' * ∥f (d m₁)∥ : Hf _ _ (by linarith) (d m₁)
... = K'' * ∥d m₁''∥ : by rw [hm₂, norm_neg]
... ≤ K'' * ∥m₁''∥ : (mul_le_mul_of_nonneg_left (hM'_adm.d_norm_noninc _ _ m₁'') $
nnreal.coe_nonneg K''),
obtain ⟨m₀ : M (k'*c) (i+1), hm₀ : ∥res (res m₁) - d m₀∥ ≤ K * ∥d (res m₁)∥ + ε₁⟩ :=
hM _ (le_trans hc $ le_mul_of_one_le_left' hk') _ (by linarith) (res m₁) ε₁ hε₁,
replace hm₀ : ∥res m₁ - d m₀∥ ≤ K * K'' * ∥d n∥ + K*K''*ε₁ + ε₁,
calc ∥res m₁ - d m₀∥ = ∥res (res m₁) - d m₀∥ : by rw res_res
... ≤ K * ∥d (res m₁)∥ + ε₁ : hm₀
... = K * ∥res (d m₁)∥ + ε₁ : by rw d_res
... ≤ K*(K'' * ∥m₁''∥) + ε₁ : add_le_add_right (mul_le_mul_of_nonneg_left hle nnreal.zero_le_coe) _
... ≤ K*(K'' * (∥d n∥ + ε₁)) + ε₁ : add_le_add_right (mul_le_mul_of_nonneg_left
(mul_le_mul_of_nonneg_left hnorm_m₁''.le nnreal.zero_le_coe)
nnreal.zero_le_coe) ε₁
... = K * K'' * ∥d n∥ + K*K''*ε₁ + ε₁ : by ring,
let mnew' := res m' - f m₀,
let mnew₁' := d mnew',
have hmnew' : mnew₁' = res m₁'' + f (res m₁ - d m₀),
calc mnew₁' = d (res m' - f m₀) : rfl
... = res (d m') - (f (d m₀)) : by rw [normed_group_hom.map_sub, d_res _, d_apply]
... = res (d m') - (f (res m₁)) + (f (res m₁) - f (d m₀)) : by abel
... = res m₁'' + f ((res m₁) - (d m₀)) : by
{ rw [← system_of_complexes.map_sub, ← res_apply,
← normed_group_hom.map_sub, ← sub_eq_of_eq_add' hm₁.symm] },
have hnormle : ∥mnew₁'∥ ≤ (K*K'' + 1)*∥d n∥ + (K*K'' + 2) * ε₁,
calc ∥mnew₁'∥ = ∥res m₁'' + f (res m₁ - d m₀)∥ : by rw [hmnew']
... ≤ ∥res m₁''∥ + ∥f (res m₁ - d m₀)∥ : norm_add_le _ _
... ≤ ∥m₁''∥ + ∥f (res m₁ - d m₀)∥ : add_le_add_right
(hM'_adm.res_norm_noninc _ _ _ infer_instance m₁'') _
... = ∥m₁''∥ + ∥res m₁ - d m₀∥ : by erw hf
... ≤ ∥d n∥ + ε₁ + ∥res m₁ - d m₀∥ : add_le_add_right (le_of_lt hnorm_m₁'') _
... ≤ ∥d n∥ + ε₁ + (K * K'' * ∥d n∥ + K * K'' * ε₁ + ε₁) : add_le_add_left hm₀ _
... = (K*K'' + 1)*∥d n∥ + (K*K'' + 2) * ε₁ : by ring,
obtain ⟨mnew₀ : M' c i, hmnew₀ : ∥res mnew' - d mnew₀∥ ≤ K' * ∥d mnew'∥ + ε₁⟩ :=
hM' _ hc _ (hi.trans (sub_one_lt m)) mnew' _ hε₁,
replace hmnew₀ : ∥res mnew' - d mnew₀∥ ≤ K' * ((K * K'' + 1) * ∥d n∥ + (K * K'' + 2) * ε₁) + ε₁ :=
hmnew₀.trans (add_le_add_right (mul_le_mul_of_nonneg_left hnormle nnreal.zero_le_coe) ε₁),
let nnew₀ : ↥(N c i) := g mnew₀,
have hmnewlift : g (res mnew' - d mnew₀) = res n - d nnew₀,
{ suffices h : g mnew' = res n,
{ rw [system_of_complexes.map_sub, ← res_apply, ← d_apply, h, res_res] },
rw system_of_complexes.map_sub,
have hker : f m₀ ∈ g.apply.ker,
{ rw [hg _ _, mem_range _ _],
use [m₀, rfl] },
replace hker : g (f m₀) = 0, by rwa mem_ker at hker,
rw [hker, sub_zero, ← res_apply, hm'] },
use nnew₀,
rw ← hmnewlift,
suffices : ∥res mnew' - d mnew₀∥ ≤ K' * (K * K'' + 1) * ∥d n∥ + ε,
from (quotient_norm_le (hgquot _ _) (res mnew' - d mnew₀)).trans this,
calc ∥res mnew' - d mnew₀∥ ≤ K' * ((K * K'' + 1) * ∥d n∥ + (K * K'' + 2) * ε₁) + ε₁ : hmnew₀
... = K' * (K * K'' + 1) * ∥d n∥ + (K'*(K * K'' + 2) + 1)* ε₁ : by ring
... = K' * (K * K'' + 1) * ∥d n∥ + ε : by rw hε₁_ε,
end
|
306dd96374a16d6b73cf340610f328770bbcea36
|
d406927ab5617694ec9ea7001f101b7c9e3d9702
|
/src/category_theory/sites/cover_lifting.lean
|
deca91fbd087b9b556f6c586f04be7d0fe12eadf
|
[
"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
| 13,245
|
lean
|
/-
Copyright (c) 2021 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import category_theory.sites.sheaf
import category_theory.limits.kan_extension
import category_theory.sites.cover_preserving
/-!
# Cover-lifting functors between sites.
We define cover-lifting functors between sites as functors that pull covering sieves back to
covering sieves. This concept is also known as *cocontinuous functors* or
*cover-reflecting functors*, but we have chosen this name following [MM92] in order to avoid
potential naming collision or confusion with the general definition of cocontinuous functors
between categories as functors preserving small colimits.
The definition given here seems stronger than the definition found elsewhere,
but they are actually equivalent via `category_theory.grothendieck_topology.superset_covering`.
(The precise statement is not formalized, but follows from it quite trivially).
## Main definitions
* `category_theory.sites.cover_lifting`: a functor between sites is cover-lifting if it
pulls back covering sieves to covering sieves
* `category_theory.sites.copullback`: A cover-lifting functor `G : (C, J) ⥤ (D, K)` induces a
morphism of sites in the same direction as the functor.
## Main results
* `category_theory.sites.Ran_is_sheaf_of_cover_lifting`: If `G : C ⥤ D` is cover_lifting, then
`Ran G.op` (`ₚu`) as a functor `(Cᵒᵖ ⥤ A) ⥤ (Dᵒᵖ ⥤ A)` of presheaves maps sheaves to sheaves.
* `category_theory.pullback_copullback_adjunction`: If `G : (C, J) ⥤ (D, K)` is cover-lifting,
cover-preserving, and compatible-preserving, then `pullback G` and `copullback G` are adjoint.
## References
* [Elephant]: *Sketches of an Elephant*, P. T. Johnstone: C2.3.
* [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92]
* https://stacks.math.columbia.edu/tag/00XI
-/
universes w v v₁ v₂ v₃ u u₁ u₂ u₃
noncomputable theory
open category_theory
open opposite
open category_theory.presieve.family_of_elements
open category_theory.presieve
open category_theory.limits
namespace category_theory
section cover_lifting
variables {C : Type*} [category C] {D : Type*} [category D] {E : Type*} [category E]
variables (J : grothendieck_topology C) (K : grothendieck_topology D)
variables {L : grothendieck_topology E}
/--
A functor `G : (C, J) ⥤ (D, K)` between sites is called to have the cover-lifting property
if for all covering sieves `R` in `D`, `R.pullback G` is a covering sieve in `C`.
-/
@[nolint has_nonempty_instance]
structure cover_lifting (G : C ⥤ D) : Prop :=
(cover_lift : ∀ {U : C} {S : sieve (G.obj U)} (hS : S ∈ K (G.obj U)), S.functor_pullback G ∈ J U)
/-- The identity functor on a site is cover-lifting. -/
lemma id_cover_lifting : cover_lifting J J (𝟭 _) := ⟨λ _ _ h, by simpa using h⟩
variables {J K}
/-- The composition of two cover-lifting functors are cover-lifting -/
lemma comp_cover_lifting {F : C ⥤ D} (hu : cover_lifting J K F) {G : D ⥤ E}
(hv : cover_lifting K L G) : cover_lifting J L (F ⋙ G) :=
⟨λ _ S h, hu.cover_lift (hv.cover_lift h)⟩
end cover_lifting
/-!
We will now prove that `Ran G.op` (`ₚu`) maps sheaves to sheaves if `G` is cover-lifting. This can
be found in <https://stacks.math.columbia.edu/tag/00XK>. However, the proof given here uses the
amalgamation definition of sheaves, and thus does not require that `C` or `D` has categorical
pullbacks.
For the following proof sketch, `⊆` denotes the homs on `C` and `D` as in the topological analogy.
By definition, the presheaf `𝒢 : Dᵒᵖ ⥤ A` is a sheaf if for every sieve `S` of `U : D`, and every
compatible family of morphisms `X ⟶ 𝒢(V)` for each `V ⊆ U : S` with a fixed source `X`,
we can glue them into a morphism `X ⟶ 𝒢(U)`.
Since the presheaf `𝒢 := (Ran G.op).obj ℱ.val` is defined via `𝒢(U) = lim_{G(V) ⊆ U} ℱ(V)`, for
gluing the family `x` into a `X ⟶ 𝒢(U)`, it suffices to provide a `X ⟶ ℱ(Y)` for each
`G(Y) ⊆ U`. This can be done since `{ Y' ⊆ Y : G(Y') ⊆ U ∈ S}` is a covering sieve for `Y` on
`C` (by the cover-lifting property of `G`). Thus the morphisms `X ⟶ 𝒢(G(Y')) ⟶ ℱ(Y')` can be
glued into a morphism `X ⟶ ℱ(Y)`. This is done in `get_sections`.
In `glued_limit_cone`, we verify these obtained sections are indeed compatible, and thus we obtain
A `X ⟶ 𝒢(U)`. The remaining work is to verify that this is indeed the amalgamation and is unique.
-/
variables {C D : Type u} [category.{v} C] [category.{v} D]
variables {A : Type w} [category.{max u v} A] [has_limits A]
variables {J : grothendieck_topology C} {K : grothendieck_topology D}
namespace Ran_is_sheaf_of_cover_lifting
variables {G : C ⥤ D} (hu : cover_lifting J K G) (ℱ : Sheaf J A)
variables {X : A} {U : D} (S : sieve U) (hS : S ∈ K U)
instance (X : Dᵒᵖ) : has_limits_of_shape (structured_arrow X G.op) A :=
begin
haveI := limits.has_limits_of_size_shrink.{v (max u v) (max u v) (max u v)} A,
exact has_limits_of_size.has_limits_of_shape _
end
variables (x : S.arrows.family_of_elements ((Ran G.op).obj ℱ.val ⋙ coyoneda.obj (op X)))
variables (hx : x.compatible)
/-- The family of morphisms `X ⟶ 𝒢(G(Y')) ⟶ ℱ(Y')` defined on `{ Y' ⊆ Y : G(Y') ⊆ U ∈ S}`. -/
def pulledback_family (Y : structured_arrow (op U) G.op) :=
(((x.pullback Y.hom.unop).functor_pullback G).comp_presheaf_map
(show _ ⟶ _, from whisker_right ((Ran.adjunction A G.op).counit.app ℱ.val)
(coyoneda.obj (op X))))
@[simp] lemma pulledback_family_apply (Y : structured_arrow (op U) G.op) {W} {f : W ⟶ _} (Hf) :
pulledback_family ℱ S x Y f Hf =
x (G.map f ≫ Y.hom.unop) Hf ≫ ((Ran.adjunction A G.op).counit.app ℱ.val).app (op W) := rfl
variables {x} {S}
include hu hS hx
/-- Given a `G(Y) ⊆ U`, we can find a unique section `X ⟶ ℱ(Y)` that agrees with `x`. -/
def get_section (Y : structured_arrow (op U) G.op) : X ⟶ ℱ.val.obj Y.right :=
begin
let hom_sh := whisker_right ((Ran.adjunction A G.op).counit.app ℱ.val) (coyoneda.obj (op X)),
have S' := (K.pullback_stable Y.hom.unop hS),
have hs' := ((hx.pullback Y.3.unop).functor_pullback G).comp_presheaf_map hom_sh,
exact (ℱ.2 X _ (hu.cover_lift S')).amalgamate _ hs'
end
lemma get_section_is_amalgamation (Y : structured_arrow (op U) G.op) :
(pulledback_family ℱ S x Y).is_amalgamation (get_section hu ℱ hS hx Y) :=
is_sheaf_for.is_amalgamation _ _
lemma get_section_is_unique (Y : structured_arrow (op U) G.op)
{y} (H : (pulledback_family ℱ S x Y).is_amalgamation y) : y = get_section hu ℱ hS hx Y :=
begin
apply is_sheaf_for.is_separated_for _ (pulledback_family ℱ S x Y),
{ exact H },
{ apply get_section_is_amalgamation },
{ exact ℱ.2 X _ (hu.cover_lift (K.pullback_stable Y.hom.unop hS)) }
end
@[simp] lemma get_section_commute {Y Z : structured_arrow (op U) G.op} (f : Y ⟶ Z) :
get_section hu ℱ hS hx Y ≫ ℱ.val.map f.right = get_section hu ℱ hS hx Z :=
begin
apply get_section_is_unique,
intros V' fV' hV',
have eq : Z.hom = Y.hom ≫ (G.map f.right.unop).op,
{ convert f.w, erw category.id_comp },
rw eq at hV',
convert get_section_is_amalgamation hu ℱ hS hx Y (fV' ≫ f.right.unop) _ using 1,
{ tidy },
{ simp only [eq, quiver.hom.unop_op, pulledback_family_apply,
functor.map_comp, unop_comp, category.assoc] },
{ change S (G.map _ ≫ Y.hom.unop),
simpa only [functor.map_comp, category.assoc] using hV' }
end
/-- The limit cone in order to glue the sections obtained via `get_section`. -/
def glued_limit_cone : limits.cone (Ran.diagram G.op ℱ.val (op U)) :=
{ X := X, π := { app := λ Y, get_section hu ℱ hS hx Y, naturality' := λ Y Z f, by tidy } }
@[simp] lemma glued_limit_cone_π_app (W) : (glued_limit_cone hu ℱ hS hx).π.app W =
get_section hu ℱ hS hx W := rfl
/-- The section obtained by passing `glued_limit_cone` into `category_theory.limits.limit.lift`. -/
def glued_section : X ⟶ ((Ran G.op).obj ℱ.val).obj (op U) :=
limit.lift _ (glued_limit_cone hu ℱ hS hx)
/--
A helper lemma for the following two lemmas. Basically stating that if the section `y : X ⟶ 𝒢(V)`
coincides with `x` on `G(V')` for all `G(V') ⊆ V ∈ S`, then `X ⟶ 𝒢(V) ⟶ ℱ(W)` is indeed the
section obtained in `get_sections`. That said, this is littered with some more categorical jargon
in order to be applied in the following lemmas easier.
-/
lemma helper {V} (f : V ⟶ U) (y : X ⟶ ((Ran G.op).obj ℱ.val).obj (op V)) (W)
(H : ∀ {V'} {fV : G.obj V' ⟶ V} (hV), y ≫ ((Ran G.op).obj ℱ.val).map fV.op = x (fV ≫ f) hV) :
y ≫ limit.π (Ran.diagram G.op ℱ.val (op V)) W =
(glued_limit_cone hu ℱ hS hx).π.app ((structured_arrow.map f.op).obj W) :=
begin
dsimp only [glued_limit_cone_π_app],
apply get_section_is_unique hu ℱ hS hx ((structured_arrow.map f.op).obj W),
intros V' fV' hV',
dsimp only [Ran.adjunction, Ran.equiv, pulledback_family_apply],
erw [adjunction.adjunction_of_equiv_right_counit_app],
have : y ≫ ((Ran G.op).obj ℱ.val).map (G.map fV' ≫ W.hom.unop).op =
x (G.map fV' ≫ W.hom.unop ≫ f) (by simpa only using hV'),
{ convert H (show S ((G.map fV' ≫ W.hom.unop) ≫ f),
by simpa only [category.assoc] using hV') using 2,
simp only [category.assoc] },
simp only [quiver.hom.unop_op, equiv.symm_symm, structured_arrow.map_obj_hom, unop_comp,
equiv.coe_fn_mk, functor.comp_map, coyoneda_obj_map, category.assoc, ← this, op_comp,
Ran_obj_map, nat_trans.id_app],
erw [category.id_comp, limit.pre_π],
congr,
convert limit.w (Ran.diagram G.op ℱ.val (op V)) (structured_arrow.hom_mk' W fV'.op),
rw structured_arrow.map_mk,
erw category.comp_id,
simp only [quiver.hom.unop_op, functor.op_map, quiver.hom.op_unop]
end
/-- Verify that the `glued_section` is an amalgamation of `x`. -/
lemma glued_section_is_amalgamation : x.is_amalgamation (glued_section hu ℱ hS hx) :=
begin
intros V fV hV,
ext W,
simp only [functor.comp_map, limit.lift_pre, coyoneda_obj_map, Ran_obj_map, glued_section],
erw limit.lift_π,
symmetry,
convert helper hu ℱ hS hx _ (x fV hV) _ _ using 1,
intros V' fV' hV',
convert hx (fV') (𝟙 _) hV hV' (by rw category.id_comp),
simp only [op_id, functor_to_types.map_id_apply]
end
/-- Verify that the amalgamation is indeed unique. -/
lemma glued_section_is_unique (y) (hy: x.is_amalgamation y) : y = glued_section hu ℱ hS hx :=
begin
unfold glued_section limit.lift,
ext W,
erw limit.lift_π,
convert helper hu ℱ hS hx (𝟙 _) y W _,
{ simp only [op_id, structured_arrow.map_id] },
{ intros V' fV' hV',
convert hy fV' (by simpa only [category.comp_id] using hV'),
erw category.comp_id }
end
end Ran_is_sheaf_of_cover_lifting
/--
If `G` is cover_lifting, then `Ran G.op` pushes sheaves to sheaves.
This result is basically https://stacks.math.columbia.edu/tag/00XK,
but without the condition that `C` or `D` has pullbacks.
-/
theorem Ran_is_sheaf_of_cover_lifting {G : C ⥤ D} (hG : cover_lifting J K G) (ℱ : Sheaf J A) :
presheaf.is_sheaf K ((Ran G.op).obj ℱ.val) :=
begin
intros X U S hS x hx,
split, swap,
{ apply Ran_is_sheaf_of_cover_lifting.glued_section hG ℱ hS hx },
split,
{ apply Ran_is_sheaf_of_cover_lifting.glued_section_is_amalgamation },
{ apply Ran_is_sheaf_of_cover_lifting.glued_section_is_unique }
end
variable (A)
/-- A cover-lifting functor induces a morphism of sites in the same direction as the functor. -/
def sites.copullback {G : C ⥤ D} (hG : cover_lifting J K G) :
Sheaf J A ⥤ Sheaf K A :=
{ obj := λ ℱ, ⟨(Ran G.op).obj ℱ.val, Ran_is_sheaf_of_cover_lifting hG ℱ⟩,
map := λ _ _ f, ⟨(Ran G.op).map f.val⟩,
map_id' := λ ℱ, Sheaf.hom.ext _ _ $ (Ran G.op).map_id ℱ.val,
map_comp' := λ _ _ _ f g, Sheaf.hom.ext _ _ $ (Ran G.op).map_comp f.val g.val }
/--
Given a functor between sites that is cover-preserving, cover-lifting, and compatible-preserving,
the pullback and copullback along `G` are adjoint to each other
-/
@[simps unit_app_val counit_app_val] noncomputable
def sites.pullback_copullback_adjunction {G : C ⥤ D} (Hp : cover_preserving J K G)
(Hl : cover_lifting J K G) (Hc : compatible_preserving K G) :
sites.pullback A Hc Hp ⊣ sites.copullback A Hl :=
{ hom_equiv := λ X Y,
{ to_fun := λ f, ⟨(Ran.adjunction A G.op).hom_equiv X.val Y.val f.val⟩,
inv_fun := λ f, ⟨((Ran.adjunction A G.op).hom_equiv X.val Y.val).symm f.val⟩,
left_inv := λ f, by { ext1, dsimp, rw [equiv.symm_apply_apply] },
right_inv := λ f, by { ext1, dsimp, rw [equiv.apply_symm_apply] } },
unit := { app := λ X, ⟨(Ran.adjunction A G.op).unit.app X.val⟩,
naturality' := λ _ _ f, Sheaf.hom.ext _ _ $ (Ran.adjunction A G.op).unit.naturality f.val },
counit := { app := λ X, ⟨(Ran.adjunction A G.op).counit.app X.val⟩,
naturality' := λ _ _ f, Sheaf.hom.ext _ _ $ (Ran.adjunction A G.op).counit.naturality f.val },
hom_equiv_unit' := λ X Y f, by { ext1, apply (Ran.adjunction A G.op).hom_equiv_unit },
hom_equiv_counit' := λ X Y f, by { ext1, apply (Ran.adjunction A G.op).hom_equiv_counit } }
end category_theory
|
c9f8c3f5e12161ba6ecf658fec7e1b83b55fcabc
|
cf39355caa609c0f33405126beee2739aa3cb77e
|
/tests/lean/try_for_heap.lean
|
4a4c0fdd3d9586631303125b99ecfecc8e717277
|
[
"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
| 2,227
|
lean
|
constant heap : Type
constant ptr : Type
constant val : Type
constant pt : ptr → val → heap
constant hunion : heap → heap → heap
constant is_def : heap → Prop
infix `∙`:60 := hunion
infix `↣`:70 := pt
/-
constant hunion_is_assoc : is_associative heap hunion
constant hunion_is_comm : is_commutative heap hunion
attribute [instance] hunion_is_comm hunion_is_assoc
axiom noalias : ∀ (h : heap) (y₁ y₂ : ptr) (w₁ w₂ : val), is_def (h ∙ y₁ ↣ w₁ ∙ y₂ ↣ w₂) → y₁ ≠ y₂
-/
open tactic
meta def my_tac : tactic unit :=
using_smt `[ { [smt]
intros,
smt_tactic.add_lemmas_from_facts,
eblast
} ]
-- set_option profiler true
example
(h₁ h₂ : heap) (x₁ x₂ x₃ x₄ : ptr) (v₁ v₂ v₃ : val)
(hcomm : ∀ x y, x ∙ y = y ∙ x)
(hassoc : ∀ x y z, (x ∙ y) ∙ z = x ∙ (y ∙ z))
(hnoalias : ∀ h y₁ y₂ w₁ w₂, is_def (h ∙ y₁ ↣ w₁ ∙ y₂ ↣ w₂) → y₁ ≠ y₂)
: is_def (h₁ ∙ (x₁ ↣ v₁ ∙ x₂ ↣ v₂) ∙ h₂ ∙ (x₃ ↣ v₃)) → x₁ ≠ x₃ ∧ x₁ ≠ x₂ ∧ x₂ ≠ x₃ :=
by my_tac -- should work
example
(h₁ h₂ : heap) (x₁ x₂ x₃ x₄ : ptr) (v₁ v₂ v₃ : val)
(hcomm : ∀ x y, x ∙ y = y ∙ x)
(hassoc : ∀ x y z, (x ∙ y) ∙ z = x ∙ (y ∙ z))
(hnoalias : ∀ h y₁ y₂ w₁ w₂, is_def (h ∙ y₁ ↣ w₁ ∙ y₂ ↣ w₂) → y₁ ≠ y₂)
: is_def (h₁ ∙ (x₁ ↣ v₁ ∙ x₂ ↣ v₂) ∙ h₂ ∙ (x₃ ↣ v₃)) → x₁ ≠ x₃ ∧ x₁ ≠ x₂ ∧ x₂ ≠ x₃ :=
by try_for 100 $ my_tac -- should timeout
/-
Remark: disable this test because it was too slow.
TODO(Leo): enable again after we resolve the cache issues, and re-implement the SMT
tactic framework
example
(h₁ h₂ : heap) (x₁ x₂ x₃ x₄ : ptr) (v₁ v₂ v₃ : val)
(hcomm : ∀ x y, x ∙ y = y ∙ x)
(hassoc : ∀ x y z, (x ∙ y) ∙ z = x ∙ (y ∙ z))
(hnoalias : ∀ h y₁ y₂ w₁ w₂, is_def (h ∙ y₁ ↣ w₁ ∙ y₂ ↣ w₂) → y₁ ≠ y₂)
: is_def (h₁ ∙ (x₁ ↣ v₁ ∙ x₂ ↣ v₂) ∙ h₂ ∙ (x₃ ↣ v₃)) → x₁ ≠ x₃ ∧ x₁ ≠ x₂ ∧ x₂ ≠ x₃ :=
by try_for 100000 $ my_tac -- should work
-/
|
e355411244a8f5b9cad929526ceee6084d10b5bd
|
74addaa0e41490cbaf2abd313a764c96df57b05d
|
/Mathlib/data/analysis/topology.lean
|
3fa267b906750e20c771cb76e42d7a7a5fd01db3
|
[] |
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
| 8,197
|
lean
|
/-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
Computational realization of topological spaces (experimental).
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.topology.bases
import Mathlib.data.analysis.filter
import Mathlib.PostPort
universes u_1 u_2 l u_3 u_4 u_5 u_6
namespace Mathlib
/-- A `ctop α σ` is a realization of a topology (basis) on `α`,
represented by a type `σ` together with operations for the top element and
the intersection operation. -/
structure ctop (α : Type u_1) (σ : Type u_2)
where
f : σ → set α
top : α → σ
top_mem : ∀ (x : α), x ∈ f (top x)
inter : (a b : σ) → (x : α) → x ∈ f a ∩ f b → σ
inter_mem : ∀ (a b : σ) (x : α) (h : x ∈ f a ∩ f b), x ∈ f (inter a b x h)
inter_sub : ∀ (a b : σ) (x : α) (h : x ∈ f a ∩ f b), f (inter a b x h) ⊆ f a ∩ f b
namespace ctop
protected instance has_coe_to_fun {α : Type u_1} {σ : Type u_3} : has_coe_to_fun (ctop α σ) :=
has_coe_to_fun.mk (fun (x : ctop α σ) => σ → set α) f
@[simp] theorem coe_mk {α : Type u_1} {σ : Type u_3} (f : σ → set α) (T : α → σ) (h₁ : ∀ (x : α), x ∈ f (T x)) (I : (a b : σ) → (x : α) → x ∈ f a ∩ f b → σ) (h₂ : ∀ (a b : σ) (x : α) (h : x ∈ f a ∩ f b), x ∈ f (I a b x h)) (h₃ : ∀ (a b : σ) (x : α) (h : x ∈ f a ∩ f b), f (I a b x h) ⊆ f a ∩ f b) (a : σ) : coe_fn (mk f T h₁ I h₂ h₃) a = f a :=
rfl
/-- Map a ctop to an equivalent representation type. -/
def of_equiv {α : Type u_1} {σ : Type u_3} {τ : Type u_4} (E : σ ≃ τ) : ctop α σ → ctop α τ :=
sorry
@[simp] theorem of_equiv_val {α : Type u_1} {σ : Type u_3} {τ : Type u_4} (E : σ ≃ τ) (F : ctop α σ) (a : τ) : coe_fn (of_equiv E F) a = coe_fn F (coe_fn (equiv.symm E) a) := sorry
/-- Every `ctop` is a topological space. -/
def to_topsp {α : Type u_1} {σ : Type u_3} (F : ctop α σ) : topological_space α :=
topological_space.generate_from (set.range (f F))
theorem to_topsp_is_topological_basis {α : Type u_1} {σ : Type u_3} (F : ctop α σ) : topological_space.is_topological_basis (set.range (f F)) := sorry
@[simp] theorem mem_nhds_to_topsp {α : Type u_1} {σ : Type u_3} (F : ctop α σ) {s : set α} {a : α} : s ∈ nhds a ↔ ∃ (b : σ), a ∈ coe_fn F b ∧ coe_fn F b ⊆ s := sorry
end ctop
/-- A `ctop` realizer for the topological space `T` is a `ctop`
which generates `T`. -/
structure ctop.realizer (α : Type u_5) [T : topological_space α]
where
σ : Type u_6
F : ctop α σ
eq : ctop.to_topsp F = T
protected def ctop.to_realizer {α : Type u_1} {σ : Type u_3} (F : ctop α σ) : ctop.realizer α :=
ctop.realizer.mk σ F sorry
namespace ctop.realizer
protected theorem is_basis {α : Type u_1} [T : topological_space α] (F : realizer α) : topological_space.is_topological_basis (set.range (f (F F))) :=
eq.mp (Eq._oldrec (Eq.refl (topological_space.is_topological_basis (set.range (f (F F))))) (eq F))
(to_topsp_is_topological_basis (F F))
protected theorem mem_nhds {α : Type u_1} [T : topological_space α] (F : realizer α) {s : set α} {a : α} : s ∈ nhds a ↔ ∃ (b : σ F), a ∈ coe_fn (F F) b ∧ coe_fn (F F) b ⊆ s :=
eq.mp (Eq._oldrec (Eq.refl (s ∈ nhds a ↔ ∃ (b : σ F), a ∈ coe_fn (F F) b ∧ coe_fn (F F) b ⊆ s)) (eq F))
(mem_nhds_to_topsp (F F))
theorem is_open_iff {α : Type u_1} [topological_space α] (F : realizer α) {s : set α} : is_open s ↔ ∀ (a : α), a ∈ s → ∃ (b : σ F), a ∈ coe_fn (F F) b ∧ coe_fn (F F) b ⊆ s :=
iff.trans is_open_iff_mem_nhds (ball_congr fun (a : α) (h : a ∈ s) => realizer.mem_nhds F)
theorem is_closed_iff {α : Type u_1} [topological_space α] (F : realizer α) {s : set α} : is_closed s ↔ ∀ (a : α), (∀ (b : σ F), a ∈ coe_fn (F F) b → ∃ (z : α), z ∈ coe_fn (F F) b ∩ s) → a ∈ s := sorry
theorem mem_interior_iff {α : Type u_1} [topological_space α] (F : realizer α) {s : set α} {a : α} : a ∈ interior s ↔ ∃ (b : σ F), a ∈ coe_fn (F F) b ∧ coe_fn (F F) b ⊆ s :=
iff.trans mem_interior_iff_mem_nhds (realizer.mem_nhds F)
protected theorem is_open {α : Type u_1} [topological_space α] (F : realizer α) (s : σ F) : is_open (coe_fn (F F) s) := sorry
theorem ext' {α : Type u_1} [T : topological_space α] {σ : Type u_2} {F : ctop α σ} (H : ∀ (a : α) (s : set α), s ∈ nhds a ↔ ∃ (b : σ), a ∈ coe_fn F b ∧ coe_fn F b ⊆ s) : to_topsp F = T := sorry
theorem ext {α : Type u_1} [T : topological_space α] {σ : Type u_2} {F : ctop α σ} (H₁ : ∀ (a : σ), is_open (coe_fn F a)) (H₂ : ∀ (a : α) (s : set α), s ∈ nhds a → ∃ (b : σ), a ∈ coe_fn F b ∧ coe_fn F b ⊆ s) : to_topsp F = T := sorry
protected def id {α : Type u_1} [topological_space α] : realizer α :=
mk (Subtype fun (x : set α) => is_open x)
(mk subtype.val (fun (_x : α) => { val := set.univ, property := is_open_univ }) set.mem_univ
(fun (_x : Subtype fun (x : set α) => is_open x) => sorry) sorry sorry)
sorry
def of_equiv {α : Type u_1} {τ : Type u_4} [topological_space α] (F : realizer α) (E : σ F ≃ τ) : realizer α :=
mk τ (of_equiv E (F F)) sorry
@[simp] theorem of_equiv_σ {α : Type u_1} {τ : Type u_4} [topological_space α] (F : realizer α) (E : σ F ≃ τ) : σ (of_equiv F E) = τ :=
rfl
@[simp] theorem of_equiv_F {α : Type u_1} {τ : Type u_4} [topological_space α] (F : realizer α) (E : σ F ≃ τ) (s : τ) : coe_fn (F (of_equiv F E)) s = coe_fn (F F) (coe_fn (equiv.symm E) s) := sorry
protected def nhds {α : Type u_1} [topological_space α] (F : realizer α) (a : α) : filter.realizer (nhds a) :=
filter.realizer.mk (Subtype fun (s : σ F) => a ∈ coe_fn (F F) s)
(cfilter.mk (fun (s : Subtype fun (s : σ F) => a ∈ coe_fn (F F) s) => coe_fn (F F) (subtype.val s))
{ val := top (F F) a, property := sorry } (fun (_x : Subtype fun (s : σ F) => a ∈ coe_fn (F F) s) => sorry) sorry
sorry)
sorry
@[simp] theorem nhds_σ {α : Type u_1} {β : Type u_2} [topological_space α] (m : α → β) (F : realizer α) (a : α) : filter.realizer.σ (realizer.nhds F a) = Subtype fun (s : σ F) => a ∈ coe_fn (F F) s :=
rfl
@[simp] theorem nhds_F {α : Type u_1} {β : Type u_2} [topological_space α] (m : α → β) (F : realizer α) (a : α) (s : filter.realizer.σ (realizer.nhds F a)) : coe_fn (filter.realizer.F (realizer.nhds F a)) s = coe_fn (F F) (subtype.val s) :=
rfl
theorem tendsto_nhds_iff {α : Type u_1} {β : Type u_2} [topological_space α] {m : β → α} {f : filter β} (F : filter.realizer f) (R : realizer α) {a : α} : filter.tendsto m f (nhds a) ↔
∀ (t : σ R),
a ∈ coe_fn (F R) t →
∃ (s : filter.realizer.σ F), ∀ (x : β), x ∈ coe_fn (filter.realizer.F F) s → m x ∈ coe_fn (F R) t :=
iff.trans (filter.realizer.tendsto_iff m F (realizer.nhds R a)) subtype.forall
end ctop.realizer
structure locally_finite.realizer {α : Type u_1} {β : Type u_2} [topological_space α] (F : ctop.realizer α) (f : β → set α)
where
bas : (a : α) → Subtype fun (s : ctop.realizer.σ F) => a ∈ coe_fn (ctop.realizer.F F) s
sets : (x : α) → fintype ↥(set_of fun (i : β) => set.nonempty (f i ∩ coe_fn (ctop.realizer.F F) ↑(bas x)))
theorem locally_finite.realizer.to_locally_finite {α : Type u_1} {β : Type u_2} [topological_space α] {F : ctop.realizer α} {f : β → set α} (R : locally_finite.realizer F f) : locally_finite f := sorry
theorem locally_finite_iff_exists_realizer {α : Type u_1} {β : Type u_2} [topological_space α] (F : ctop.realizer α) {f : β → set α} : locally_finite f ↔ Nonempty (locally_finite.realizer F f) := sorry
def compact.realizer {α : Type u_1} [topological_space α] (R : ctop.realizer α) (s : set α) :=
{f : filter α} →
(F : filter.realizer f) →
(x : filter.realizer.σ F) →
f ≠ ⊥ → coe_fn (filter.realizer.F F) x ⊆ s → Subtype fun (a : α) => a ∈ s ∧ nhds a ⊓ f ≠ ⊥
|
ed25f772f716756ad4b950ff6c3dee3d4f0b2d2e
|
acc85b4be2c618b11fc7cb3005521ae6858a8d07
|
/data/list/basic.lean
|
cec1c6888e72b4f45bc98834dc0183f82d4470dc
|
[
"Apache-2.0"
] |
permissive
|
linpingchuan/mathlib
|
d49990b236574df2a45d9919ba43c923f693d341
|
5ad8020f67eb13896a41cc7691d072c9331b1f76
|
refs/heads/master
| 1,626,019,377,808
| 1,508,048,784,000
| 1,508,048,784,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 94,159
|
lean
|
/-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
Basic properties of lists.
-/
import logic.basic data.nat.basic data.option data.bool tactic.interactive
open function nat
namespace list
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
@[simp] theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ [].
theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → h₁ = h₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq)
theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → t₁ = t₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq)
theorem cons_inj {a : α} : injective (cons a) :=
assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe
@[simp] theorem cons_inj' (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' :=
⟨λ e, cons_inj e, congr_arg _⟩
/- mem -/
theorem eq_nil_of_forall_not_mem : ∀ {l : list α}, (∀ a, a ∉ l) → l = nil
| [] := assume h, rfl
| (b :: l') := assume h, absurd (mem_cons_self b l') (h b)
theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _
theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b :=
assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, this)
(assume : a ∈ [], absurd this (not_mem_nil a))
@[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b :=
⟨eq_of_mem_singleton, by intro h; simp [h]⟩
theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l :=
assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl)
(assume : a = b, begin subst a, exact binl end)
(assume : a ∈ l, this)
theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t :=
mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩
theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l
| (b::l) _ := zero_lt_succ _
theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l
| (b::l) _ := ⟨b, mem_cons_self _ _⟩
theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t :=
begin
induction l with b l ih; simp at h; cases h with h h,
{ subst h, exact ⟨[], l, rfl⟩ },
{ cases ih h with s e, cases e with t e,
subst l, exact ⟨b::s, t, rfl⟩ }
end
theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l :=
or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r)
theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b :=
assume nin aeqb, absurd (or.inl aeqb) nin
theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l :=
assume nin nainl, absurd (or.inr nainl) nin
theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l :=
assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2))
theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l :=
assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p)
theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l :=
begin
induction l with b l' ih,
{simp at h, contradiction },
{simp, simp at h, cases h with h h,
{simp *},
{exact or.inr (ih h)}}
end
theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b :=
begin
induction l with c l' ih,
{simp at h, contradiction},
{cases (eq_or_mem_of_mem_cons h) with h h,
{existsi c, simp [h]},
{cases ih h with a ha, cases ha with ha₁ ha₂,
existsi a, simp * }}
end
@[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b :=
⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩
@[simp] theorem mem_map_of_inj {f : α → β} (H : injective f) {a : α} {l : list α} :
f a ∈ map f l ↔ a ∈ l :=
⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩
@[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l
| [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩
| (c :: L) := by simp [join, @mem_join L]; exact
⟨λh, match h with
| or.inl ac := ⟨c, ac, or.inl rfl⟩
| or.inr ⟨l, al, lL⟩ := ⟨l, al, or.inr lL⟩
end,
λ⟨l, al, o⟩, o.elim (λ lc, by rw lc at al; exact or.inl al) (λlL, or.inr ⟨l, al, lL⟩)⟩
theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l :=
mem_join.1
theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L :=
mem_join.2 ⟨l, lL, al⟩
@[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ bind l f ↔ ∃ a ∈ l, b ∈ f a :=
iff.trans mem_join
⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩,
λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩
theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ bind l f → ∃ a ∈ l, b ∈ f a :=
mem_bind.1
theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ bind l f :=
mem_bind.2 ⟨a, al, h⟩
/- list subset -/
theorem subset_app_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_left _ _
theorem subset_app_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_right _ _
theorem cons_subset_of_subset_of_mem {a : α} {l m : list α} (ainm : a ∈ m) (lsubm : l ⊆ m) :
a::l ⊆ m :=
λ b, or_imp_distrib.2 ⟨λ e, e.symm ▸ ainm, @lsubm _⟩
theorem app_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) :
l₁ ++ l₂ ⊆ l :=
λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _)
theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = []
| [] s := rfl
| (a::l) s := false.elim $ s $ mem_cons_self a l
theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l :=
show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩
/- append -/
theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
theorem append_foldl (f : α → β → α) (a : α) (s t : list β) : foldl f a (s ++ t) = foldl f (foldl f a s) t :=
by {induction s with b s H generalizing a, refl, simp [foldl], rw H _}
theorem append_foldr (f : α → β → β) (a : β) (s t : list α) : foldr f a (s ++ t) = foldr f (foldr f a t) s :=
by {induction s with b s H generalizing a, refl, simp [foldr], rw H _}
/- join -/
attribute [simp] join
/- repeat take drop -/
def split_at : ℕ → list α → list α × list α
| 0 a := ([], a)
| (succ n) [] := ([], [])
| (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r)
@[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l)
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := by simp [split_at, split_at_eq_take_drop n xs]
@[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := by simp [take_append_drop n xs]
-- TODO(Leo): cleanup proof after arith dec proc
theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂
| [] [] t₁ t₂ h hl := ⟨rfl, h⟩
| (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl
| [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm
| (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap,
let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in
by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩
theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ :=
(append_inj h hl).left
theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ :=
(append_inj h hl).right
theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ :=
append_inj h $ @nat.add_right_cancel _ (length t₁) _ $
let hap := congr_arg length h in by simp at hap; rwa [← hl] at hap
theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ :=
(append_inj' h hl).left
theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ :=
(append_inj' h hl).right
theorem append_left_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ :=
append_inj_left' h rfl
theorem append_right_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ :=
append_inj_right h rfl
theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a
| (n+1) h := or.elim h id $ @eq_of_mem_repeat _
theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length
| [] H := rfl
| (b::l) H :=
have b = a ∧ ∀ (x : α), x ∈ l → x = a,
by simpa [or_imp_distrib, forall_and_distrib] using H,
by dsimp; congr; [exact this.1, exact eq_repeat_of_mem this.2]
theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩
theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] :=
λ b h, mem_singleton.2 (eq_of_mem_repeat h)
@[simp] theorem map_const {l : list α} {b : β} : map (function.const α b) l = repeat b l.length :=
by induction l; simp [-add_comm, *]
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ :=
by rw map_const at h; exact eq_of_mem_repeat h
/- concat -/
@[simp] def concat : list α → α → list α
| [] a := [a]
| (b::l) a := b :: concat l a
@[simp] theorem concat_nil (a : α) : concat [] a = [a] := rfl
@[simp] theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl
@[simp] theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] :=
by induction l; intro h; contradiction
@[simp] theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ :=
by induction l₁ with b l₁ ih; [simp, simp [ih]]
@[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] :=
by induction l; simp [*, concat]
@[simp] theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) :=
by simp [succ_eq_add_one]
theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a :=
by induction l₂ with b l₂ ih; simp
/- reverse -/
@[simp] theorem reverse_nil : reverse (@nil α) = [] :=
rfl
local attribute [simp] reverse_core
@[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a :=
have aux : ∀ l₁ l₂, reverse_core l₁ (concat l₂ a) = concat (reverse_core l₁ l₂) a,
by intros l₁; induction l₁; intros; rsimp,
aux l nil
theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] :=
by simp
@[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] :=
rfl
@[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) :=
by induction s; simp *
@[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l :=
by induction l; simp *
theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) :=
by simp
@[simp] theorem length_reverse (l : list α) : length (reverse l) = length l :=
by induction l; simp *
@[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) :=
by induction l; simp *
@[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l :=
by induction l; simp *; rw mem_append_eq
/- last -/
@[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ :=
by {induction l; intros, contradiction, simp *, reflexivity}
@[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a :=
begin
induction l with hd tl ih; rsimp,
have haux : tl ++ [a] ≠ [],
{apply append_ne_nil_of_ne_nil_right, contradiction},
simp *
end
theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a :=
by simp *
@[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl
@[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) :
last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl
theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) :
last l₁ h₁ = last l₂ h₂ :=
by subst l₁
/- head and tail -/
@[simp] theorem head_cons [h : inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl
@[simp] theorem tail_nil : tail (@nil α) = [] := rfl
@[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl
@[simp] theorem head_append [h : inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s :=
by {induction s, contradiction, simp}
theorem cons_head_tail [h : inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l :=
by {induction l, contradiction, simp}
/- map -/
theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) :=
by induction l; simp *
theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l :=
by induction l; simp *
@[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l :=
by revert a; induction l; intros; simp *
@[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l :=
by revert a; induction l; intros; simp *
theorem foldl_hom (f : α → β) (g : α → γ → α) (g' : β → γ → β) (a : α)
(h : ∀a x, f (g a x) = g' (f a) x) (l : list γ) : f (foldl g a l) = foldl g' (f a) l :=
by revert a; induction l; intros; simp *
theorem foldr_hom (f : α → β) (g : γ → α → α) (g' : γ → β → β) (a : α)
(h : ∀x a, f (g x a) = g' x (f a)) (l : list γ) : f (foldr g a l) = foldr g' (f a) l :=
by revert a; induction l; intros; simp *
theorem eq_nil_of_map_eq_nil {f : α → β} {l :list α} (h : map f l = nil) : l = nil :=
eq_nil_of_length_eq_zero (begin rw [← length_map f l], simp [h] end)
/- map₂ -/
theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] :=
by cases l; refl
theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] :=
by cases l; refl
/- sublists -/
@[simp] theorem nil_sublist : Π (l : list α), [] <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons _ _ a (nil_sublist l)
@[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons2 _ _ a (sublist.refl l)
@[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ :=
sublist.rec_on h₂ (λ_ s, s)
(λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁))
(λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁
(λ_, nil_sublist _)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl)
l₁ h₁
@[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l :=
sublist.cons _ _ _ (sublist.refl l)
theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ :=
sublist.trans (sublist_cons a l₁)
theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ :=
sublist.cons2 _ _ _ s
@[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂
| [] l₂ := nil_sublist _
| (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂)
@[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂
| [] l₂ := sublist.refl _
| (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂)
theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ :=
sublist.cons _ _ _
theorem sublist_app_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ :=
s.trans $ sublist_append_left _ _
theorem sublist_app_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ :=
s.trans $ sublist_append_right _ _
theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂
| ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s
| ._ (sublist.cons2 ._ ._ a s) := s
theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ :=
⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩
@[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂
| [] := iff.rfl
| (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l)
theorem append_sublist_append_of_sublist_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l :=
by induction h; [refl,
apply sublist_cons_of_sublist _ ih_1,
apply cons_sublist_cons _ ih_1]
theorem reverse_sublist {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse :=
by induction h; simp; [
exact sublist_app_of_sublist_left ih_1,
exact append_sublist_append_of_sublist_right ih_1 _]
@[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ :=
⟨λ h, by have := reverse_sublist h; simp at this; assumption, reverse_sublist⟩
@[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ :=
⟨λ h, by have := reverse_sublist h; simp at this; assumption,
λ h, append_sublist_append_of_sublist_right h l⟩
theorem subset_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂
| ._ ._ sublist.slnil b h := h
| ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (subset_of_sublist s h)
| ._ ._ (sublist.cons2 l₁ l₂ a s) b h :=
match eq_or_mem_of_mem_cons h with
| or.inl h := h ▸ mem_cons_self _ _
| or.inr h := mem_cons_of_mem _ (subset_of_sublist s h)
end
theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l :=
⟨λ h, subset_of_sublist h (mem_singleton_self _), λ h,
let ⟨s, t, e⟩ := mem_split h in e.symm ▸
(cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩
theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] :=
eq_nil_of_subset_nil $ subset_of_sublist s
theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n :=
⟨λ h, by simpa using length_le_of_sublist h,
λ h, by induction h; [apply sublist.refl, simp [*, sublist.cons]] ⟩
theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂
| ._ ._ sublist.slnil h := rfl
| ._ ._ (sublist.cons l₁ l₂ a s) h :=
absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self
| ._ ._ (sublist.cons2 l₁ l₂ a s) h :=
by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h
theorem sublist_antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ :=
eq_of_sublist_of_length_eq s₁ (le_antisymm (length_le_of_sublist s₁) (length_le_of_sublist s₂))
instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂)
| [] l₂ := is_true $ nil_sublist _
| (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h
| (a::l₁) (b::l₂) :=
if h : a = b then
decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $
by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩
else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂)
⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with
| a, l₁, sublist.cons ._ ._ ._ s', h := s'
| ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h
end⟩
/- index_of -/
section index_of
variable [decidable_eq α]
@[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl
theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl
theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 :=
assume e, if_pos e
@[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 :=
index_of_cons_eq _ rfl
@[simp] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) :=
assume n, if_neg n
theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l :=
begin
induction l with b l ih; simp [-add_comm],
by_cases a = b with h; simp [h, -add_comm],
{ intro, contradiction },
{ rw ← ih, exact ⟨succ_inj, congr_arg _⟩ }
end
@[simp] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l :=
index_of_eq_length.2
theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l :=
begin
induction l with b l ih; simp [-add_comm, index_of_cons],
by_cases a = b with h; simp [h, -add_comm, zero_le],
exact succ_le_succ ih
end
theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l :=
⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al,
λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩
end index_of
/- nth element -/
theorem nth_le_nth : Π (l : list α) (n h), nth l n = some (nth_le l n h)
| [] n h := absurd h (not_lt_zero n)
| (a :: l) 0 h := rfl
| (a :: l) (n+1) h := nth_le_nth l n _
theorem nth_ge_len : Π (l : list α) (n), n ≥ length l → nth l n = none
| [] n h := rfl
| (a :: l) 0 h := absurd h (not_lt_zero _)
| (a :: l) (n+1) h := nth_ge_len l n (le_of_succ_le_succ h)
theorem ext : Π {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂
| [] [] h := rfl
| (a::l₁) [] h := by have h0 := h 0; contradiction
| [] (a'::l₂) h := by have h0 := h 0; contradiction
| (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa; simp [*, ext (λn, h (n+1))]
theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ :=
ext $ λn, if h₁ : n < length l₁
then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])]
else let h₁ := le_of_not_gt h₁ in by rw [nth_ge_len _ _ h₁, nth_ge_len _ _ (by rwa [← hl])]
@[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a
| (b::l) h := by by_cases a = b with h'; simp *
@[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a :=
by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)]
theorem nth_le_reverse_aux1 : Π (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2
| [] r i := λh1 h2, rfl
| (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, by simp); exact
λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2)
theorem nth_le_reverse_aux2 : Π (l r : list α) (i : nat) (h1) (h2),
nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2
| [] r i h1 h2 := absurd h2 (not_lt_zero _)
| (a :: l) r 0 h1 h2 := begin
have aux := nth_le_reverse_aux1 l (a :: r) 0,
rw zero_add at aux,
exact aux _ (zero_lt_succ _)
end
| (a :: l) r (i+1) h1 h2 := begin
have aux := nth_le_reverse_aux2 l (a :: r) i,
have heq := calc length (a :: l) - 1 - (i + 1)
= length l - (1 + i) : by rw add_comm; refl
... = length l - 1 - i : by rw nat.sub_sub,
rw [← heq] at aux,
apply aux
end
@[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) :
nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 :=
nth_le_reverse_aux2 _ _ _ _ _
def to_array (l : list α) : array α l.length :=
{data := λ v, l.nth_le v.1 v.2}
@[simp] def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget
/- take, drop -/
@[simp] theorem take_zero : ∀ (l : list α), take 0 l = [] :=
begin intros, reflexivity end
@[simp] theorem take_nil : ∀ n, take n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl
theorem take_all : ∀ (l : list α), take (length l) l = l
| [] := rfl
| (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_all end
theorem take_all_of_ge : ∀ {n} {l : list α}, n ≥ length l → take n l = l
| 0 [] h := rfl
| 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _))
| (n+1) [] h := rfl
| (n+1) (a::l) h :=
begin
change a :: take n l = a :: l,
rw [take_all_of_ge (le_of_succ_le_succ h)]
end
theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l
| n 0 l := by rw [min_zero, take_zero, take_nil]
| 0 m l := by simp
| (succ n) (succ m) nil := by simp
| (succ n) (succ m) (a::l) := by simp [min_succ_succ, take_take]
/- take_while -/
def take_while (p : α → Prop) [decidable_pred p] : list α → list α
| [] := []
| (a::l) := if p a then a :: take_while l else []
/- foldl, foldr, scanl, scanr -/
@[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl
@[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) :
foldl f a (b::l) = foldl f (f a b) l := rfl
@[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
foldr f b (a::l) = f a (foldr f b l) := rfl
@[simp] theorem foldl_append (f : β → α → β) :
∀ (b : β) (l₁ l₂ : list α), foldl f b (l₁++l₂) = foldl f (foldl f b l₁) l₂
| b [] l₂ := rfl
| b (a::l₁) l₂ := by simp [foldl_append]
@[simp] theorem foldr_append (f : α → β → β) :
∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁
| b [] l₂ := rfl
| b (a::l₁) l₂ := by simp [foldr_append]
theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l :=
by induction l; simp [*, foldr]
theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l :=
let t := foldl_reverse (λx y, f y x) a (reverse l) in
by rw reverse_reverse l at t; rwa t
@[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l
| [] := rfl
| (x::l) := by simp [foldr_eta l]
def scanl (f : α → β → α) : α → list β → list α
| a [] := [a]
| a (b::l) := a :: scanl (f a b) l
def scanr_aux (f : α → β → β) (b : β) : list α → β × list β
| [] := (b, [])
| (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l')
def scanr (f : α → β → β) (b : β) (l : list α) : list β :=
let (b', l') := scanr_aux f b l in b' :: l'
@[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl
@[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α),
scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l)
| a [] := rfl
| a (x::l) := let t := scanr_aux_cons x l in
by simp [scanr, scanr_aux] at t; simp [scanr, scanr_aux, t]
@[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
scanr f b (a::l) = foldr f b (a::l) :: scanr f b l :=
by simp [scanr]
section foldl_eq_foldr
-- foldl and foldr coincide when f is commutative and associative
variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f)
include hassoc
theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l)
| a b nil := rfl
| a b (c :: l) := by simp [foldl1_eq_foldr1 _ _ l]; rw hassoc
include hcomm
theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l)
| a b nil := hcomm a b
| a b (c::l) := by simp;
rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; simp
theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l
| a nil := rfl
| a (b :: l) :=
by simp [foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l)
end foldl_eq_foldr
/- sum -/
def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1
def sum [has_add α] [has_zero α] : list α → α := foldl (+) 0
/- all & any, bounded quantifiers over lists -/
theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x :=
by simp
@[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} :
(∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x :=
by simp [or_imp_distrib, forall_and_distrib]
theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} :
(∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x :=
by simp
theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α}
(h : ∀ x ∈ a :: l, p x) :
∀ x ∈ l, p x :=
(forall_mem_cons.1 h).2
theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x :=
by simp
theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) :
∃ x ∈ a :: l, p x :=
bex.intro a (by simp) h
theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) :
∃ x ∈ a :: l, p x :=
bex.elim h (λ x xl px, bex.intro x (by simp [xl]) px)
theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) :
p a ∨ ∃ x ∈ l, p x :=
bex.elim h (λ x xal px,
or.elim (eq_or_mem_of_mem_cons xal)
(assume : x = a, begin rw ←this, simp [px] end)
(assume : x ∈ l, or.inr (bex.intro x this px)))
@[simp] theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) :
(∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x :=
iff.intro or_exists_of_exists_mem_cons
(assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists)
@[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl
@[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl
theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a :=
by induction l with a l; simp [forall_and_distrib, *]
theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p]
{l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a :=
by simp [all_iff_forall]
@[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl
@[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl
theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a :=
by induction l with a l; simp [and_or_distrib_left, exists_or_distrib, *]
theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p]
{l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a :=
by simp [any_iff_exists]
theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p :=
any_iff_exists.2 ⟨_, h₁, h₂⟩
instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∀ x ∈ l, p x) :=
decidable_of_iff _ all_iff_forall_prop
instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∃ x ∈ l, p x) :=
decidable_of_iff _ any_iff_exists_prop
/- find -/
section find
variables (p : α → Prop) [decidable_pred p]
def find : list α → option α
| [] := none
| (a::l) := if p a then some a else find l
def find_indexes_aux (p : α → Prop) [decidable_pred p] : list α → nat → list nat
| [] n := []
| (a::l) n := let t := find_indexes_aux l (succ n) in if p a then n :: t else t
def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat :=
find_indexes_aux p l 0
@[simp] theorem find_nil : find p [] = none := rfl
@[simp] theorem find_cons_of_pos {p : α → Prop} [h : decidable_pred p] {a : α}
(l) (h : p a) : find p (a::l) = some a :=
if_pos h
@[simp] theorem find_cons_of_neg {p : α → Prop} [h : decidable_pred p] {a : α}
(l) (h : ¬ p a) : find p (a::l) = find p l :=
if_neg h
@[simp] theorem find_eq_none {p : α → Prop} [h : decidable_pred p] {l : list α} :
find p l = none ↔ ∀ x ∈ l, ¬ p x :=
begin
induction l with a l IH, {simp},
by_cases p a; simp [h, IH],
intro, contradiction
end
@[simp] theorem find_some {p : α → Prop} [h : decidable_pred p] {l : list α} {a : α}
(H : find p l = some a) : p a :=
begin
induction l with b l IH, {contradiction},
by_cases p b; simp [h] at H,
{ subst b, assumption },
{ exact IH H }
end
@[simp] theorem find_mem {p : α → Prop} [h : decidable_pred p] {l : list α} {a : α}
(H : find p l = some a) : a ∈ l :=
begin
induction l with b l IH, {contradiction},
by_cases p b; simp [h] at H,
{ subst b, apply mem_cons_self },
{ exact mem_cons_of_mem _ (IH H) }
end
end find
def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a)
/- filter_map -/
@[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) :
filter_map f (a :: l) = filter_map f l :=
by simp [filter_map, h]
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (l : list α) {b : β} (h : f a = some b) :
filter_map f (a :: l) = b :: filter_map f l :=
by simp [filter_map, h]
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
funext $ λ l, begin
induction l with a l IH, {simp},
simp [filter_map_cons_some (some ∘ f) _ _ rfl, IH]
end
theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] :
filter_map (option.guard p) = filter p :=
funext $ λ l, begin
induction l with a l IH, {simp},
by_cases p a with pa; simp [filter_map, option.guard, pa, IH]
end
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) :
filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l :=
begin
induction l with a l IH, {refl},
cases h : f a with b,
{ rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH],
simp [h, option.bind] },
rw filter_map_cons_some _ _ _ h,
cases h' : g b with c;
[ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH],
rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ];
simp [h, h', option.bind]
end
theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) :
map g (filter_map f l) = filter_map (λ x, (f x).map g) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) :
filter_map g (map f l) = filter_map (g ∘ f) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) :
filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l :=
by rw [← filter_map_eq_filter, filter_map_filter_map]; refl
theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) :
filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l :=
begin
rw [← filter_map_eq_filter, filter_map_filter_map], congr,
apply funext, intro x,
show (option.guard p x).bind f = ite (p x) (f x) none,
by_cases p x; simp [h, option.guard, option.bind]
end
@[simp] theorem filter_map_some (l : list α) : filter_map some l = l :=
by rw filter_map_eq_map; apply map_id
@[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} :
b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b :=
begin
induction l with a l IH, {simp},
cases h : f a with b',
{ have : f a ≠ some b, {rw h, intro, contradiction},
simp [filter_map_cons_none _ _ h, IH,
or_and_distrib_right, exists_or_distrib, this] },
{ have : f a = some b ↔ b = b',
{ split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} },
simp [filter_map_cons_some _ _ _ h, IH,
or_and_distrib_right, exists_or_distrib, this] }
end
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (l : list α) :
map g (filter_map f l) = l :=
by simp [map_filter_map, H]
theorem filter_map_sublist_filter_map (f : α → option β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ :=
by induction s with l₁ l₂ a s IH l₁ l₂ a s IH;
simp [filter_map]; cases f a with b;
simp [filter_map, IH, sublist.cons, sublist.cons2]
/- filter -/
section filter
variables {p : α → Prop} [decidable_pred p]
@[simp] theorem filter_subset (l : list α) : filter p l ⊆ l :=
subset_of_sublist $ filter_sublist l
theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a
| [] ain := absurd ain (not_mem_nil a)
| (b::l) ain :=
if pb : p b then
have a ∈ b :: filter p l, begin simp [pb] at ain, assumption end,
or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, begin rw [← this] at pb, exact pb end)
(assume : a ∈ filter p l, of_mem_filter this)
else
begin simp [pb] at ain, exact (of_mem_filter ain) end
theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l :=
filter_subset l h
theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l
| [] ain pa := absurd ain (not_mem_nil a)
| (b::l) ain pa :=
if pb : p b then
or.elim (eq_or_mem_of_mem_cons ain)
(assume : a = b, by simp [pb, this])
(assume : a ∈ l, begin simp [pb], exact (mem_cons_of_mem _ (mem_filter_of_mem this pa)) end)
else
or.elim (eq_or_mem_of_mem_cons ain)
(assume : a = b, begin simp [this] at pa, contradiction end) --absurd (this ▸ pa) pb)
(assume : a ∈ l, by simp [pa, pb, mem_filter_of_mem this])
@[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a :=
⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩
theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a :=
begin
induction l with a l, {simp},
by_cases p a; simp [filter, *],
show filter p l ≠ a :: l, intro e,
have := filter_sublist l, rw e at this,
exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _)
end
theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a :=
by simp [-and.comm, eq_nil_iff_forall_not_mem, mem_filter]
theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ :=
by rw ← filter_map_eq_filter; exact filter_map_sublist_filter_map _ s
@[simp] theorem span_eq_take_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), span p l = (take_while p l, drop_while p l)
| [] := rfl
| (a::l) := by by_cases p a with pa; simp [span, take_while, drop_while, pa, span_eq_take_drop l]
@[simp] theorem take_while_append_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), take_while p l ++ drop_while p l = l
| [] := rfl
| (a::l) := by by_cases p a with pa; simp [take_while, drop_while, pa, take_while_append_drop l]
def countp (p : α → Prop) [decidable_pred p] : list α → nat
| [] := 0
| (x::xs) := if p x then succ (countp xs) else countp xs
@[simp] theorem countp_nil (p : α → Prop) [decidable_pred p] : countp p [] = 0 := rfl
@[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 :=
if_pos pa
@[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l :=
if_neg pa
theorem countp_eq_length_filter (l) : countp p l = length (filter p l) :=
by induction l with x l; [refl, by_cases (p x)]; simp [*, -add_comm]
local attribute [simp] countp_eq_length_filter
@[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ :=
by simp
theorem exists_mem_of_countp_pos {l} (h : countp p l > 0) : ∃ a ∈ l, p a :=
by simp at h; exact
exists_imp_exists
(λ a al, ⟨mem_of_mem_filter al, of_mem_filter al⟩)
(exists_mem_of_length_pos h)
theorem countp_pos_of_mem {l a} (h : a ∈ l) (pa : p a) : countp p l > 0 :=
by simp; exact length_pos_of_mem (mem_filter_of_mem h pa)
theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ :=
by simpa using length_le_of_sublist (filter_sublist_filter s)
end filter
/- count -/
section count
variable [decidable_eq α]
def count (a : α) : list α → nat := countp (eq a)
@[simp] theorem count_nil (a : α) : count a [] = 0 := rfl
theorem count_cons (a b : α) (l : list α) :
count a (b :: l) = if a = b then succ (count a l) else count a l := rfl
theorem count_cons' (a b : α) (l : list α) :
count a (b :: l) = count a l + (if a = b then 1 else 0) :=
decidable.by_cases
(assume : a = b, begin rw [count_cons, if_pos this, if_pos this] end)
(assume : a ≠ b, begin rw [count_cons, if_neg this, if_neg this], reflexivity end)
@[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) :=
if_pos rfl
@[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l :=
if_neg h
theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ :=
countp_le_of_sublist
theorem count_cons_ge_count (a b : α) (l : list α) : count a (b :: l) ≥ count a l :=
count_le_of_sublist _ (sublist_cons _ _)
theorem count_singleton (a : α) : count a [a] = 1 :=
by simp
@[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ :=
countp_append
@[simp] theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) :=
by rw [concat_eq_append, count_append, count_singleton]
theorem mem_of_count_pos {a : α} {l : list α} (h : count a l > 0) : a ∈ l :=
let ⟨a', ael, e⟩ := exists_mem_of_countp_pos h in e.symm ▸ ael
theorem count_pos_of_mem {a : α} {l : list α} (h : a ∈ l) : count a l > 0 :=
countp_pos_of_mem h rfl
theorem count_pos {a : α} {l : list α} : count a l > 0 ↔ a ∈ l :=
⟨mem_of_count_pos, count_pos_of_mem⟩
@[simp] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l :=
λ h', ne_of_gt (count_pos.2 h') h
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat];
exact λ b m, (eq_of_mem_repeat m).symm
theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l :=
⟨λ h, ((repeat_sublist_repeat a).2 h).trans $
have filter (eq a) l = repeat a (count a l), from eq_repeat.2
⟨by simp [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩,
by rw ← this; apply filter_sublist,
λ h, by simpa using count_le_of_sublist a h⟩
end count
/- prefix, suffix, infix -/
def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂
def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂
def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂
infix ` <+: `:50 := is_prefix
infix ` <:+ `:50 := is_suffix
infix ` <:+: `:50 := is_infix
@[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩
@[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩
@[simp] theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩
@[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩
@[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩
@[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a]
@[simp] theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp
theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨[], t, h⟩
theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨t, [], by simp [h]⟩
@[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l
@[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃
| l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, by simp⟩
@[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃
| l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, by simp⟩
@[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃
| l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp⟩
theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ :=
λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _)
theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_prefix
theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_suffix
theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ :=
length_le_of_sublist $ sublist_of_infix s
theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] :=
eq_nil_of_sublist_nil $ sublist_of_infix s
theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_prefix s
theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_suffix s
theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ :=
⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩,
λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩
theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_infix s
theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_prefix s
theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_suffix s
@[simp] def inits : list α → list (list α)
| [] := [[]]
| (a::l) := [] :: map (λt, a::t) (inits l)
@[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t
| s [] := suffices s = nil ↔ s <+: nil, by simpa,
⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩
| s (a::t) :=
suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa,
⟨λo, match s, o with
| ._, or.inl rfl := ⟨_, rfl⟩
| s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in
by rw [← hs, ← ht]; exact ⟨s, rfl⟩
end, λmi, match s, mi with
| [], ⟨._, rfl⟩ := or.inl rfl
| (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $
by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩
end⟩
@[simp] def tails : list α → list (list α)
| [] := [[]]
| (a::l) := (a::l) :: tails l
@[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t
| s [] := by simp; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩
| s (a::t) := by simp [mem_tails s t]; exact show s <:+ t ∨ s = a :: t ↔ s <:+ a :: t, from
⟨λo, match s, t, o with
| s, ._, or.inl ⟨l, rfl⟩ := ⟨a::l, rfl⟩
| ._, t, or.inr rfl := suffix_refl _
end, λe, match s, t, e with
| ._, t, ⟨[], rfl⟩ := or.inr rfl
| s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inl ⟨l, lt⟩)
end⟩
def sublists_aux : list α → (list α → list β → list β) → list β
| [] f := []
| (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r)))
def sublists (l : list α) : list (list α) :=
[] :: sublists_aux l cons
theorem sublists_aux_eq_foldl : ∀ (l : list α) {β : Type u} (f : list α → list β → list β),
sublists_aux l f = foldr f [] (sublists_aux l cons)
| [] β f := rfl
| (a::l) β f := suffices ∀ t, foldr (λ ys r, f ys (f (a :: ys) r)) [] t =
foldr f [] (t.foldr (λ ys r, ys :: (a :: ys) :: r) nil),
by simp [sublists_aux]; rw [sublists_aux_eq_foldl l, sublists_aux_eq_foldl l (λ ys r, ys :: (a :: ys) :: r), this],
λt, by induction t; simp; simp [ih_1]
theorem sublists_aux_cons_cons (l : list α) (a : α) :
sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) :=
by rw [← sublists_aux_eq_foldl]; refl
@[simp] theorem mem_sublists (s t : list α) : s ∈ sublists t ↔ s <+ t :=
by simp [sublists]; exact
⟨λm, let good := λ (l : list (list α)), ∀ s ∈ l, s <+ t in
suffices ∀ l (f : list α → list (list α) → list (list α)),
(∀ {x y}, x <+ l → good y → good (f x y)) → l <+ t → good (sublists_aux l f), from
or.elim m (λe, by rw e; apply nil_sublist)
(this t cons (λ x y hx hy s m, by exact or.elim m (λe, by rw e; exact hx) (hy s)) (sublist.refl _) s),
begin
intro l; induction l with a l IH; intros f al sl x m,
exact false.elim m,
refine al (cons_sublist_cons a (nil_sublist _)) _ _ m,
exact λs hs, IH _ (λx y hx hy, al (sublist_cons_of_sublist _ hx) (al (cons_sublist_cons _ hx) hy))
(sublist_of_cons_sublist sl) _ hs
end,
λsl, begin
have this : ∀ {a : α} {y t}, y ∈ t → y ∈ foldr (λ ys r, ys :: (a :: ys) :: r) nil t
∧ a :: y ∈ foldr (λ ys r, ys :: (a :: ys) :: r) nil t,
{ intros a y t yt, induction t with x t IH, exact absurd yt (not_mem_nil _),
simp, simp at yt, cases yt with yx yt,
{ simp [yx] },
{ cases IH yt with h1 h2,
exact ⟨or.inr $ or.inr h1, or.inr $ or.inr h2⟩ } },
induction sl with l₁ l₂ a sl IH l₁ l₂ a sl IH, exact or.inl rfl,
{ refine or.imp_right (λh, _) IH,
rw sublists_aux_cons_cons,
exact mem_cons_of_mem _ (this h).left },
{ refine or.inr _,
rw sublists_aux_cons_cons, simp,
refine or.imp (λ(h : l₁ = []), by rw h) (λh, _) IH,
exact (this h).right },
end⟩
instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂)
| [] l₂ := is_true ⟨l₂, rfl⟩
| (a::l₁) [] := is_false $ λ⟨t, te⟩, list.no_confusion te
| (a::l₁) (b::l₂) :=
if h : a = b then
decidable_of_decidable_of_iff (decidable_prefix l₁ l₂) $ by rw [← h]; exact
⟨λ⟨t, te⟩, ⟨t, by rw [← te]; refl⟩,
λ⟨t, te⟩, list.no_confusion te (λ_ te, ⟨t, te⟩)⟩
else
is_false $ λ⟨t, te⟩, list.no_confusion te $ λh', absurd h' h
-- Alternatively, use mem_tails
instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂)
| [] l₂ := is_true ⟨l₂, append_nil _⟩
| (a::l₁) [] := is_false $ λ⟨t, te⟩, absurd te $
append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h
| l₁ l₂ := let len1 := length l₁, len2 := length l₂ in
if hl : len1 ≤ len2 then
if he : drop (len2 - len1) l₂ = l₁ then is_true $
⟨take (len2 - len1) l₂, by rw [← he, take_append_drop]⟩
else is_false $
suffices length l₁ ≤ length l₂ → l₁ <:+ l₂ → drop (length l₂ - length l₁) l₂ = l₁,
from λsuf, he (this hl suf),
λ hl ⟨t, te⟩, append_inj_right'
((take_append_drop (length l₂ - length l₁) l₂).trans te.symm)
(by simp; exact nat.sub_sub_self hl)
else is_false $ λ⟨t, te⟩, hl $
show length l₁ ≤ length l₂, by rw [← te, length_append]; apply nat.le_add_left
instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂)
| [] l₂ := is_true ⟨[], l₂, rfl⟩
| (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $
append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h
| l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $
by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm;
exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩
/- transpose -/
def transpose_aux : list α → list (list α) → list (list α)
| [] ls := ls
| (a::i) [] := [a] :: transpose_aux i []
| (a::i) (l::ls) := (a::l) :: transpose_aux i ls
def transpose : list (list α) → list (list α)
| [] := []
| (l::ls) := transpose_aux l (transpose ls)
/- permutations -/
def permutations_aux2 (t : α) (ts : list α) : list α → (list α → β) → list β → list α × list β
| [] f r := (ts, r)
| (y::ys) f r := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) r in
(y :: us, f (t :: y :: us) :: zs)
private def meas : list α × list α → ℕ × ℕ | (l, i) := (length l + length i, length l)
local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas
def permutations_aux.F : Π (x : list α × list α), (Π (y : list α × list α), y ≺ x → list (list α)) → list (list α)
| ([], is) IH := []
| (t::ts, is) IH :=
have h1 : (ts, t :: is) ≺ (t :: ts, is), from
show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is, length (t :: ts)),
by rw nat.succ_add; exact prod.lex.right _ _ (lt_succ_self _),
have h2 : (is, []) ≺ (t :: ts, is), from prod.lex.left _ _ _ (lt_add_of_pos_left _ (succ_pos _)),
foldr (λy r, (permutations_aux2 t ts y id r).2) (IH (ts, t::is) h1) (is :: IH (is, []) h2)
def permutations_aux : list α × list α → list (list α) :=
well_founded.fix (inv_image.wf meas (prod.lex_wf lt_wf lt_wf)) permutations_aux.F
def permutations (l : list α) : list (list α) :=
l :: permutations_aux (l, [])
def permutations_aux.eqn_1 (is : list α) : permutations_aux ([], is) = [] :=
well_founded.fix_eq _ _ _
def permutations_aux.eqn_2 (t : α) (ts is) : permutations_aux (t::ts, is) =
foldr (λy r, (permutations_aux2 t ts y id r).2) (permutations_aux (ts, t::is)) (permutations is) :=
well_founded.fix_eq _ _ _
/- insert -/
section insert
variable [decidable_eq α]
@[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl
theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl
@[simp] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l :=
by simp [insert.def, h]
@[simp] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l :=
by simp [insert.def, h]
@[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l :=
begin
by_cases b ∈ l with h'; simp [h'],
apply (or_iff_right_of_imp _).symm,
exact λ e, e.symm ▸ h'
end
@[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l :=
by by_cases a ∈ l; simp *
@[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l :=
mem_insert_iff.2 (or.inl rfl)
@[simp] theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l :=
mem_insert_iff.2 (or.inr h)
theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l :=
mem_insert_iff.1 h
@[simp] theorem length_insert_of_mem {a : α} [decidable_eq α] {l : list α} (h : a ∈ l) :
length (insert a l) = length l :=
by simp [h]
@[simp] theorem length_insert_of_not_mem {a : α} [decidable_eq α] {l : list α} (h : a ∉ l) :
length (insert a l) = length l + 1 :=
by simp [h]
end insert
/- erase -/
section erase
variable [decidable_eq α]
@[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl
theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl
@[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l :=
by simp [erase_cons]
@[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a :=
by simp [erase_cons, h]
@[simp] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l :=
by induction l with b l; [refl,
simp [(ne_of_not_mem_cons h).symm, ih_1 (not_mem_of_not_mem_cons h)]]
theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) :
∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ :=
by induction l with b l; [cases h, {
simp at h,
by_cases b = a with e,
{ subst b, exact ⟨[], l, not_mem_nil _, rfl, by simp⟩ },
{ exact let ⟨l₁, l₂, h₁, h₂, h₃⟩ := ih_1 (h.resolve_left (ne.symm e)) in
⟨b::l₁, l₂, not_mem_cons_of_ne_of_not_mem (ne.symm e) h₁,
by rw h₂; refl,
by simp [e, h₃]⟩ } }]
@[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) :=
match l, l.erase a, exists_erase_eq h with
| ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩ := by simp [-add_comm]; refl
end
theorem erase_append_left {a : α} : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erase a = l₁.erase a ++ l₂
| (x::xs) l₂ h := begin
by_cases x = a with h'; simp [h'],
rw erase_append_left l₂ (mem_of_ne_of_mem (ne.symm h') h)
end
theorem erase_append_right {a : α} : ∀ {l₁ : list α} (l₂), a ∉ l₁ → (l₁++l₂).erase a = l₁ ++ l₂.erase a
| [] l₂ h := rfl
| (x::xs) l₂ h := by simp [*, (ne_of_not_mem_cons h).symm, (not_mem_of_not_mem_cons h)]
theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l :=
if h : a ∈ l then match l, l.erase a, exists_erase_eq h with
| ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩ := by simp
end else by simp [h]
theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l :=
subset_of_sublist (erase_sublist a l)
theorem mem_erase_of_ne_of_mem {a b : α} {l : list α} (ab : a ≠ b) (al : a ∈ l) : a ∈ l.erase b :=
if h : b ∈ l then match l, l.erase b, exists_erase_eq h, al with
| ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩, al :=
by simp at *; exact or.resolve_left al ab
end else by simp [h, al]
theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l :=
@erase_subset _ _ _ _ _
end erase
/- zip & unzip -/
@[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) :
zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl
@[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl
@[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] :=
by cases l; refl
@[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl
@[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) :
unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) :=
by rw unzip; cases unzip l; refl
theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l
| [] := rfl
| ((a, b) :: l) := by simp [zip_unzip l]
/- product -/
def product (l₁ : list α) (l₂ : list β) : list (α × β) :=
l₁.bind $ λ a, l₂.map $ prod.mk a
@[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl
@[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β)
: product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl
@[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = []
| [] := rfl
| (a::l) := begin rw [product_cons, product_nil], reflexivity end
@[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} :
(a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ :=
by simp [product]
theorem length_product (l₁ : list α) (l₂ : list β) :
length (product l₁ l₂) = length l₁ * length l₂ :=
by induction l₁ with x l₁ IH; simp [*, right_distrib]
/- disjoint -/
/- disjoint -/
section disjoint
def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, (a ∈ l₁ → a ∈ l₂ → false)
theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁
| a i₂ i₁ := d i₁ i₂
@[simp] theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl
theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ :=
disjoint_comm
theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b :=
by simp [disjoint_left, imp_not_comm]
theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂
| x m₁ := d (ss m₁)
theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂
| x m m₁ := d m (ss m₁)
theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ :=
disjoint_of_subset_left (list.subset_cons _ _)
theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ :=
disjoint_of_subset_right (list.subset_cons _ _)
@[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l
| a := (not_mem_nil a).elim
@[simp] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l :=
by simp [disjoint]; refl
@[simp] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l :=
by rw disjoint_comm; simp
@[simp] theorem disjoint_append_left {l₁ l₂ l : list α} :
disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_append_right {l₁ l₂ l : list α} :
disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ :=
disjoint_comm.trans $ by simp [disjoint_append_left]
@[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} :
disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ :=
(@disjoint_append_left _ [a] l₁ l₂).trans $ by simp
@[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} :
disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ :=
disjoint_comm.trans $ by simp [disjoint_cons_left]
theorem disjoint_append_of_disjoint_left {l₁ l₂ l : list α} :
disjoint l₁ l → disjoint l₂ l → disjoint (l₁++l₂) l :=
λ d₁ d₂ x h, or.elim (mem_append.1 h) (@d₁ x) (@d₂ x)
theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l :=
(disjoint_append_left.1 d).1
theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l :=
(disjoint_append_left.1 d).2
theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ :=
(disjoint_append_right.1 d).1
theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ :=
(disjoint_append_right.1 d).2
end disjoint
/- union -/
section union
variable [decidable_eq α]
@[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl
@[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl
@[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ :=
by induction l₁; simp *
theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inl h)
theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inr h)
theorem sublist_suffix_of_union : Π l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂
| [] l₂ := ⟨[], by refl, rfl⟩
| (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
by simp [e.symm]; by_cases a ∈ t ++ l₂ with h;
[existsi t, existsi a::t]; simp [h];
[apply sublist_cons_of_sublist _ s, apply cons_sublist_cons _ s]
theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ :=
exists_imp_exists (λ a, and.right) (sublist_suffix_of_union l₁ l₂)
theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ :=
let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
e ▸ (append_sublist_append_right _).2 s
theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp [or_imp_distrib, forall_and_distrib]
theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x :=
(forall_mem_union.1 h).1
theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x :=
(forall_mem_union.1 h).2
end union
/- inter -/
section inter
variable [decidable_eq α]
@[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl
@[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) :
(a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) :=
if_pos h
@[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) :
(a::l₁) ∩ l₂ = l₁ ∩ l₂ :=
if_neg h
theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ :=
mem_of_mem_filter
theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ :=
of_mem_filter
theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ :=
mem_filter_of_mem
@[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ :=
mem_filter
theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ :=
filter_subset _
theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ :=
λ a, mem_of_mem_inter_right
theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ :=
λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩
theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ :=
by simp [eq_nil_iff_forall_not_mem]; refl
theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x)
(l₂ : list α) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_left) h
theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α}
(h : ∀ x ∈ l₂, p x) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_right) h
end inter
/- pairwise relation (generalized no duplicate) -/
section pairwise
variable (R : α → α → Prop)
inductive pairwise : list α → Prop
| nil : pairwise []
| cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l)
attribute [simp] pairwise.nil
variable {R}
@[simp] theorem pairwise_cons {a : α} {l : list α} :
pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l :=
⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩
theorem rel_of_pairwise_cons {a : α} {l : list α}
(p : pairwise R (a::l)) : ∀ {a'}, a' ∈ l → R a a' :=
(pairwise_cons.1 p).1
theorem pairwise_of_pairwise_cons {a : α} {l : list α}
(p : pairwise R (a::l)) : pairwise R l :=
(pairwise_cons.1 p).2
theorem pairwise.imp {S : α → α → Prop}
(H : ∀ a b, R a b → S a b) {l : list α} (p : pairwise R l) : pairwise S l :=
by induction p with a l r p IH; constructor;
[exact ball.imp_right (λ x _, H _ _) r, exact IH]
theorem pairwise.iff {S : α → α → Prop}
(H : ∀ a b, R a b ↔ S a b) {l : list α} : pairwise R l ↔ pairwise S l :=
⟨pairwise.imp (λ a b, (H a b).1), pairwise.imp (λ a b, (H a b).2)⟩
theorem pairwise_of_forall {l : list α} (H : ∀ x y, R x y) : pairwise R l :=
by induction l; simp *
theorem pairwise.iff_mem {l : list α} :
pairwise R l ↔ pairwise (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l :=
⟨λ p, by induction p with a l r p IH; constructor;
[exact λ b m, ⟨mem_cons_self _ _, mem_cons_of_mem _ m, r b m⟩,
exact IH.imp (λ a b ⟨am, bm, h⟩,
⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)],
pairwise.imp (λ a b h, h.2.2)⟩
theorem pairwise_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → pairwise R l₂ → pairwise R l₁
| ._ ._ sublist.slnil h := h
| ._ ._ (sublist.cons l₁ l₂ a s) (pairwise.cons i n) := pairwise_of_sublist s n
| ._ ._ (sublist.cons2 l₁ l₂ a s) (pairwise.cons i n) :=
(pairwise_of_sublist s n).cons (ball.imp_left (subset_of_sublist s) i)
theorem pairwise_singleton (R) (a : α) : pairwise R [a] :=
by simp
theorem pairwise_pair {a b : α} : pairwise R [a, b] ↔ R a b :=
by simp
theorem pairwise_append {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔
pairwise R l₁ ∧ pairwise R l₂ ∧ ∀ x ∈ l₁, ∀ y ∈ l₂, R x y :=
by induction l₁ with x l₁ IH; simp [or_imp_distrib, forall_and_distrib, *]
theorem pairwise_app_comm (s : symmetric R) {l₁ l₂ : list α} :
pairwise R (l₁++l₂) ↔ pairwise R (l₂++l₁) :=
have ∀ l₁ l₂ : list α,
(∀ (x : α), x ∈ l₁ → ∀ (y : α), y ∈ l₂ → R x y) →
(∀ (x : α), x ∈ l₂ → ∀ (y : α), y ∈ l₁ → R x y),
from λ l₁ l₂ a x xm y ym, s (a y ym x xm),
by simp [pairwise_append]; rw iff.intro (this l₁ l₂) (this l₂ l₁)
theorem pairwise_middle (s : symmetric R) {a : α} {l₁ l₂ : list α} :
pairwise R (l₁ ++ a::l₂) ↔ pairwise R (a::(l₁++l₂)) :=
show pairwise R (l₁ ++ ([a] ++ l₂)) ↔ pairwise R ([a] ++ l₁ ++ l₂),
by rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁),
pairwise_app_comm s]; simp
theorem pairwise_map (f : β → α) :
∀ {l : list β}, pairwise R (map f l) ↔ pairwise (λ a b : β, R (f a) (f b)) l
| [] := by simp
| (b::l) :=
have (∀ a b', f b' = a → b' ∈ l → R (f b) a) ↔ ∀ (b' : β), b' ∈ l → R (f b) (f b'), from
forall_swap.trans $ forall_congr $ by simp,
by simp *; rw this
theorem pairwise_of_pairwise_map {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α}
(p : pairwise S (map f l)) : pairwise R l :=
((pairwise_map f).1 p).imp H
theorem pairwise_map_of_pairwise {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α}
(p : pairwise R l) : pairwise S (map f l) :=
(pairwise_map f).2 $ p.imp H
theorem pairwise_filter_map (f : β → option α) {l : list β} :
pairwise R (filter_map f l) ↔ pairwise (λ a a' : β, ∀ (b ∈ f a) (b' ∈ f a'), R b b') l :=
let S (a a' : β) := ∀ (b ∈ f a) (b' ∈ f a'), R b b' in
begin
simp, induction l with a l IH; simp,
cases e : f a with b; simp [e, IH],
{ show pairwise S l ↔ pairwise S l ∧ ∀ (a' : β), a' ∈ l →
∀ (b : α), none = some b → ∀ (b' : α), f a' = some b' → R b b',
refine (and_iff_left _).symm, intros, contradiction },
{ rw [filter_map_cons_some _ _ _ e], simp [IH],
show (∀ (a' : α) (x : β), f x = some a' → x ∈ l → R b a') ∧ pairwise S l ↔
(∀ (a' : β), a' ∈ l → ∀ (b' : α), f a' = some b' → R b b') ∧ pairwise S l,
from and_congr ⟨λ h b mb a ma, h a b ma mb, λ h a b ma mb, h b mb a ma⟩ iff.rfl }
end
theorem pairwise_filter_map_of_pairwise {S : β → β → Prop} (f : α → option β)
(H : ∀ (a a' : α), R a a' → ∀ (b ∈ f a) (b' ∈ f a'), S b b') {l : list α}
(p : pairwise R l) : pairwise S (filter_map f l) :=
(pairwise_filter_map _).2 $ p.imp H
theorem pairwise_filter (p : α → Prop) [decidable_pred p] {l : list α} :
pairwise R (filter p l) ↔ pairwise (λ x y, p x → p y → R x y) l :=
begin
rw [← filter_map_eq_filter, pairwise_filter_map],
apply pairwise.iff, intros b c, simp,
have : (∀ (b' : α), p b → b = b' → ∀ (c' : α), p c → c = c' → R b' c') ↔
∀ (b' : α), b = b' → p b → ∀ (c' : α), c = c' → p c → R b' c' :=
⟨λ h a b c d e f, h a c b d f e, λ h a c b d f e, h a b c d e f⟩,
simp [this]
end
theorem pairwise_filter_of_pairwise (p : α → Prop) [decidable_pred p] {l : list α}
: pairwise R l → pairwise R (filter p l) :=
pairwise_of_sublist (filter_sublist _)
theorem pairwise_join {L : list (list α)} : pairwise R (join L) ↔
(∀ l ∈ L, pairwise R l) ∧ pairwise (λ l₁ l₂, ∀ (x ∈ l₁) (y ∈ l₂), R x y) L :=
begin
induction L with l L IH, {simp},
have : (∀ (x : α), x ∈ l → ∀ (y : α) (x_1 : list α), y ∈ x_1 → x_1 ∈ L → R x y) ↔
∀ (a' : list α), a' ∈ L → ∀ (x : α), x ∈ l → ∀ (y : α), y ∈ a' → R x y :=
⟨λ h a b c d e f, h c d e a f b, λ h c d e a f b, h a b c d e f⟩,
simp [pairwise_append, IH, this]
end
@[simp] theorem pairwise_reverse : ∀ {R} {l : list α},
pairwise R (reverse l) ↔ pairwise (λ x y, R y x) l :=
suffices ∀ {R l}, @pairwise α R l → pairwise (λ x y, R y x) (reverse l),
from λ R l, ⟨λ p, reverse_reverse l ▸ this p, this⟩,
λ R l p, by induction p with a l h p IH;
[simp, simpa [pairwise_append, IH] using h]
variable [decidable_rel R]
instance decidable_pairwise (l : list α) : decidable (pairwise R l) :=
by induction l; simp; apply_instance
/- pairwise reduct -/
def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α
| [] := []
| (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH
@[simp] theorem pw_filter_nil : pw_filter R [] = [] := rfl
@[simp] theorem pw_filter_cons_of_pos {a : α} {l : list α} (h : ∀ b ∈ pw_filter R l, R a b) :
pw_filter R (a::l) = a :: pw_filter R l := if_pos h
@[simp] theorem pw_filter_cons_of_neg {a : α} {l : list α} (h : ¬ ∀ b ∈ pw_filter R l, R a b) :
pw_filter R (a::l) = pw_filter R l := if_neg h
theorem pw_filter_sublist : ∀ (l : list α), pw_filter R l <+ l
| [] := nil_sublist _
| (x::l) := begin
by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h,
{ rw [pw_filter_cons_of_pos h],
exact cons_sublist_cons _ (pw_filter_sublist l) },
{ rw [pw_filter_cons_of_neg h],
exact sublist_cons_of_sublist _ (pw_filter_sublist l) },
end
theorem pw_filter_subset (l : list α) : pw_filter R l ⊆ l :=
subset_of_sublist (pw_filter_sublist _)
theorem pairwise_pw_filter : ∀ (l : list α), pairwise R (pw_filter R l)
| [] := pairwise.nil _
| (x::l) := begin
by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h,
{ rw [pw_filter_cons_of_pos h],
exact pairwise_cons.2 ⟨h, pairwise_pw_filter l⟩ },
{ rw [pw_filter_cons_of_neg h],
exact pairwise_pw_filter l },
end
theorem pw_filter_eq_self {l : list α} : pw_filter R l = l ↔ pairwise R l :=
⟨λ e, e ▸ pairwise_pw_filter l, λ p, begin
induction l with x l IH, {simp},
cases pairwise_cons.1 p with al p,
rw [pw_filter_cons_of_pos (ball.imp_left (pw_filter_subset l) al), IH p],
end⟩
theorem forall_mem_pw_filter (neg_trans : ∀ {x y z}, R x z → R x y ∨ R y z)
(a : α) (l : list α) : (∀ b ∈ pw_filter R l, R a b) ↔ (∀ b ∈ l, R a b) :=
⟨begin
induction l with x l IH; simp *,
by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h,
{ simp [pw_filter_cons_of_pos h],
exact λ r H, ⟨r, IH H⟩ },
{ rw [pw_filter_cons_of_neg h],
refine λ H, ⟨_, IH H⟩,
cases e : find (λ y, ¬ R x y) (pw_filter R l) with k,
{ exact h.elim (ball.imp_right (λ_ _, not_not.1) (find_eq_none.1 e)) },
{ have := find_some e,
exact (neg_trans (H k (find_mem e))).resolve_right this } }
end, ball.imp_left (pw_filter_subset l)⟩
end pairwise
/- chain relation (conjunction of R a b ∧ R b c ∧ R c d ...) -/
section chain
variable (R : α → α → Prop)
inductive chain : α → list α → Prop
| nil (a : α) : chain a []
| cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l)
attribute [simp] chain.nil
variable {R}
@[simp] theorem chain_cons {a b : α} {l : list α} :
chain R a (b::l) ↔ R a b ∧ chain R b l :=
⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩
theorem rel_of_chain_cons {a b : α} {l : list α}
(p : chain R a (b::l)) : R a b :=
(chain_cons.1 p).1
theorem chain_of_chain_cons {a b : α} {l : list α}
(p : chain R a (b::l)) : chain R b l :=
(chain_cons.1 p).2
theorem chain.imp {S : α → α → Prop}
(H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l :=
by induction p with _ a b l r p IH; constructor;
[exact H _ _ r, exact IH]
theorem chain.iff {S : α → α → Prop}
(H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l :=
⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩
theorem chain.iff_mem {S : α → α → Prop} {a : α} {l : list α} :
chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l :=
⟨λ p, by induction p with _ a b l r p IH; constructor;
[exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩,
exact IH.imp (λ a b ⟨am, bm, h⟩,
⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)],
chain.imp (λ a b h, h.2.2)⟩
theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b :=
by simp
theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁++b::l₂) ↔
chain R a (l₁++[b]) ∧ chain R b l₂ :=
by induction l₁ with x l₁ IH generalizing a; simp *
theorem chain_map (f : β → α) {b : β} {l : list β} :
chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l :=
by induction l generalizing b; simp *
theorem chain_of_chain_map {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α}
(p : chain S (f a) (map f l)) : chain R a l :=
((chain_map f).1 p).imp H
theorem chain_map_of_chain {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α}
(p : chain R a l) : chain S (f a) (map f l) :=
(chain_map f).2 $ p.imp H
theorem chain_of_pairwise {a : α} {l : list α} (p : pairwise R (a::l)) : chain R a l :=
begin
cases pairwise_cons.1 p with r p', clear p,
induction p' with b l r' p IH generalizing a; simp,
simp at r, simp [r],
show chain R b l, from IH r'
end
theorem chain_iff_pairwise (tr : transitive R) {a : α} {l : list α} :
chain R a l ↔ pairwise R (a::l) :=
⟨λ c, begin
induction c with b b c l r p IH, {simp},
apply IH.cons _, simp [r],
show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)),
end, chain_of_pairwise⟩
instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) :=
by induction l generalizing a; simp; apply_instance
end chain
/- no duplicates predicate -/
def nodup : list α → Prop := pairwise (≠)
section nodup
@[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l :=
⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩
@[simp] theorem nodup_nil : @nodup α [] := pairwise.nil _
@[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l :=
by simp [nodup]
theorem nodup_cons_of_nodup {a : α} {l : list α} (m : a ∉ l) (n : nodup l) : nodup (a::l) :=
nodup_cons.2 ⟨m, n⟩
theorem nodup_singleton (a : α) : nodup [a] :=
nodup_cons_of_nodup (not_mem_nil a) nodup_nil
theorem nodup_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : nodup l :=
(nodup_cons.1 h).2
theorem not_mem_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : a ∉ l :=
(nodup_cons.1 h).1
theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) :=
imp_not_comm.1 not_mem_of_nodup_cons
theorem nodup_of_sublist {l₁ l₂ : list α} : l₁ <+ l₂ → nodup l₂ → nodup l₁ :=
pairwise_of_sublist
theorem not_nodup_pair (a : α) : ¬ nodup [a, a] :=
not_nodup_cons_of_mem $ mem_singleton_self _
theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l :=
⟨λ d a h, not_nodup_pair a (nodup_of_sublist h d), begin
induction l with a l IH; intro h, {simp},
exact nodup_cons_of_nodup
(λ al, h a $ cons_sublist_cons _ $ singleton_sublist.2 al)
(IH $ λ a s, h a $ sublist_cons_of_sublist _ s)
end⟩
theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 :=
nodup_iff_sublist.trans $ forall_congr $ λ a,
have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_repeat_sublist _ _ a l 2).symm,
(not_congr this).trans not_lt
@[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α}
(d : nodup l) (h : a ∈ l) : count a l = 1 :=
le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos_of_mem h)
theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ :=
nodup_of_sublist (sublist_append_left l₁ l₂)
theorem nodup_of_nodup_append_right {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₂ :=
nodup_of_sublist (sublist_append_right l₁ l₂)
theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ :=
by simp [nodup, pairwise_append, disjoint_iff_ne]
theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ :=
(nodup_append.1 d).2.2
theorem nodup_append_of_nodup {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁++l₂) :=
nodup_append.2 ⟨d₁, d₂, dj⟩
theorem nodup_app_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) :=
by simp [nodup_append]
theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) :=
by simp [nodup_append, not_or_distrib]
theorem nodup_of_nodup_map (f : α → β) {l : list α} : nodup (map f l) → nodup l :=
pairwise_of_pairwise_map f $ λ a b, mt $ congr_arg f
theorem nodup_map_on {f : α → β} {l : list α} (H : ∀x∈l, ∀y∈l, f x = f y → x = y)
(d : nodup l) : nodup (map f l) :=
pairwise_map_of_pairwise _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.iff_mem.1 d)
theorem nodup_map {f : α → β} {l : list α} (hf : injective f) (h : nodup l) : nodup (map f l) :=
nodup_map_on (assume x _ y _ h, hf h) h
theorem nodup_filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) :=
pairwise_filter_of_pairwise p
@[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l :=
pairwise_reverse.trans $ by simp [nodup, eq_comm]
instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) :=
list.decidable_pairwise
theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {l} (d : nodup l) : l.erase a = filter (≠ a) l :=
begin
induction d with b l m d IH; simp [list.erase, list.filter],
by_cases b = a; simp *, subst b,
show l = filter (λ a', ¬ a' = a) l, rw filter_eq_self.2,
simpa only [eq_comm] using m
end
theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) :=
nodup_of_sublist (erase_sublist _ _)
theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) :
a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l :=
by rw nodup_erase_eq_filter b d; simp
theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a :=
by rw mem_erase_iff_of_nodup h; simp
theorem nodup_join {L : list (list α)} : nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L :=
by simp [nodup, pairwise_join, disjoint_left.symm]
theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔
(∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ :=
by simp [bind, nodup_join, pairwise_map];
rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔
(∀ (x : α), x ∈ l₁ → nodup (f x)),
from forall_swap.trans $ forall_congr $ λ_, by simp]
theorem nodup_product {l₁ : list α} {l₂ : list β} (d₁ : nodup l₁) (d₂ : nodup l₂) :
nodup (product l₁ l₂) :=
nodup_bind.2
⟨λ a ma, nodup_map (injective_of_left_inverse (λ b, (rfl : (a,b).2 = b))) d₂,
d₁.imp (λ a₁ a₂ n x,
suffices ∀ (b₁ : β), b₁ ∈ l₂ → (a₁, b₁) = x → ∀ (b₂ : β), b₂ ∈ l₂ → (a₂, b₂) ≠ x, by simpa,
λ b₁ mb₁ e b₂ mb₂ e', by subst e'; injection e; contradiction)⟩
theorem nodup_filter_map {f : α → option β} (pdi : true) {l : list α}
(H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') :
nodup l → nodup (filter_map f l) :=
pairwise_filter_map_of_pairwise f $ λ a a' n b bm b' bm' e, n $ H a a' b' (e ▸ bm) bm'
theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) :=
by simp; exact nodup_append_of_nodup h' (nodup_singleton _) (disjoint_singleton.2 h)
theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) :=
by by_cases a ∈ l with h'; simp [h', h]; apply nodup_cons h' h
theorem nodup_union [decidable_eq α] (l₁ : list α) {l₂ : list α} (h : nodup l₂) :
nodup (l₁ ∪ l₂) :=
begin
induction l₁ with a l₁ ih generalizing l₂,
{ exact h },
simp,
apply nodup_insert,
exact ih h
end
theorem nodup_inter_of_nodup [decidable_eq α] {l₁ : list α} (l₂) : nodup l₁ → nodup (l₁ ∩ l₂) :=
nodup_filter _
end nodup
/- erase duplicates function -/
section erase_dup
variable [decidable_eq α]
def erase_dup : list α → list α := pw_filter (≠)
@[simp] theorem erase_dup_nil : erase_dup [] = ([] : list α) := rfl
theorem erase_dup_cons_of_mem' {a : α} {l : list α} (h : a ∈ erase_dup l) :
erase_dup (a::l) = erase_dup l :=
pw_filter_cons_of_neg $ by simpa using h
theorem erase_dup_cons_of_not_mem' {a : α} {l : list α} (h : a ∉ erase_dup l) :
erase_dup (a::l) = a :: erase_dup l :=
pw_filter_cons_of_pos $ by simpa using h
@[simp] theorem mem_erase_dup {a : α} {l : list α} : a ∈ erase_dup l ↔ a ∈ l :=
by simpa using not_congr (@forall_mem_pw_filter α (≠) _
(λ x y z xz, not_and_distrib.1 $ mt (and.rec eq.trans) xz) a l)
@[simp] theorem erase_dup_cons_of_mem {a : α} {l : list α} (h : a ∈ l) :
erase_dup (a::l) = erase_dup l :=
erase_dup_cons_of_mem' $ mem_erase_dup.2 h
@[simp] theorem erase_dup_cons_of_not_mem {a : α} {l : list α} (h : a ∉ l) :
erase_dup (a::l) = a :: erase_dup l :=
erase_dup_cons_of_not_mem' $ mt mem_erase_dup.1 h
theorem erase_dup_sublist : ∀ (l : list α), erase_dup l <+ l := pw_filter_sublist
theorem erase_dup_subset : ∀ (l : list α), erase_dup l ⊆ l := pw_filter_subset
theorem subset_erase_dup (l : list α) : l ⊆ erase_dup l :=
λ a, mem_erase_dup.2
theorem nodup_erase_dup : ∀ l : list α, nodup (erase_dup l) := pairwise_pw_filter
theorem erase_dup_eq_self {l : list α} : erase_dup l = l ↔ nodup l := pw_filter_eq_self
theorem erase_dup_append {l₁ l₂ : list α} : erase_dup (l₁ ++ l₂) = l₁ ∪ erase_dup l₂ :=
begin
induction l₁ with a l₁ IH; simp, rw ← IH,
show erase_dup (a :: (l₁ ++ l₂)) = insert a (erase_dup (l₁ ++ l₂)),
by_cases a ∈ erase_dup (l₁ ++ l₂);
[ rw [erase_dup_cons_of_mem' h, insert_of_mem h],
rw [erase_dup_cons_of_not_mem' h, insert_of_not_mem h]]
end
end erase_dup
/- iota and range -/
@[simp] def range' : ℕ → ℕ → list ℕ
| s 0 := []
| s (n+1) := s :: range' (s+1) n
@[simp] theorem length_range' : ∀ (s n : ℕ), length (range' s n) = n
| s 0 := rfl
| s (n+1) := congr_arg succ (length_range' _ _)
@[simp] theorem mem_range' {m : ℕ} : ∀ {s n : ℕ}, m ∈ range' s n ↔ s ≤ m ∧ m < s + n
| s 0 := by simp
| s (n+1) :=
have m = s → m < s + (n + 1),
from λ e, e ▸ lt_succ_of_le (le_add_right _ _),
have l : m = s ∨ s + 1 ≤ m ↔ s ≤ m,
by simpa [eq_comm] using (@le_iff_eq_or_lt _ _ s m).symm,
by simp [@mem_range' (s+1) n, or_and_distrib_left, or_iff_right_of_imp this, l]
theorem chain_succ_range' : ∀ s n : ℕ, chain (λ a b, b = succ a) s (range' (s+1) n)
| s 0 := chain.nil _ _
| s (n+1) := (chain_succ_range' (s+1) n).cons rfl
theorem chain_lt_range' (s n : ℕ) : chain (<) s (range' (s+1) n) :=
(chain_succ_range' s n).imp (λ a b e, e.symm ▸ lt_succ_self _)
theorem pairwise_lt_range' : ∀ s n : ℕ, pairwise (<) (range' s n)
| s 0 := pairwise.nil _
| s (n+1) := (chain_iff_pairwise (by exact λ a b c, lt_trans)).1 (chain_lt_range' s n)
theorem nodup_range' (s n : ℕ) : nodup (range' s n) :=
(pairwise_lt_range' s n).imp (λ a b, ne_of_lt)
theorem range'_append : ∀ s m n : ℕ, range' s m ++ range' (s+m) n = range' s (n+m)
| s 0 n := rfl
| s (m+1) n := show s :: (range' (s+1) m ++ range' (s+m+1) n) = s :: range' (s+1) (n+m),
by rw [add_right_comm, range'_append]
theorem range'_sublist_right {s m n : ℕ} : range' s m <+ range' s n ↔ m ≤ n :=
⟨λ h, by simpa using length_le_of_sublist h,
λ h, by rw [← nat.sub_add_cancel h, ← range'_append]; apply sublist_append_left⟩
theorem range'_subset_right {s m n : ℕ} : range' s m ⊆ range' s n ↔ m ≤ n :=
⟨λ h, le_of_not_lt $ λ hn, lt_irrefl (s+n) $
(mem_range'.1 $ h $ mem_range'.2 ⟨le_add_right _ _, nat.add_lt_add_left hn s⟩).2,
λ h, subset_of_sublist (range'_sublist_right.2 h)⟩
theorem range'_concat (s n : ℕ) : range' s (n + 1) = range' s n ++ [s+n] :=
by rw add_comm n 1; exact (range'_append s n 1).symm
theorem range_core_range' : ∀ s n : ℕ, range_core s (range' s n) = range' 0 (n + s)
| 0 n := rfl
| (s+1) n := by rw [show n+(s+1) = n+1+s, by simp]; exact range_core_range' s (n+1)
theorem range_eq_range' (n : ℕ) : range n = range' 0 n :=
(range_core_range' n 0).trans $ by rw zero_add
@[simp] theorem length_range (n : ℕ) : length (range n) = n :=
by simp [range_eq_range']
theorem pairwise_lt_range (n : ℕ) : pairwise (<) (range n) :=
by simp [range_eq_range', pairwise_lt_range']
theorem nodup_range (n : ℕ) : nodup (range n) :=
by simp [range_eq_range', nodup_range']
theorem range_sublist {m n : ℕ} : range m <+ range n ↔ m ≤ n :=
by simp [range_eq_range', range'_sublist_right]
theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n :=
by simp [range_eq_range', range'_subset_right]
@[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n :=
by simp [range_eq_range', zero_le]
@[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n :=
mt mem_range.1 $ lt_irrefl _
theorem iota_eq_reverse_range' : ∀ n : ℕ, iota n = reverse (range' 1 n)
| 0 := rfl
| (n+1) := by simp [iota, range'_concat, iota_eq_reverse_range' n]
@[simp] theorem length_iota (n : ℕ) : length (iota n) = n :=
by simp [iota_eq_reverse_range']
theorem pairwise_gt_iota (n : ℕ) : pairwise (>) (iota n) :=
by simp [iota_eq_reverse_range', pairwise_lt_range']
theorem nodup_iota (n : ℕ) : nodup (iota n) :=
by simp [iota_eq_reverse_range', nodup_range']
theorem mem_iota {m n : ℕ} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n :=
by simp [iota_eq_reverse_range', lt_succ_iff]
end list
|
addd6a1c08a24e2db694fb582be4455fb6e2e6f6
|
2c096fdfecf64e46ea7bc6ce5521f142b5926864
|
/src/Lean/Server/FileWorker/RequestHandling.lean
|
f30cc076b401791be8926d0559674fc2d998c5d5
|
[
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"
] |
permissive
|
Kha/lean4
|
1005785d2c8797ae266a303968848e5f6ce2fe87
|
b99e11346948023cd6c29d248cd8f3e3fb3474cf
|
refs/heads/master
| 1,693,355,498,027
| 1,669,080,461,000
| 1,669,113,138,000
| 184,748,176
| 0
| 0
|
Apache-2.0
| 1,665,995,520,000
| 1,556,884,930,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 25,464
|
lean
|
/-
Copyright (c) 2021 Wojciech Nawrocki. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Wojciech Nawrocki, Marc Huisinga
-/
import Lean.DeclarationRange
import Lean.Data.Json
import Lean.Data.Lsp
import Lean.Server.FileWorker.Utils
import Lean.Server.Requests
import Lean.Server.Completion
import Lean.Server.References
import Lean.Server.GoTo
import Lean.Widget.InteractiveGoal
import Lean.Widget.Diff
namespace Lean.Server.FileWorker
open Lsp
open RequestM
open Snapshots
def handleCompletion (p : CompletionParams)
: RequestM (RequestTask CompletionList) := do
let doc ← readDoc
let text := doc.meta.text
let pos := text.lspPosToUtf8Pos p.position
let caps := (← read).initParams.capabilities
-- dbg_trace ">> handleCompletion invoked {pos}"
-- NOTE: use `+ 1` since we sometimes want to consider invalid input technically after the command,
-- such as a trailing dot after an option name. This shouldn't be a problem since any subsequent
-- command starts with a keyword that (currently?) does not participate in completion.
withWaitFindSnap doc (·.endPos + ' ' >= pos)
(notFoundX := pure { items := #[], isIncomplete := true }) fun snap => do
if let some r ← Completion.find? doc.meta.text pos snap.infoTree caps then
return r
return { items := #[ ], isIncomplete := true }
open Elab in
def handleHover (p : HoverParams)
: RequestM (RequestTask (Option Hover)) := do
let doc ← readDoc
let text := doc.meta.text
let mkHover (s : String) (r : String.Range) : Hover := {
contents := {
kind := MarkupKind.markdown
value := s
}
range? := r.toLspRange text
}
let hoverPos := text.lspPosToUtf8Pos p.position
withWaitFindSnap doc (fun s => s.endPos > hoverPos)
(notFoundX := pure none) fun snap => do
-- try to find parser docstring from syntax tree
let stack? := snap.stx.findStack? (·.getRange?.any (·.contains hoverPos))
let stxDoc? ← match stack? with
| some stack => stack.findSomeM? fun (stx, _) => do
return (← findDocString? snap.env stx.getKind).map (·, stx.getRange?.get!)
| none => pure none
-- now try info tree
if let some (ci, i) := snap.infoTree.hoverableInfoAt? hoverPos then
if let some range := i.range? then
-- prefer info tree if at least as specific as parser docstring
if stxDoc?.all fun (_, stxRange) => stxRange.includes range then
if let some hoverFmt ← i.fmtHover? ci then
return mkHover (toString hoverFmt) range
if let some (doc, range) := stxDoc? then
return mkHover doc range
return none
open Elab GoToKind in
def locationLinksOfInfo (kind : GoToKind) (ci : Elab.ContextInfo) (i : Elab.Info)
(infoTree? : Option InfoTree := none) : RequestM (Array LocationLink) := do
let rc ← read
let doc ← readDoc
let text := doc.meta.text
let locationLinksFromDecl (i : Elab.Info) (n : Name) :=
locationLinksFromDecl rc.srcSearchPath doc.meta.uri n <| (·.toLspRange text) <$> i.range?
let locationLinksFromBinder (i : Elab.Info) (id : FVarId) := do
if let some i' := infoTree? >>= InfoTree.findInfo? fun
| Info.ofTermInfo { isBinder := true, expr := Expr.fvar id' .., .. } => id' == id
| _ => false then
if let some r := i'.range? then
let r := r.toLspRange text
let ll : LocationLink := {
originSelectionRange? := (·.toLspRange text) <$> i.range?
targetUri := doc.meta.uri
targetRange := r
targetSelectionRange := r
}
return #[ll]
return #[]
let locationLinksFromImport (i : Elab.Info) := do
let name := i.stx[2].getId
if let some modUri ← documentUriFromModule rc.srcSearchPath name then
let range := { start := ⟨0, 0⟩, «end» := ⟨0, 0⟩ : Range }
let ll : LocationLink := {
originSelectionRange? := (·.toLspRange text) <$> i.stx[2].getRange? (canonicalOnly := true)
targetUri := modUri
targetRange := range
targetSelectionRange := range
}
return #[ll]
return #[]
match i with
| .ofTermInfo ti =>
let mut expr := ti.expr
if kind == type then
expr ← ci.runMetaM i.lctx do
return Expr.getAppFn (← instantiateMVars (← Meta.inferType expr))
match expr with
| Expr.const n .. => return ← ci.runMetaM i.lctx <| locationLinksFromDecl i n
| Expr.fvar id .. => return ← ci.runMetaM i.lctx <| locationLinksFromBinder i id
| _ => pure ()
| .ofFieldInfo fi =>
if kind == type then
let expr ← ci.runMetaM i.lctx do
instantiateMVars (← Meta.inferType fi.val)
if let some n := expr.getAppFn.constName? then
return ← ci.runMetaM i.lctx <| locationLinksFromDecl i n
else
return ← ci.runMetaM i.lctx <| locationLinksFromDecl i fi.projName
| .ofOptionInfo oi =>
return ← ci.runMetaM i.lctx <| locationLinksFromDecl i oi.declName
| .ofCommandInfo ⟨`import, _⟩ =>
if kind == definition || kind == declaration then
return ← ci.runMetaM i.lctx <| locationLinksFromImport i
| _ => pure ()
-- If other go-tos fail, we try to show the elaborator or parser
if let some ei := i.toElabInfo? then
if kind == declaration && ci.env.contains ei.stx.getKind then
return ← ci.runMetaM i.lctx <| locationLinksFromDecl i ei.stx.getKind
if kind == definition && ci.env.contains ei.elaborator then
return ← ci.runMetaM i.lctx <| locationLinksFromDecl i ei.elaborator
return #[]
open Elab GoToKind in
def handleDefinition (kind : GoToKind) (p : TextDocumentPositionParams)
: RequestM (RequestTask (Array LocationLink)) := do
let doc ← readDoc
let text := doc.meta.text
let hoverPos := text.lspPosToUtf8Pos p.position
withWaitFindSnap doc (fun s => s.endPos > hoverPos)
(notFoundX := pure #[]) fun snap => do
if let some (ci, i) := snap.infoTree.hoverableInfoAt? (includeStop := true /- #767 -/) hoverPos then
locationLinksOfInfo kind ci i snap.infoTree
else return #[]
open RequestM in
def getInteractiveGoals (p : Lsp.PlainGoalParams) : RequestM (RequestTask (Option Widget.InteractiveGoals)) := do
let doc ← readDoc
let text := doc.meta.text
let hoverPos := text.lspPosToUtf8Pos p.position
-- NOTE: use `>=` since the cursor can be *after* the input
withWaitFindSnap doc (fun s => s.endPos >= hoverPos)
(notFoundX := return none) fun snap => do
if let rs@(_ :: _) := snap.infoTree.goalsAt? doc.meta.text hoverPos then
let goals : List Widget.InteractiveGoals ← rs.mapM fun { ctxInfo := ci, tacticInfo := ti, useAfter := useAfter, .. } => do
let ciAfter := { ci with mctx := ti.mctxAfter }
let ci := if useAfter then ciAfter else { ci with mctx := ti.mctxBefore }
-- compute the interactive goals
let goals ← ci.runMetaM {} (do
let goals := List.toArray <| if useAfter then ti.goalsAfter else ti.goalsBefore
let goals ← goals.mapM Widget.goalToInteractive
return {goals}
)
-- compute the goal diff
let goals ← ciAfter.runMetaM {} (do
try
Widget.diffInteractiveGoals useAfter ti goals
catch _ =>
-- fail silently, since this is just a bonus feature
return goals
)
return goals
return some <| goals.foldl (· ++ ·) ∅
else
return none
open Elab in
def handlePlainGoal (p : PlainGoalParams)
: RequestM (RequestTask (Option PlainGoal)) := do
let t ← getInteractiveGoals p
return t.map <| Except.map <| Option.map <| fun {goals, ..} =>
if goals.isEmpty then
{ goals := #[], rendered := "no goals" }
else
let goalStrs := goals.map (toString ·.pretty)
let goalBlocks := goalStrs.map fun goal => s!"```lean
{goal}
```"
let md := String.intercalate "\n---\n" goalBlocks.toList
{ goals := goalStrs, rendered := md }
def getInteractiveTermGoal (p : Lsp.PlainTermGoalParams)
: RequestM (RequestTask (Option Widget.InteractiveTermGoal)) := do
let doc ← readDoc
let text := doc.meta.text
let hoverPos := text.lspPosToUtf8Pos p.position
withWaitFindSnap doc (fun s => s.endPos > hoverPos)
(notFoundX := pure none) fun snap => do
if let some (ci, i@(Elab.Info.ofTermInfo ti)) := snap.infoTree.termGoalAt? hoverPos then
let ty ← ci.runMetaM i.lctx do
instantiateMVars <| ti.expectedType?.getD (← Meta.inferType ti.expr)
-- for binders, hide the last hypothesis (the binder itself)
let lctx' := if ti.isBinder then i.lctx.pop else i.lctx
let goal ← ci.runMetaM lctx' do
Widget.goalToInteractive (← Meta.mkFreshExprMVar ty).mvarId!
let range := if let some r := i.range? then r.toLspRange text else ⟨p.position, p.position⟩
return some { goal with range }
else
return none
def handlePlainTermGoal (p : PlainTermGoalParams)
: RequestM (RequestTask (Option PlainTermGoal)) := do
let t ← getInteractiveTermGoal p
return t.map <| Except.map <| Option.map fun goal =>
{ goal := toString goal.toInteractiveGoal.pretty
range := goal.range
}
partial def handleDocumentHighlight (p : DocumentHighlightParams)
: RequestM (RequestTask (Array DocumentHighlight)) := do
let doc ← readDoc
let text := doc.meta.text
let pos := text.lspPosToUtf8Pos p.position
let rec highlightReturn? (doRange? : Option Range) : Syntax → Option DocumentHighlight
| `(doElem|return%$i $e) => Id.run do
if let some range := i.getRange? then
if range.contains pos then
return some { range := doRange?.getD (range.toLspRange text), kind? := DocumentHighlightKind.text }
highlightReturn? doRange? e
| `(do%$i $elems) => highlightReturn? (i.getRange?.get!.toLspRange text) elems
| stx => stx.getArgs.findSome? (highlightReturn? doRange?)
let highlightRefs? (snaps : Array Snapshot) : Option (Array DocumentHighlight) := Id.run do
let trees := snaps.map (·.infoTree)
let refs : Lsp.ModuleRefs := findModuleRefs text trees
let mut ranges := #[]
for ident in ← refs.findAt p.position do
if let some info ← refs.find? ident then
if let some definition := info.definition then
ranges := ranges.push definition
ranges := ranges.append info.usages
if ranges.isEmpty then
return none
some <| ranges.map ({ range := ·, kind? := DocumentHighlightKind.text })
withWaitFindSnap doc (fun s => s.endPos > pos)
(notFoundX := pure #[]) fun snap => do
let (snaps, _) ← doc.cmdSnaps.getFinishedPrefix
if let some his := highlightRefs? snaps.toArray then
return his
if let some hi := highlightReturn? none snap.stx then
return #[hi]
return #[]
structure NamespaceEntry where
/-- The list of the name components introduced by this namespace command,
in reverse order so that `end` will peel them off from the front. -/
name : List Name
stx : Syntax
selection : Syntax
prevSiblings : Array DocumentSymbol
def NamespaceEntry.finish (text : FileMap) (syms : Array DocumentSymbol) (endStx : Option Syntax) :
NamespaceEntry → Array DocumentSymbol
| { name, stx, selection, prevSiblings, .. } =>
-- we can assume that commands always have at least one position (see `parseCommand`)
let range := match endStx with
| some endStx => (mkNullNode #[stx, endStx]).getRange?.get!
| none => { stx.getRange?.get! with stop := text.source.endPos }
let name := name.foldr (fun x y => y ++ x) Name.anonymous
prevSiblings.push <| DocumentSymbol.mk {
-- anonymous sections are represented by `«»` name components
name := if name == `«» then "<section>" else name.toString
kind := .namespace
range := range.toLspRange text
selectionRange := selection.getRange?.getD range |>.toLspRange text
children? := syms
}
open Parser.Command in
partial def handleDocumentSymbol (_ : DocumentSymbolParams)
: RequestM (RequestTask DocumentSymbolResult) := do
let doc ← readDoc
-- bad: we have to wait on elaboration of the entire file before we can report document symbols
let t := doc.cmdSnaps.waitAll
mapTask t fun (snaps, _) => do
let mut stxs := snaps.map (·.stx)
return { syms := toDocumentSymbols doc.meta.text stxs #[] [] }
where
toDocumentSymbols (text : FileMap) (stxs : List Syntax)
(syms : Array DocumentSymbol) (stack : List NamespaceEntry) :
Array DocumentSymbol :=
match stxs with
| [] => stack.foldl (fun syms entry => entry.finish text syms none) syms
| stx::stxs => match stx with
| `(namespace $id) =>
let entry := { name := id.getId.componentsRev, stx, selection := id, prevSiblings := syms }
toDocumentSymbols text stxs #[] (entry :: stack)
| `(section $(id)?) =>
let name := id.map (·.getId.componentsRev) |>.getD [`«»]
let entry := { name, stx, selection := id.map (·.raw) |>.getD stx, prevSiblings := syms }
toDocumentSymbols text stxs #[] (entry :: stack)
| `(end $(id)?) =>
let rec popStack n syms
| [] => toDocumentSymbols text stxs syms []
| entry :: stack =>
if entry.name.length == n then
let syms := entry.finish text syms stx
toDocumentSymbols text stxs syms stack
else if entry.name.length > n then
let syms := { entry with name := entry.name.take n, prevSiblings := #[] }.finish text syms stx
toDocumentSymbols text stxs syms ({ entry with name := entry.name.drop n } :: stack)
else
let syms := entry.finish text syms stx
popStack (n - entry.name.length) syms stack
popStack (id.map (·.getId.getNumParts) |>.getD 1) syms stack
| _ => Id.run do
unless stx.isOfKind ``Lean.Parser.Command.declaration do
return toDocumentSymbols text stxs syms stack
if let some stxRange := stx.getRange? then
let (name, selection) := match stx with
| `($_:declModifiers $_:attrKind instance $[$np:namedPrio]? $[$id$[.{$ls,*}]?]? $sig:declSig $_) =>
((·.getId.toString) <$> id |>.getD s!"instance {sig.raw.reprint.getD ""}", id.map (·.raw) |>.getD sig)
| _ =>
match stx.getArg 1 |>.getArg 1 with
| `(declId|$id$[.{$ls,*}]?) => (id.raw.getId.toString, id)
| _ =>
let stx10 : Syntax := (stx.getArg 1).getArg 0 -- TODO: stx[1][0] times out
(stx10.isIdOrAtom?.getD "<unknown>", stx10)
if let some selRange := selection.getRange? then
let sym := DocumentSymbol.mk {
name := name
kind := SymbolKind.method
range := stxRange.toLspRange text
selectionRange := selRange.toLspRange text
}
return toDocumentSymbols text stxs (syms.push sym) stack
toDocumentSymbols text stxs syms stack
def noHighlightKinds : Array SyntaxNodeKind := #[
-- usually have special highlighting by the client
``Lean.Parser.Term.sorry,
``Lean.Parser.Term.type,
``Lean.Parser.Term.prop,
-- not really keywords
`antiquotName,
``Lean.Parser.Command.docComment,
``Lean.Parser.Command.moduleDoc]
structure SemanticTokensContext where
beginPos : String.Pos
endPos : String.Pos
text : FileMap
snap : Snapshot
structure SemanticTokensState where
data : Array Nat
lastLspPos : Lsp.Position
partial def handleSemanticTokens (beginPos endPos : String.Pos)
: RequestM (RequestTask SemanticTokens) := do
let doc ← readDoc
let text := doc.meta.text
let t := doc.cmdSnaps.waitAll (·.beginPos < endPos)
mapTask t fun (snaps, _) =>
StateT.run' (s := { data := #[], lastLspPos := ⟨0, 0⟩ : SemanticTokensState }) do
for s in snaps do
if s.endPos <= beginPos then
continue
ReaderT.run (r := SemanticTokensContext.mk beginPos endPos text s) <|
go s.stx
return { data := (← get).data }
where
go (stx : Syntax) := do
match stx with
| `($e.$id:ident) => go e; addToken id SemanticTokenType.property
-- indistinguishable from next pattern
--| `(level|$id:ident) => addToken id SemanticTokenType.variable
| `($id:ident) => highlightId id
| _ =>
if !noHighlightKinds.contains stx.getKind then
highlightKeyword stx
if stx.isOfKind choiceKind then
go stx[0]
else
stx.getArgs.forM go
highlightId (stx : Syntax) : ReaderT SemanticTokensContext (StateT SemanticTokensState RequestM) _ := do
if let some range := stx.getRange? then
let mut lastPos := range.start
for ti in (← read).snap.infoTree.deepestNodes (fun
| _, i@(Elab.Info.ofTermInfo ti), _ => match i.pos? with
| some ipos => if range.contains ipos then some ti else none
| _ => none
| _, _, _ => none) do
let pos := ti.stx.getPos?.get!
-- avoid reporting same position twice; the info node can occur multiple times if
-- e.g. the term is elaborated multiple times
if pos < lastPos then
continue
if let Expr.fvar fvarId .. := ti.expr then
if let some localDecl := ti.lctx.find? fvarId then
-- Recall that `isAuxDecl` is an auxiliary declaration used to elaborate a recursive definition.
if localDecl.isAuxDecl then
if ti.isBinder then
addToken ti.stx SemanticTokenType.function
else
addToken ti.stx SemanticTokenType.variable
else if ti.stx.getPos?.get! > lastPos then
-- any info after the start position: must be projection notation
addToken ti.stx SemanticTokenType.property
lastPos := ti.stx.getPos?.get!
highlightKeyword stx := do
if let Syntax.atom _ val := stx then
if (val.length > 0 && val.front.isAlpha) ||
-- Support for keywords of the form `#<alpha>...`
(val.length > 1 && val.front == '#' && (val.get ⟨1⟩).isAlpha) then
addToken stx SemanticTokenType.keyword
addToken stx type := do
let ⟨beginPos, endPos, text, _⟩ ← read
if let (some pos, some tailPos) := (stx.getPos?, stx.getTailPos?) then
if beginPos <= pos && pos < endPos then
let lspPos := (← get).lastLspPos
let lspPos' := text.utf8PosToLspPos pos
let deltaLine := lspPos'.line - lspPos.line
let deltaStart := lspPos'.character - (if lspPos'.line == lspPos.line then lspPos.character else 0)
let length := (text.utf8PosToLspPos tailPos).character - lspPos'.character
let tokenType := type.toNat
let tokenModifiers := 0
modify fun st => {
data := st.data ++ #[deltaLine, deltaStart, length, tokenType, tokenModifiers]
lastLspPos := lspPos'
}
def handleSemanticTokensFull (_ : SemanticTokensParams)
: RequestM (RequestTask SemanticTokens) := do
handleSemanticTokens 0 ⟨1 <<< 16⟩
def handleSemanticTokensRange (p : SemanticTokensRangeParams)
: RequestM (RequestTask SemanticTokens) := do
let doc ← readDoc
let text := doc.meta.text
let beginPos := text.lspPosToUtf8Pos p.range.start
let endPos := text.lspPosToUtf8Pos p.range.end
handleSemanticTokens beginPos endPos
partial def handleFoldingRange (_ : FoldingRangeParams)
: RequestM (RequestTask (Array FoldingRange)) := do
let doc ← readDoc
let t := doc.cmdSnaps.waitAll
mapTask t fun (snaps, _) => do
let stxs := snaps.map (·.stx)
let (_, ranges) ← StateT.run (addRanges doc.meta.text [] stxs) #[]
return ranges
where
isImport stx := stx.isOfKind ``Lean.Parser.Module.header || stx.isOfKind ``Lean.Parser.Command.open
addRanges (text : FileMap) sections
| [] => do
if let (_, start)::rest := sections then
addRange text FoldingRangeKind.region start text.source.endPos
addRanges text rest []
| stx::stxs => match stx with
| `(namespace $id) =>
addRanges text ((id.getId.getNumParts, stx.getPos?)::sections) stxs
| `(section $(id)?) =>
addRanges text ((id.map (·.getId.getNumParts) |>.getD 1, stx.getPos?)::sections) stxs
| `(end $(id)?) => do
let rec popRanges n sections := do
if let (size, start)::rest := sections then
if size == n then
addRange text FoldingRangeKind.region start stx.getTailPos?
addRanges text rest stxs
else if size > n then
-- we don't add a range here because vscode doesn't like
-- multiple folding regions with the same start line
addRanges text ((size - n, start)::rest) stxs
else
addRange text FoldingRangeKind.region start stx.getTailPos?
popRanges (n - size) rest
else
addRanges text sections stxs
popRanges (id.map (·.getId.getNumParts) |>.getD 1) sections
| `(mutual $body* end) => do
addRangeFromSyntax text FoldingRangeKind.region stx
addRanges text [] body.raw.toList
addRanges text sections stxs
| _ => do
if isImport stx then
let (imports, stxs) := stxs.span isImport
let last := imports.getLastD stx
addRange text FoldingRangeKind.imports stx.getPos? last.getTailPos?
addRanges text sections stxs
else
addCommandRange text stx
addRanges text sections stxs
addCommandRange text stx :=
match stx.getKind with
| `Lean.Parser.Command.moduleDoc =>
addRangeFromSyntax text FoldingRangeKind.comment stx
| ``Lean.Parser.Command.declaration => do
-- When visiting a declaration, attempt to fold the doc comment
-- separately to the main definition.
-- We never fold other modifiers, such as annotations.
if let `($dm:declModifiers $decl) := stx then
if let some comment := dm.raw[0].getOptional? then
addRangeFromSyntax text FoldingRangeKind.comment comment
addRangeFromSyntax text FoldingRangeKind.region decl
else
addRangeFromSyntax text FoldingRangeKind.region stx
| _ =>
addRangeFromSyntax text FoldingRangeKind.region stx
addRangeFromSyntax (text : FileMap) kind stx := addRange text kind stx.getPos? stx.getTailPos?
addRange (text : FileMap) kind start? stop? := do
if let (some startP, some endP) := (start?, stop?) then
let startP := text.utf8PosToLspPos startP
let endP := text.utf8PosToLspPos endP
if startP.line != endP.line then
modify fun st => st.push
{ startLine := startP.line
endLine := endP.line
kind? := some kind }
partial def handleWaitForDiagnostics (p : WaitForDiagnosticsParams)
: RequestM (RequestTask WaitForDiagnostics) := do
let rec waitLoop : RequestM EditableDocument := do
let doc ← readDoc
if p.version ≤ doc.meta.version then
return doc
else
IO.sleep 50
waitLoop
let t ← RequestM.asTask waitLoop
RequestM.bindTask t fun doc? => do
let doc ← liftExcept doc?
let t₁ := doc.cmdSnaps.waitAll
return t₁.map fun _ => pure WaitForDiagnostics.mk
builtin_initialize
registerLspRequestHandler "textDocument/waitForDiagnostics" WaitForDiagnosticsParams WaitForDiagnostics handleWaitForDiagnostics
registerLspRequestHandler "textDocument/completion" CompletionParams CompletionList handleCompletion
registerLspRequestHandler "textDocument/hover" HoverParams (Option Hover) handleHover
registerLspRequestHandler "textDocument/declaration" TextDocumentPositionParams (Array LocationLink) (handleDefinition GoToKind.declaration)
registerLspRequestHandler "textDocument/definition" TextDocumentPositionParams (Array LocationLink) (handleDefinition GoToKind.definition)
registerLspRequestHandler "textDocument/typeDefinition" TextDocumentPositionParams (Array LocationLink) (handleDefinition GoToKind.type)
registerLspRequestHandler "textDocument/documentHighlight" DocumentHighlightParams DocumentHighlightResult handleDocumentHighlight
registerLspRequestHandler "textDocument/documentSymbol" DocumentSymbolParams DocumentSymbolResult handleDocumentSymbol
registerLspRequestHandler "textDocument/semanticTokens/full" SemanticTokensParams SemanticTokens handleSemanticTokensFull
registerLspRequestHandler "textDocument/semanticTokens/range" SemanticTokensRangeParams SemanticTokens handleSemanticTokensRange
registerLspRequestHandler "textDocument/foldingRange" FoldingRangeParams (Array FoldingRange) handleFoldingRange
registerLspRequestHandler "$/lean/plainGoal" PlainGoalParams (Option PlainGoal) handlePlainGoal
registerLspRequestHandler "$/lean/plainTermGoal" PlainTermGoalParams (Option PlainTermGoal) handlePlainTermGoal
end Lean.Server.FileWorker
|
024c049183053d4af656ee7e88ae356e9a114971
|
7cef822f3b952965621309e88eadf618da0c8ae9
|
/src/tactic/monotonicity/basic.lean
|
a12231b35f7e7caeeae661ec98929b10ea31f385
|
[
"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
| 5,485
|
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 tactic.core
import category.basic
import algebra.order_functions
import algebra.order
import meta.rb_map
namespace tactic.interactive
open tactic list
open lean lean.parser interactive
open interactive.types
structure mono_cfg :=
(unify := ff)
@[derive [decidable_eq,has_reflect]]
inductive mono_selection : Type
| left : mono_selection
| right : mono_selection
| both : mono_selection
section compare
parameter opt : mono_cfg
meta def compare (e₀ e₁ : expr) : tactic unit := do
if opt.unify then do
guard (¬ e₀.is_mvar ∧ ¬ e₁.is_mvar),
unify e₀ e₁
else is_def_eq e₀ e₁
meta def find_one_difference
: list expr → list expr → tactic (list expr × expr × expr × list expr)
| (x :: xs) (y :: ys) :=
do c ← try_core (compare x y),
if c.is_some
then prod.map (cons x) id <$> find_one_difference xs ys
else do
guard (xs.length = ys.length),
mzip_with' compare xs ys,
return ([],x,y,xs)
| xs ys := fail format!"find_one_difference: {xs}, {ys}"
end compare
def last_two {α : Type*} (l : list α) : option (α × α) :=
match l.reverse with
| (x₁ :: x₀ :: _) := some (x₀, x₁)
| _ := none
end
meta def match_imp : expr → tactic (expr × expr)
| `(%%e₀ → %%e₁) :=
do guard (¬ e₁.has_var),
return (e₀,e₁)
| _ := failed
open expr
meta def same_operator : expr → expr → bool
| (app e₀ _) (app e₁ _) :=
let fn₀ := e₀.get_app_fn,
fn₁ := e₁.get_app_fn in
fn₀.is_constant ∧ fn₀.const_name = fn₁.const_name
| (pi _ _ _ _) (pi _ _ _ _) := tt
| _ _ := ff
meta def get_operator (e : expr) : option name :=
guard (¬ e.is_pi) >> pure e.get_app_fn.const_name
meta def monotoncity.check_rel (xs : list expr) (l r : expr) : tactic (option name) :=
do guard (same_operator l r) <|>
do { fail format!"{l} and {r} should be the f x and f y for some f" },
if l.is_pi then pure none
else pure r.get_app_fn.const_name
@[reducible]
def mono_key := (with_bot name × with_bot name)
open nat
meta def mono_head_candidates : ℕ → list expr → expr → tactic mono_key
| 0 _ h := failed
| (succ n) xs h :=
do { (rel,l,r) ← if h.is_arrow
then pure (none,h.binding_domain,h.binding_body)
else guard h.get_app_fn.is_constant >>
prod.mk (some h.get_app_fn.const_name) <$> last_two h.get_app_args,
prod.mk <$> monotoncity.check_rel xs.reverse l r <*> pure rel } <|>
match xs with
| [] := fail format!"oh? {h}"
| (x::xs) := mono_head_candidates n xs (h.pis [x])
end
meta def monotoncity.check (lm_n : name) (prio : ℕ) (persistent : bool) : tactic mono_key :=
do lm ← mk_const lm_n,
lm_t ← infer_type lm,
(xs,h) ← mk_local_pis lm_t,
mono_head_candidates 3 xs.reverse h
meta instance : has_to_format mono_selection :=
⟨ λ x, match x with
| mono_selection.left := "left"
| mono_selection.right := "right"
| mono_selection.both := "both"
end ⟩
meta def side : lean.parser mono_selection :=
with_desc "expecting 'left', 'right' or 'both' (default)" $
do some n ← optional ident | pure mono_selection.both,
if n = `left then pure $ mono_selection.left
else if n = `right then pure $ mono_selection.right
else if n = `both then pure $ mono_selection.both
else fail format!"invalid argument: {n}, expecting 'left', 'right' or 'both' (default)"
open function
@[user_attribute]
meta def monotonicity.attr : user_attribute
(native.rb_lmap mono_key (name))
(option mono_key × mono_selection) :=
{ name := `mono
, descr := "monotonicity of function `f` wrt relations `R₀` and `R₁`: R₀ x y → R₁ (f x) (f y)"
, cache_cfg :=
{ dependencies := [],
mk_cache := λ ls,
do ps ← ls.mmap monotonicity.attr.get_param,
let ps := ps.filter_map prod.fst,
pure $ (ps.zip ls).foldl
(flip $ uncurry (λ k n m, m.insert k n))
(native.rb_lmap.mk mono_key _) }
, after_set := some $ λ n prio p,
do { (none,v) ← monotonicity.attr.get_param n | pure (),
k ← monotoncity.check n prio p,
monotonicity.attr.set n (some k,v) p }
, parser := prod.mk none <$> side }
meta def filter_instances (e : mono_selection) (ns : list name) : tactic (list name) :=
ns.mfilter $ λ n,
do d ← user_attribute.get_param_untyped monotonicity.attr n,
(_,d) ← to_expr ``(id %%d) >>= eval_expr (option mono_key × mono_selection),
return (e = d : bool)
meta def get_monotonicity_lemmas (k : expr) (e : mono_selection) : tactic (list name) :=
do ns ← monotonicity.attr.get_cache,
k' ← if k.is_pi
then pure (get_operator k.binding_domain,none)
else do { (x₀,x₁) ← last_two k.get_app_args,
pure (get_operator x₀,some k.get_app_fn.const_name) },
let ns := ns.find_def [] k',
ns' ← filter_instances e ns,
if e ≠ mono_selection.both then (++) ns' <$> filter_instances mono_selection.both ns
else pure ns'
end tactic.interactive
attribute [mono] add_le_add mul_le_mul neg_le_neg
mul_lt_mul_of_pos_left mul_lt_mul_of_pos_right
imp_imp_imp le_implies_le_of_le_of_le
sub_le_sub abs_le_abs
attribute [mono left] add_lt_add_of_le_of_lt mul_lt_mul'
attribute [mono right] add_lt_add_of_lt_of_le mul_lt_mul
open tactic.interactive
|
19dc81e3d6ef13d30b22dc2e7ffd862d5f20ecbe
|
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
|
/src/Lean/Util/Trace.lean
|
a34d0d983216492fdbfd0ee2ce38db2a74838fb8
|
[
"Apache-2.0"
] |
permissive
|
dupuisf/lean4
|
d082d13b01243e1de29ae680eefb476961221eef
|
6a39c65bd28eb0e28c3870188f348c8914502718
|
refs/heads/master
| 1,676,948,755,391
| 1,610,665,114,000
| 1,610,665,114,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 5,522
|
lean
|
/-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich, Leonardo de Moura
-/
import Lean.Message
import Lean.MonadEnv
universe u
namespace Lean
open Std (PersistentArray)
structure TraceElem where
ref : Syntax
msg : MessageData
deriving Inhabited
structure TraceState where
enabled : Bool := true
traces : PersistentArray TraceElem := {}
deriving Inhabited
namespace TraceState
private def toFormat (traces : PersistentArray TraceElem) (sep : Format) : IO Format :=
traces.size.foldM
(fun i r => do
let curr ← (traces.get! i).msg.format
pure $ if i > 0 then r ++ sep ++ curr else r ++ curr)
Format.nil
end TraceState
class MonadTrace (m : Type → Type) where
modifyTraceState : (TraceState → TraceState) → m Unit
getTraceState : m TraceState
export MonadTrace (getTraceState modifyTraceState)
instance (m n) [MonadLift m n] [MonadTrace m] : MonadTrace n where
modifyTraceState := fun f => liftM (modifyTraceState f : m _)
getTraceState := liftM (getTraceState : m _)
variables {α : Type} {m : Type → Type} [Monad m] [MonadTrace m]
def printTraces {m} [Monad m] [MonadTrace m] [MonadLiftT IO m] : m Unit := do
let traceState ← getTraceState
traceState.traces.forM fun m => do
let d ← m.msg.format
IO.println d
def resetTraceState {m} [MonadTrace m] : m Unit :=
modifyTraceState (fun _ => {})
private def checkTraceOptionAux (opts : Options) : Name → Bool
| n@(Name.str p _ _) => opts.getBool n || (!opts.contains n && checkTraceOptionAux opts p)
| _ => false
def checkTraceOption (opts : Options) (cls : Name) : Bool :=
if opts.isEmpty then false
else checkTraceOptionAux opts (`trace ++ cls)
private def checkTraceOptionM [MonadOptions m] (cls : Name) : m Bool := do
let opts ← getOptions
pure $ checkTraceOption opts cls
@[inline] def isTracingEnabledFor [MonadOptions m] (cls : Name) : m Bool := do
let s ← getTraceState
if !s.enabled then pure false
else checkTraceOptionM cls
@[inline] def enableTracing (b : Bool) : m Bool := do
let s ← getTraceState
let oldEnabled := s.enabled
modifyTraceState fun s => { s with enabled := b }
pure oldEnabled
@[inline] def getTraces : m (PersistentArray TraceElem) := do
let s ← getTraceState
pure s.traces
@[inline] def modifyTraces (f : PersistentArray TraceElem → PersistentArray TraceElem) : m Unit :=
modifyTraceState fun s => { s with traces := f s.traces }
@[inline] def setTraceState (s : TraceState) : m Unit :=
modifyTraceState fun _ => s
private def addNode (oldTraces : PersistentArray TraceElem) (cls : Name) (ref : Syntax) : m Unit :=
modifyTraces fun traces =>
if traces.isEmpty then
oldTraces
else
let d := MessageData.tagged cls (MessageData.node (traces.toArray.map fun elem => elem.msg))
oldTraces.push { ref := ref, msg := d }
private def getResetTraces : m (PersistentArray TraceElem) := do
let oldTraces ← getTraces
modifyTraces fun _ => {}
pure oldTraces
section
variables [MonadRef m] [AddMessageContext m] [MonadOptions m]
def addTrace (cls : Name) (msg : MessageData) : m Unit := do
let ref ← getRef
let msg ← addMessageContext msg
modifyTraces fun traces => traces.push { ref := ref, msg := MessageData.tagged cls msg }
@[inline] def trace (cls : Name) (msg : Unit → MessageData) : m Unit := do
if (← isTracingEnabledFor cls) then
addTrace cls (msg ())
@[inline] def traceM (cls : Name) (mkMsg : m MessageData) : m Unit := do
if (← isTracingEnabledFor cls) then
let msg ← mkMsg
addTrace cls msg
@[inline] def traceCtx [MonadFinally m] (cls : Name) (ctx : m α) : m α := do
let b ← isTracingEnabledFor cls
if !b then
let old ← enableTracing false
try ctx finally enableTracing old
else
let ref ← getRef
let oldCurrTraces ← getResetTraces
try ctx finally addNode oldCurrTraces cls ref
-- TODO: delete after fix old frontend
def MonadTracer.trace (cls : Name) (msg : Unit → MessageData) : m Unit :=
Lean.trace cls msg
end
def registerTraceClass (traceClassName : Name) : IO Unit :=
registerOption (`trace ++ traceClassName) { group := "trace", defValue := false, descr := "enable/disable tracing for the given module and submodules" }
macro:max "trace!" id:term:max msg:term : term =>
`(trace $id fun _ => ($msg : MessageData))
syntax "trace[" ident "]!" (interpolatedStr(term) <|> term) : term
macro_rules
| `(trace[$id]! $s) =>
if s.getKind == interpolatedStrKind then
`(Lean.trace $(quote id.getId) fun _ => m! $s)
else
`(Lean.trace $(quote id.getId) fun _ => ($s : MessageData))
variables {α : Type} {m : Type → Type} [Monad m] [MonadTrace m] [MonadOptions m] [MonadRef m]
def withNestedTraces [MonadFinally m] (x : m α) : m α := do
let s ← getTraceState
if !s.enabled then
x
else
let currTraces ← getTraces
modifyTraces fun _ => {}
let ref ← getRef
try
x
finally
modifyTraces fun traces =>
if traces.size == 0 then
currTraces
else if traces.size == 1 && traces[0].msg.isNest then
currTraces ++ traces -- No nest of nest
else
let d := traces.foldl (init := MessageData.nil) fun d elem =>
if d.isNil then elem.msg else m!"{d}\n{elem.msg}"
currTraces.push { ref := ref, msg := MessageData.nestD d }
end Lean
|
d0323e8478505bb15f160f6a024141e95a90b78c
|
4727251e0cd73359b15b664c3170e5d754078599
|
/src/tactic/ring_exp.lean
|
42f2f55f91f72415bd685202c2bacea6c7025279
|
[
"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
| 57,195
|
lean
|
/-
Copyright (c) 2019 Tim Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baanen
-/
import tactic.norm_num
import control.traversable.basic
/-!
# `ring_exp` tactic
A tactic for solving equations in commutative (semi)rings,
where the exponents can also contain variables.
More precisely, expressions of the following form are supported:
- constants (non-negative integers)
- variables
- coefficients (any rational number, embedded into the (semi)ring)
- addition of expressions
- multiplication of expressions
- exponentiation of expressions (the exponent must have type `ℕ`)
- subtraction and negation of expressions (if the base is a full ring)
The motivating example is proving `2 * 2^n * b = b * 2^(n+1)`,
something that the `ring` tactic cannot do, but `ring_exp` can.
## Implementation notes
The basic approach to prove equalities is to normalise both sides and check for equality.
The normalisation is guided by building a value in the type `ex` at the meta level,
together with a proof (at the base level) that the original value is equal to
the normalised version.
The normalised version and normalisation proofs are also stored in the `ex` type.
The outline of the file:
- Define an inductive family of types `ex`, parametrised over `ex_type`,
which can represent expressions with `+`, `*`, `^` and rational numerals.
The parametrisation over `ex_type` ensures that associativity and distributivity are applied,
by restricting which kinds of subexpressions appear as arguments to the various operators.
- Represent addition, multiplication and exponentiation in the `ex` type,
thus allowing us to map expressions to `ex` (the `eval` function drives this).
We apply associativity and distributivity of the operators here (helped by `ex_type`)
and commutativity as well (by sorting the subterms; unfortunately not helped by anything).
Any expression not of the above formats is treated as an atom (the same as a variable).
There are some details we glossed over which make the plan more complicated:
- The order on atoms is not initially obvious.
We construct a list containing them in order of initial appearance in the expression,
then use the index into the list as a key to order on.
- In the tactic, a normalized expression `ps : ex` lives in the meta-world,
but the normalization proofs live in the real world.
Thus, we cannot directly say `ps.orig = ps.pretty` anywhere,
but we have to carefully construct the proof when we compute `ps`.
This was a major source of bugs in development!
- For `pow`, the exponent must be a natural number, while the base can be any semiring `α`.
We swap out operations for the base ring `α` with those for the exponent ring `ℕ`
as soon as we deal with exponents.
This is accomplished by the `in_exponent` function and is relatively painless since
we work in a `reader` monad.
- The normalized form of an expression is the one that is useful for the tactic,
but not as nice to read. To remedy this, the user-facing normalization calls `ex.simp`.
## Caveats and future work
Subtraction cancels out identical terms, but division does not.
That is: `a - a = 0 := by ring_exp` solves the goal,
but `a / a := 1 by ring_exp` doesn't.
Note that `0 / 0` is generally defined to be `0`,
so division cancelling out is not true in general.
Multiplication of powers can be simplified a little bit further:
`2 ^ n * 2 ^ n = 4 ^ n := by ring_exp` could be implemented
in a similar way that `2 * a + 2 * a = 4 * a := by ring_exp` already works.
This feature wasn't needed yet, so it's not implemented yet.
## Tags
ring, semiring, exponent, power
-/
-- The base ring `α` will have a universe level `u`.
-- We do not introduce `α` as a variable yet,
-- in order to make it explicit or implicit as required.
universes u
namespace tactic.ring_exp
open nat
/--
The `atom` structure is used to represent atomic expressions:
those which `ring_exp` cannot parse any further.
For instance, `a + (a % b)` has `a` and `(a % b)` as atoms.
The `ring_exp_eq` tactic does not normalize the subexpressions in atoms,
but `ring_exp` does if `ring_exp_eq` was not sufficient.
Atoms in fact represent equivalence classes of expressions,
modulo definitional equality.
The field `index : ℕ` should be a unique number for each class,
while `value : expr` contains a representative of this class.
The function `resolve_atom` determines the appropriate atom
for a given expression.
-/
meta structure atom : Type := (value : expr) (index : ℕ)
namespace atom
/--
The `eq` operation on `atom`s works modulo definitional equality,
ignoring their `value`s.
The invariants on `atom` ensure indices are unique per value.
Thus, `eq` indicates equality as long as the `atom`s come from the same context.
-/
meta def eq (a b : atom) : bool := a.index = b.index
/--
We order `atom`s on the order of appearance in the main expression.
-/
meta def lt (a b : atom) : bool := a.index < b.index
meta instance : has_repr atom := ⟨λ x, "(atom " ++ repr x.2 ++ ")"⟩
end atom
section expression
/-!
### `expression` section
In this section, we define the `ex` type and its basic operations.
First, we introduce the supporting types `coeff`, `ex_type` and `ex_info`.
For understanding the code, it's easier to check out `ex` itself first,
then refer back to the supporting types.
The arithmetic operations on `ex` need additional definitions,
so they are defined in a later section.
-/
/--
Coefficients in the expression are stored in a wrapper structure,
allowing for easier modification of the data structures.
The modifications might be caching of the result of `expr.of_rat`,
or using a different meta representation of numerals.
-/
@[derive decidable_eq, derive inhabited]
structure coeff : Type := (value : ℚ)
/-- The values in `ex_type` are used as parameters to `ex` to control the expression's structure. -/
@[derive decidable_eq, derive inhabited]
inductive ex_type : Type
| base : ex_type
| sum : ex_type
| prod : ex_type
| exp : ex_type
open ex_type
/--
Each `ex` stores information for its normalization proof.
The `orig` expression is the expression that was passed to `eval`.
The `pretty` expression is the normalised form that the `ex` represents.
(I didn't call this something like `norm`, because there are already
too many things called `norm` in mathematics!)
The field `proof` contains an optional proof term of type `%%orig = %%pretty`.
The value `none` for the proof indicates that everything reduces to reflexivity.
(Which saves space in quite a lot of cases.)
-/
meta structure ex_info : Type :=
(orig : expr) (pretty : expr) (proof : option expr)
/--
The `ex` type is an abstract representation of an expression with `+`, `*` and `^`.
Those operators are mapped to the `sum`, `prod` and `exp` constructors respectively.
The `zero` constructor is the base case for `ex sum`, e.g. `1 + 2` is represented
by (something along the lines of) `sum 1 (sum 2 zero)`.
The `coeff` constructor is the base case for `ex prod`, and is used for numerals.
The code maintains the invariant that the coefficient is never `0`.
The `var` constructor is the base case for `ex exp`, and is used for atoms.
The `sum_b` constructor allows for addition in the base of an exponentiation;
it serves a similar purpose as the parentheses in `(a + b)^c`.
The code maintains the invariant that the argument to `sum_b` is not `zero`
or `sum _ zero`.
All of the constructors contain an `ex_info` field,
used to carry around (arguments to) proof terms.
While the `ex_type` parameter enforces some simplification invariants,
the following ones must be manually maintained at the risk of insufficient power:
- the argument to `coeff` must be nonzero (to ensure `0 = 0 * 1`)
- the argument to `sum_b` must be of the form `sum a (sum b bs)` (to ensure `(a + 0)^n = a^n`)
- normalisation proofs of subexpressions must be `refl ps.pretty`
- if we replace `sum` with `cons` and `zero` with `nil`, the resulting list is sorted
according to the `lt` relation defined further down; similarly for `prod` and `coeff`
(to ensure `a + b = b + a`).
The first two invariants could be encoded in a subtype of `ex`,
but aren't (yet) to spare some implementation burden.
The other invariants cannot be encoded because we need the `tactic` monad to check them.
(For example, the correct equality check of `expr` is `is_def_eq : expr → expr → tactic unit`.)
-/
meta inductive ex : ex_type → Type
| zero (info : ex_info) : ex sum
| sum (info : ex_info) : ex prod → ex sum → ex sum
| coeff (info : ex_info) : coeff → ex prod
| prod (info : ex_info) : ex exp → ex prod → ex prod
| var (info : ex_info) : atom → ex base
| sum_b (info : ex_info) : ex sum → ex base
| exp (info : ex_info) : ex base → ex prod → ex exp
/--
Return the proof information associated to the `ex`.
-/
meta def ex.info : Π {et : ex_type} (ps : ex et), ex_info
| sum (ex.zero i) := i
| sum (ex.sum i _ _) := i
| prod (ex.coeff i _) := i
| prod (ex.prod i _ _) := i
| base (ex.var i _) := i
| base (ex.sum_b i _) := i
| exp (ex.exp i _ _) := i
/--
Return the original, non-normalized version of this `ex`.
Note that arguments to another `ex` are always "pre-normalized":
their `orig` and `pretty` are equal, and their `proof` is reflexivity.
-/
meta def ex.orig {et : ex_type} (ps : ex et) : expr := ps.info.orig
/--
Return the normalized version of this `ex`.
-/
meta def ex.pretty {et : ex_type} (ps : ex et) : expr := ps.info.pretty
/--
Return the normalisation proof of the given expression.
If the proof is `refl`, we give `none` instead,
which helps to control the size of proof terms.
To get an actual term, use `ex.proof_term`,
or use `mk_proof` with the correct set of arguments.
-/
meta def ex.proof {et : ex_type} (ps : ex et) : option expr := ps.info.proof
/--
Update the `orig` and `proof` fields of the `ex_info`.
Intended for use in `ex.set_info`.
-/
meta def ex_info.set (i : ex_info) (o : option expr) (pf : option expr) : ex_info :=
{orig := o.get_or_else i.pretty, proof := pf, .. i}
/--
Update the `ex_info` of the given expression.
We use this to combine intermediate normalisation proofs.
Since `pretty` only depends on the subexpressions,
which do not change, we do not set `pretty`.
-/
meta def ex.set_info : Π {et : ex_type} (ps : ex et), option expr → option expr → ex et
| sum (ex.zero i) o pf := ex.zero (i.set o pf)
| sum (ex.sum i p ps) o pf := ex.sum (i.set o pf) p ps
| prod (ex.coeff i x) o pf := ex.coeff (i.set o pf) x
| prod (ex.prod i p ps) o pf := ex.prod (i.set o pf) p ps
| base (ex.var i x) o pf := ex.var (i.set o pf) x
| base (ex.sum_b i ps) o pf := ex.sum_b (i.set o pf) ps
| exp (ex.exp i p ps) o pf := ex.exp (i.set o pf) p ps
instance coeff_has_repr : has_repr coeff := ⟨λ x, repr x.1⟩
/-- Convert an `ex` to a `string`. -/
meta def ex.repr : Π {et : ex_type}, ex et → string
| sum (ex.zero _) := "0"
| sum (ex.sum _ p ps) := ex.repr p ++ " + " ++ ex.repr ps
| prod (ex.coeff _ x) := repr x
| prod (ex.prod _ p ps) := ex.repr p ++ " * " ++ ex.repr ps
| base (ex.var _ x) := repr x
| base (ex.sum_b _ ps) := "(" ++ ex.repr ps ++ ")"
| exp (ex.exp _ p ps) := ex.repr p ++ " ^ " ++ ex.repr ps
meta instance {et : ex_type} : has_repr (ex et) := ⟨ex.repr⟩
/--
Equality test for expressions.
Since equivalence of `atom`s is not the same as equality,
we cannot make a true `(=)` operator for `ex` either.
-/
meta def ex.eq : Π {et : ex_type}, ex et → ex et → bool
| sum (ex.zero _) (ex.zero _) := tt
| sum (ex.zero _) (ex.sum _ _ _) := ff
| sum (ex.sum _ _ _) (ex.zero _) := ff
| sum (ex.sum _ p ps) (ex.sum _ q qs) := p.eq q && ps.eq qs
| prod (ex.coeff _ x) (ex.coeff _ y) := x = y
| prod (ex.coeff _ _) (ex.prod _ _ _) := ff
| prod (ex.prod _ _ _) (ex.coeff _ _) := ff
| prod (ex.prod _ p ps) (ex.prod _ q qs) := p.eq q && ps.eq qs
| base (ex.var _ x) (ex.var _ y) := x.eq y
| base (ex.var _ _) (ex.sum_b _ _) := ff
| base (ex.sum_b _ _) (ex.var _ _) := ff
| base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.eq qs
| exp (ex.exp _ p ps) (ex.exp _ q qs) := p.eq q && ps.eq qs
/--
The ordering on expressions.
As for `ex.eq`, this is a linear order only in one context.
-/
meta def ex.lt : Π {et : ex_type}, ex et → ex et → bool
| sum _ (ex.zero _) := ff
| sum (ex.zero _) _ := tt
| sum (ex.sum _ p ps) (ex.sum _ q qs) := p.lt q || (p.eq q && ps.lt qs)
| prod (ex.coeff _ x) (ex.coeff _ y) := x.1 < y.1
| prod (ex.coeff _ _) _ := tt
| prod _ (ex.coeff _ _) := ff
| prod (ex.prod _ p ps) (ex.prod _ q qs) := p.lt q || (p.eq q && ps.lt qs)
| base (ex.var _ x) (ex.var _ y) := x.lt y
| base (ex.var _ _) (ex.sum_b _ _) := tt
| base (ex.sum_b _ _) (ex.var _ _) := ff
| base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.lt qs
| exp (ex.exp _ p ps) (ex.exp _ q qs) := p.lt q || (p.eq q && ps.lt qs)
end expression
section operations
/-!
### `operations` section
This section defines the operations (on `ex`) that use tactics.
They live in the `ring_exp_m` monad,
which adds a cache and a list of encountered atoms to the `tactic` monad.
Throughout this section, we will be constructing proof terms.
The lemmas used in the construction are all defined over a commutative semiring α.
-/
variables {α : Type u} [comm_semiring α]
open tactic
open ex_type
/--
Stores the information needed in the `eval` function and its dependencies,
so they can (re)construct expressions.
The `eval_info` structure stores this information for one type,
and the `context` combines the two types, one for bases and one for exponents.
-/
meta structure eval_info :=
(α : expr) (univ : level)
-- Cache the instances for optimization and consistency
(csr_instance : expr) (ha_instance : expr) (hm_instance : expr) (hp_instance : expr)
-- Optional instances (only required for (-) and (/) respectively)
(ring_instance : option expr) (dr_instance : option expr)
-- Cache common constants.
(zero : expr) (one : expr)
/--
The `context` contains the full set of information needed for the `eval` function.
This structure has two copies of `eval_info`:
one is for the base (typically some semiring `α`) and another for the exponent (always `ℕ`).
When evaluating an exponent, we put `info_e` in `info_b`.
-/
meta structure context :=
(info_b : eval_info) (info_e : eval_info) (transp : transparency)
/--
The `ring_exp_m` monad is used instead of `tactic` to store the context.
-/
@[derive [monad, alternative]]
meta def ring_exp_m (α : Type) : Type := reader_t context (state_t (list atom) tactic) α
/--
Access the instance cache.
-/
meta def get_context : ring_exp_m context := reader_t.read
/--
Lift an operation in the `tactic` monad to the `ring_exp_m` monad.
This operation will not access the cache.
-/
meta def lift {α} (m : tactic α) : ring_exp_m α := reader_t.lift (state_t.lift m)
/--
Change the context of the given computation,
so that expressions are evaluated in the exponent ring,
instead of the base ring.
-/
meta def in_exponent {α} (mx : ring_exp_m α) : ring_exp_m α := do
ctx ← get_context,
reader_t.lift $ mx.run ⟨ctx.info_e, ctx.info_e, ctx.transp⟩
/--
Specialized version of `mk_app` where the first two arguments are `{α}` `[some_class α]`.
Should be faster because it can use the cached instances.
-/
meta def mk_app_class (f : name) (inst : expr) (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
pure $ (@expr.const tt f [ctx.info_b.univ] ctx.info_b.α inst).mk_app args
/--
Specialized version of `mk_app` where the first two arguments are `{α}` `[comm_semiring α]`.
Should be faster because it can use the cached instances.
-/
meta def mk_app_csr (f : name) (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
mk_app_class f (ctx.info_b.csr_instance) args
/--
Specialized version of `mk_app ``has_add.add`.
Should be faster because it can use the cached instances.
-/
meta def mk_add (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
mk_app_class ``has_add.add ctx.info_b.ha_instance args
/--
Specialized version of `mk_app ``has_mul.mul`.
Should be faster because it can use the cached instances.
-/
meta def mk_mul (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
mk_app_class ``has_mul.mul ctx.info_b.hm_instance args
/--
Specialized version of `mk_app ``has_pow.pow`.
Should be faster because it can use the cached instances.
-/
meta def mk_pow (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
pure $ (@expr.const tt ``has_pow.pow
[ctx.info_b.univ, ctx.info_e.univ]
ctx.info_b.α ctx.info_e.α
ctx.info_b.hp_instance).mk_app args
/-- Construct a normalization proof term or return the cached one. -/
meta def ex_info.proof_term (ps : ex_info) : ring_exp_m expr :=
match ps.proof with
| none := lift $ tactic.mk_eq_refl ps.pretty
| (some p) := pure p
end
/-- Construct a normalization proof term or return the cached one. -/
meta def ex.proof_term {et : ex_type} (ps : ex et) : ring_exp_m expr := ps.info.proof_term
/--
If all `ex_info` have trivial proofs, return a trivial proof.
Otherwise, construct all proof terms.
Useful in applications where trivial proofs combine to another trivial proof,
most importantly to pass to `mk_proof_or_refl`.
-/
meta def none_or_proof_term : list ex_info → ring_exp_m (option (list expr))
| [] := pure none
| (x :: xs) := do
xs_pfs ← none_or_proof_term xs,
match (x.proof, xs_pfs) with
| (none, none) := pure none
| (some x_pf, none) := do
xs_pfs ← traverse ex_info.proof_term xs,
pure (some (x_pf :: xs_pfs))
| (_, some xs_pfs) := do
x_pf ← x.proof_term,
pure (some (x_pf :: xs_pfs))
end
/--
Use the proof terms as arguments to the given lemma.
If the lemma could reduce to reflexivity, consider using `mk_proof_or_refl.`
-/
meta def mk_proof (lem : name) (args : list expr) (hs : list ex_info) : ring_exp_m expr := do
hs' ← traverse ex_info.proof_term hs,
mk_app_csr lem (args ++ hs')
/--
Use the proof terms as arguments to the given lemma.
Often, we construct a proof term using congruence where reflexivity suffices.
To solve this, the following function tries to get away with reflexivity.
-/
meta def mk_proof_or_refl (term : expr) (lem : name) (args : list expr) (hs : list ex_info) :
ring_exp_m expr := do
hs_full ← none_or_proof_term hs,
match hs_full with
| none := lift $ mk_eq_refl term
| (some hs') := mk_app_csr lem (args ++ hs')
end
/-- A shortcut for adding the original terms of two expressions. -/
meta def add_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr :=
mk_add [ps.orig, qs.orig]
/-- A shortcut for multiplying the original terms of two expressions. -/
meta def mul_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr :=
mk_mul [ps.orig, qs.orig]
/-- A shortcut for exponentiating the original terms of two expressions. -/
meta def pow_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr :=
mk_pow [ps.orig, qs.orig]
/-- Congruence lemma for constructing `ex.sum`. -/
lemma sum_congr {p p' ps ps' : α} : p = p' → ps = ps' → p + ps = p' + ps' := by cc
/-- Congruence lemma for constructing `ex.prod`. -/
lemma prod_congr {p p' ps ps' : α} : p = p' → ps = ps' → p * ps = p' * ps' := by cc
/-- Congruence lemma for constructing `ex.exp`. -/
lemma exp_congr {p p' : α} {ps ps' : ℕ} : p = p' → ps = ps' → p ^ ps = p' ^ ps' := by cc
/-- Constructs `ex.zero` with the correct arguments. -/
meta def ex_zero : ring_exp_m (ex sum) := do
ctx ← get_context,
pure $ ex.zero ⟨ctx.info_b.zero, ctx.info_b.zero, none⟩
/-- Constructs `ex.sum` with the correct arguments. -/
meta def ex_sum (p : ex prod) (ps : ex sum) : ring_exp_m (ex sum) := do
pps_o ← add_orig p ps,
pps_p ← mk_add [p.pretty, ps.pretty],
pps_pf ← mk_proof_or_refl pps_p ``sum_congr
[p.orig, p.pretty, ps.orig, ps.pretty]
[p.info, ps.info],
pure (ex.sum ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none))
/--
Constructs `ex.coeff` with the correct arguments.
There are more efficient constructors for specific numerals:
if `x = 0`, you should use `ex_zero`; if `x = 1`, use `ex_one`.
-/
meta def ex_coeff (x : rat) : ring_exp_m (ex prod) := do
ctx ← get_context,
x_p ← lift $ expr.of_rat ctx.info_b.α x,
pure (ex.coeff ⟨x_p, x_p, none⟩ ⟨x⟩)
/--
Constructs `ex.coeff 1` with the correct arguments.
This is a special case for optimization purposes.
-/
meta def ex_one : ring_exp_m (ex prod) := do
ctx ← get_context,
pure $ ex.coeff ⟨ctx.info_b.one, ctx.info_b.one, none⟩ ⟨1⟩
/-- Constructs `ex.prod` with the correct arguments. -/
meta def ex_prod (p : ex exp) (ps : ex prod) : ring_exp_m (ex prod) := do
pps_o ← mul_orig p ps,
pps_p ← mk_mul [p.pretty, ps.pretty],
pps_pf ← mk_proof_or_refl pps_p ``prod_congr
[p.orig, p.pretty, ps.orig, ps.pretty]
[p.info, ps.info],
pure (ex.prod ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none))
/-- Constructs `ex.var` with the correct arguments. -/
meta def ex_var (p : atom) : ring_exp_m (ex base) := pure (ex.var ⟨p.1, p.1, none⟩ p)
/-- Constructs `ex.sum_b` with the correct arguments. -/
meta def ex_sum_b (ps : ex sum) : ring_exp_m (ex base) :=
pure (ex.sum_b ps.info (ps.set_info none none))
/-- Constructs `ex.exp` with the correct arguments. -/
meta def ex_exp (p : ex base) (ps : ex prod) : ring_exp_m (ex exp) := do
ctx ← get_context,
pps_o ← pow_orig p ps,
pps_p ← mk_pow [p.pretty, ps.pretty],
pps_pf ← mk_proof_or_refl pps_p ``exp_congr
[p.orig, p.pretty, ps.orig, ps.pretty]
[p.info, ps.info],
pure (ex.exp ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none))
lemma base_to_exp_pf {p p' : α} : p = p' → p = p' ^ 1 := by simp
/-- Conversion from `ex base` to `ex exp`. -/
meta def base_to_exp (p : ex base) : ring_exp_m (ex exp) := do
o ← in_exponent $ ex_one,
ps ← ex_exp p o,
pf ← mk_proof ``base_to_exp_pf [p.orig, p.pretty] [p.info],
pure $ ps.set_info p.orig pf
lemma exp_to_prod_pf {p p' : α} : p = p' → p = p' * 1 := by simp
/-- Conversion from `ex exp` to `ex prod`. -/
meta def exp_to_prod (p : ex exp) : ring_exp_m (ex prod) := do
o ← ex_one,
ps ← ex_prod p o,
pf ← mk_proof ``exp_to_prod_pf [p.orig, p.pretty] [p.info],
pure $ ps.set_info p.orig pf
lemma prod_to_sum_pf {p p' : α} : p = p' → p = p' + 0 := by simp
/-- Conversion from `ex prod` to `ex sum`. -/
meta def prod_to_sum (p : ex prod) : ring_exp_m (ex sum) := do
z ← ex_zero,
ps ← ex_sum p z,
pf ← mk_proof ``prod_to_sum_pf [p.orig, p.pretty] [p.info],
pure $ ps.set_info p.orig pf
lemma atom_to_sum_pf (p : α) : p = p ^ 1 * 1 + 0 := by simp
/--
A more efficient conversion from `atom` to `ex sum`.
The result should be the same as `ex_var p >>= base_to_exp >>= exp_to_prod >>= prod_to_sum`,
except we need to calculate less intermediate steps.
-/
meta def atom_to_sum (p : atom) : ring_exp_m (ex sum) := do
p' ← ex_var p,
o ← in_exponent $ ex_one,
p' ← ex_exp p' o,
o ← ex_one,
p' ← ex_prod p' o,
z ← ex_zero,
p' ← ex_sum p' z,
pf ← mk_proof ``atom_to_sum_pf [p.1] [],
pure $ p'.set_info p.1 pf
/--
Compute the sum of two coefficients.
Note that the result might not be a valid expression:
if `p = -q`, then the result should be `ex.zero : ex sum` instead.
The caller must detect when this happens!
The returned value is of the form `ex.coeff _ (p + q)`,
with the proof of `expr.of_rat p + expr.of_rat q = expr.of_rat (p + q)`.
-/
meta def add_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do
ctx ← get_context,
pq_o ← mk_add [p_p, q_p],
(pq_p, pq_pf) ← lift $ norm_num.eval_field pq_o,
pure $ ex.coeff ⟨pq_o, pq_p, pq_pf⟩ ⟨p.1 + q.1⟩
lemma mul_coeff_pf_one_mul (q : α) : 1 * q = q := one_mul q
lemma mul_coeff_pf_mul_one (p : α) : p * 1 = p := mul_one p
/--
Compute the product of two coefficients.
The returned value is of the form `ex.coeff _ (p * q)`,
with the proof of `expr.of_rat p * expr.of_rat q = expr.of_rat (p * q)`.
-/
meta def mul_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) :=
match p.1, q.1 with -- Special case to speed up multiplication with 1.
| ⟨1, 1, _, _⟩, _ := do
ctx ← get_context,
pq_o ← mk_mul [p_p, q_p],
pf ← mk_app_csr ``mul_coeff_pf_one_mul [q_p],
pure $ ex.coeff ⟨pq_o, q_p, pf⟩ ⟨q.1⟩
| _, ⟨1, 1, _, _⟩ := do
ctx ← get_context,
pq_o ← mk_mul [p_p, q_p],
pf ← mk_app_csr ``mul_coeff_pf_mul_one [p_p],
pure $ ex.coeff ⟨pq_o, p_p, pf⟩ ⟨p.1⟩
| _, _ := do
ctx ← get_context,
pq' ← mk_mul [p_p, q_p],
(pq_p, pq_pf) ← lift $ norm_num.eval_field pq',
pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩
end
section rewrite
/-! ### `rewrite` section
In this section we deal with rewriting terms to fit in the basic grammar of `eval`.
For example, `nat.succ n` is rewritten to `n + 1` before it is evaluated further.
-/
/-- Given a proof that the expressions `ps_o` and `ps'.orig` are equal,
show that `ps_o` and `ps'.pretty` are equal.
Useful to deal with aliases in `eval`. For instance, `nat.succ p` can be handled
as an alias of `p + 1` as follows:
```
| ps_o@`(nat.succ %%p_o) := do
ps' ← eval `(%%p_o + 1),
pf ← lift $ mk_app ``nat.succ_eq_add_one [p_o],
rewrite ps_o ps' pf
```
-/
meta def rewrite (ps_o : expr) (ps' : ex sum) (pf : expr) : ring_exp_m (ex sum) :=
do
ps'_pf ← ps'.info.proof_term,
pf ← lift $ mk_eq_trans pf ps'_pf,
pure $ ps'.set_info ps_o pf
end rewrite
/--
Represents the way in which two products are equal except coefficient.
This type is used in the function `add_overlap`.
In order to deal with equations of the form `a * 2 + a = 3 * a`,
the `add` function will add up overlapping products,
turning `a * 2 + a` into `a * 3`.
We need to distinguish `a * 2 + a` from `a * 2 + b` in order to do this,
and the `overlap` type carries the information on how it overlaps.
The case `none` corresponds to non-overlapping products, e.g. `a * 2 + b`;
the case `nonzero` to overlapping products adding to non-zero, e.g. `a * 2 + a`
(the `ex prod` field will then look like `a * 3` with a proof that `a * 2 + a = a * 3`);
the case `zero` to overlapping products adding to zero, e.g. `a * 2 + a * -2`.
We distinguish those two cases because in the second, the whole product reduces to `0`.
A potential extension to the tactic would also do this for the base of exponents,
e.g. to show `2^n * 2^n = 4^n`.
-/
meta inductive overlap : Type
| none : overlap
| nonzero : ex prod → overlap
| zero : ex sum → overlap
lemma add_overlap_pf {ps qs pq} (p : α) : ps + qs = pq → p * ps + p * qs = p * pq := λ pq_pf, calc
p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _)
... = p * pq : by rw pq_pf
lemma add_overlap_pf_zero {ps qs} (p : α) : ps + qs = 0 → p * ps + p * qs = 0 := λ pq_pf, calc
p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _)
... = p * 0 : by rw pq_pf
... = 0 : mul_zero _
/--
Given arguments `ps`, `qs` of the form `ps' * x` and `ps' * y` respectively
return `ps + qs = ps' * (x + y)` (with `x` and `y` arbitrary coefficients).
For other arguments, return `overlap.none`.
-/
meta def add_overlap : ex prod → ex prod → ring_exp_m overlap
| (ex.coeff x_i x) (ex.coeff y_i y) := do
xy@(ex.coeff _ xy_c) ← add_coeff x_i.pretty y_i.pretty x y
| lift $ fail "internal error: add_coeff should return ex.coeff",
if xy_c.1 = 0
then do
z ← ex_zero,
pure $ overlap.zero (z.set_info xy.orig xy.proof)
else pure $ overlap.nonzero xy
| (ex.prod _ _ _) (ex.coeff _ _) := pure overlap.none
| (ex.coeff _ _) (ex.prod _ _ _) := pure overlap.none
| pps@(ex.prod _ p ps) qqs@(ex.prod _ q qs) := if p.eq q
then do
pq_ol ← add_overlap ps qs,
pqs_o ← add_orig pps qqs,
match pq_ol with
| overlap.none := pure overlap.none
| (overlap.nonzero pq) := do
pqs ← ex_prod p pq,
pf ← mk_proof ``add_overlap_pf
[ps.pretty, qs.pretty, pq.pretty, p.pretty]
[pq.info],
pure $ overlap.nonzero (pqs.set_info pqs_o pf)
| (overlap.zero pq) := do
z ← ex_zero,
pf ← mk_proof ``add_overlap_pf_zero
[ps.pretty, qs.pretty, p.pretty]
[pq.info],
pure $ overlap.zero (z.set_info pqs_o pf)
end
else pure overlap.none
section addition
lemma add_pf_z_sum {ps qs qs' : α} : ps = 0 → qs = qs' → ps + qs = qs' := λ ps_pf qs_pf, calc
ps + qs = 0 + qs' : by rw [ps_pf, qs_pf]
... = qs' : zero_add _
lemma add_pf_sum_z {ps ps' qs : α} : ps = ps' → qs = 0 → ps + qs = ps' := λ ps_pf qs_pf, calc
ps + qs = ps' + 0 : by rw [ps_pf, qs_pf]
... = ps' : add_zero _
lemma add_pf_sum_overlap {pps p ps qqs q qs pq pqs : α} :
pps = p + ps → qqs = q + qs → p + q = pq → ps + qs = pqs → pps + qqs = pq + pqs := by cc
lemma add_pf_sum_overlap_zero {pps p ps qqs q qs pqs : α} :
pps = p + ps → qqs = q + qs → p + q = 0 → ps + qs = pqs → pps + qqs = pqs :=
λ pps_pf qqs_pf pq_pf pqs_pf, calc
pps + qqs = (p + ps) + (q + qs) : by rw [pps_pf, qqs_pf]
... = (p + q) + (ps + qs) : by cc
... = 0 + pqs : by rw [pq_pf, pqs_pf]
... = pqs : zero_add _
lemma add_pf_sum_lt {pps p ps qqs pqs : α} :
pps = p + ps → ps + qqs = pqs → pps + qqs = p + pqs := by cc
lemma add_pf_sum_gt {pps qqs q qs pqs : α} :
qqs = q + qs → pps + qs = pqs → pps + qqs = q + pqs := by cc
/--
Add two expressions.
* `0 + qs = 0`
* `ps + 0 = 0`
* `ps * x + ps * y = ps * (x + y)` (for `x`, `y` coefficients; uses `add_overlap`)
* `(p + ps) + (q + qs) = p + (ps + (q + qs))` (if `p.lt q`)
* `(p + ps) + (q + qs) = q + ((p + ps) + qs)` (if not `p.lt q`)
-/
meta def add : ex sum → ex sum → ring_exp_m (ex sum)
| ps@(ex.zero ps_i) qs := do
pf ← mk_proof ``add_pf_z_sum [ps.orig, qs.orig, qs.pretty] [ps.info, qs.info],
pqs_o ← add_orig ps qs,
pure $ qs.set_info pqs_o pf
| ps qs@(ex.zero qs_i) := do
pf ← mk_proof ``add_pf_sum_z [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info],
pqs_o ← add_orig ps qs,
pure $ ps.set_info pqs_o pf
| pps@(ex.sum pps_i p ps) qqs@(ex.sum qqs_i q qs) := do
ol ← add_overlap p q,
ppqqs_o ← add_orig pps qqs,
match ol with
| (overlap.nonzero pq) := do
pqs ← add ps qs,
pqqs ← ex_sum pq pqs,
qqs_pf ← qqs.proof_term,
pf ← mk_proof ``add_pf_sum_overlap
[pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pq.pretty, pqs.pretty]
[pps.info, qqs.info, pq.info, pqs.info],
pure $ pqqs.set_info ppqqs_o pf
| (overlap.zero pq) := do
pqs ← add ps qs,
pf ← mk_proof ``add_pf_sum_overlap_zero
[pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[pps.info, qqs.info, pq.info, pqs.info],
pure $ pqs.set_info ppqqs_o pf
| overlap.none := if p.lt q
then do
pqs ← add ps qqs,
ppqs ← ex_sum p pqs,
pf ← mk_proof ``add_pf_sum_lt
[pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty]
[pps.info, pqs.info],
pure $ ppqs.set_info ppqqs_o pf
else do
pqs ← add pps qs,
pqqs ← ex_sum q pqs,
pf ← mk_proof ``add_pf_sum_gt
[pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[qqs.info, pqs.info],
pure $ pqqs.set_info ppqqs_o pf
end
end addition
section multiplication
lemma mul_pf_c_c {ps ps' qs qs' pq : α} :
ps = ps' → qs = qs' → ps' * qs' = pq → ps * qs = pq := by cc
lemma mul_pf_c_prod {ps qqs q qs pqs : α} :
qqs = q * qs → ps * qs = pqs → ps * qqs = q * pqs := by cc
lemma mul_pf_prod_c {pps p ps qs pqs : α} :
pps = p * ps → ps * qs = pqs → pps * qs = p * pqs := by cc
lemma mul_pp_pf_overlap {pps p_b ps qqs qs psqs : α} {p_e q_e : ℕ} :
pps = p_b ^ p_e * ps → qqs = p_b ^ q_e * qs →
p_b ^ (p_e + q_e) * (ps * qs) = psqs → pps * qqs = psqs
:= λ ps_pf qs_pf psqs_pf, by simp [symm psqs_pf, pow_add, ps_pf, qs_pf]; ac_refl
lemma mul_pp_pf_prod_lt {pps p ps qqs pqs : α} :
pps = p * ps → ps * qqs = pqs → pps * qqs = p * pqs := by cc
lemma mul_pp_pf_prod_gt {pps qqs q qs pqs : α} :
qqs = q * qs → pps * qs = pqs → pps * qqs = q * pqs := by cc
/--
Multiply two expressions.
* `x * y = (x * y)` (for `x`, `y` coefficients)
* `x * (q * qs) = q * (qs * x)` (for `x` coefficient)
* `(p * ps) * y = p * (ps * y)` (for `y` coefficient)
* `(p_b^p_e * ps) * (p_b^q_e * qs) = p_b^(p_e + q_e) * (ps * qs)`
(if `p_e` and `q_e` are identical except coefficient)
* `(p * ps) * (q * qs) = p * (ps * (q * qs))` (if `p.lt q`)
* `(p * ps) * (q * qs) = q * ((p * ps) * qs)` (if not `p.lt q`)
-/
meta def mul_pp : ex prod → ex prod → ring_exp_m (ex prod)
| ps@(ex.coeff _ x) qs@(ex.coeff _ y) := do
pq ← mul_coeff ps.pretty qs.pretty x y,
pq_o ← mul_orig ps qs,
pf ← mk_proof_or_refl pq.pretty ``mul_pf_c_c
[ps.orig, ps.pretty, qs.orig, qs.pretty, pq.pretty]
[ps.info, qs.info, pq.info],
pure $ pq.set_info pq_o pf
| ps@(ex.coeff _ x) qqs@(ex.prod _ q qs) := do
pqs ← mul_pp ps qs,
pqqs ← ex_prod q pqs,
pqqs_o ← mul_orig ps qqs,
pf ← mk_proof ``mul_pf_c_prod
[ps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[qqs.info, pqs.info],
pure $ pqqs.set_info pqqs_o pf
| pps@(ex.prod _ p ps) qs@(ex.coeff _ y) := do
pqs ← mul_pp ps qs,
ppqs ← ex_prod p pqs,
ppqs_o ← mul_orig pps qs,
pf ← mk_proof ``mul_pf_prod_c
[pps.orig, p.pretty, ps.pretty, qs.orig, pqs.pretty]
[pps.info, pqs.info],
pure $ ppqs.set_info ppqs_o pf
| pps@(ex.prod _ p@(ex.exp _ p_b p_e) ps) qqs@(ex.prod _ q@(ex.exp _ q_b q_e) qs) := do
ppqqs_o ← mul_orig pps qqs,
pq_ol ← in_exponent $ add_overlap p_e q_e,
match pq_ol, p_b.eq q_b with
| (overlap.nonzero pq_e), tt := do
psqs ← mul_pp ps qs,
pq ← ex_exp p_b pq_e,
ppsqqs ← ex_prod pq psqs,
pf ← mk_proof ``mul_pp_pf_overlap
[pps.orig, p_b.pretty, ps.pretty, qqs.orig, qs.pretty, ppsqqs.pretty, p_e.pretty, q_e.pretty]
[pps.info, qqs.info, ppsqqs.info],
pure $ ppsqqs.set_info ppqqs_o pf
| _, _ := if p.lt q then do
pqs ← mul_pp ps qqs,
ppqs ← ex_prod p pqs,
pf ← mk_proof ``mul_pp_pf_prod_lt
[pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty]
[pps.info, pqs.info],
pure $ ppqs.set_info ppqqs_o pf
else do
pqs ← mul_pp pps qs,
pqqs ← ex_prod q pqs,
pf ← mk_proof ``mul_pp_pf_prod_gt
[pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[qqs.info, pqs.info],
pure $ pqqs.set_info ppqqs_o pf
end
lemma mul_p_pf_zero {ps qs : α} : ps = 0 → ps * qs = 0 :=
λ ps_pf, by rw [ps_pf, zero_mul]
lemma mul_p_pf_sum {pps p ps qs ppsqs : α} : pps = p + ps →
p * qs + ps * qs = ppsqs → pps * qs = ppsqs := λ pps_pf ppsqs_pf, calc
pps * qs = (p + ps) * qs : by rw [pps_pf]
... = p * qs + ps * qs : add_mul _ _ _
... = ppsqs : ppsqs_pf
/--
Multiply two expressions.
* `0 * qs = 0`
* `(p + ps) * qs = (p * qs) + (ps * qs)`
-/
meta def mul_p : ex sum → ex prod → ring_exp_m (ex sum)
| ps@(ex.zero ps_i) qs := do
z ← ex_zero,
z_o ← mul_orig ps qs,
pf ← mk_proof ``mul_p_pf_zero [ps.orig, qs.orig] [ps.info],
pure $ z.set_info z_o pf
| pps@(ex.sum pps_i p ps) qs := do
pqs ← mul_pp p qs >>= prod_to_sum,
psqs ← mul_p ps qs,
ppsqs ← add pqs psqs,
pps_pf ← pps.proof_term,
ppsqs_o ← mul_orig pps qs,
ppsqs_pf ← ppsqs.proof_term,
pf ← mk_proof ``mul_p_pf_sum
[pps.orig, p.pretty, ps.pretty, qs.orig, ppsqs.pretty]
[pps.info, ppsqs.info],
pure $ ppsqs.set_info ppsqs_o pf
lemma mul_pf_zero {ps qs : α} : qs = 0 → ps * qs = 0 :=
λ qs_pf, by rw [qs_pf, mul_zero]
lemma mul_pf_sum {ps qqs q qs psqqs : α} : qqs = q + qs → ps * q + ps * qs = psqqs →
ps * qqs = psqqs := λ qs_pf psqqs_pf, calc
ps * qqs = ps * (q + qs) : by rw [qs_pf]
... = ps * q + ps * qs : mul_add _ _ _
... = psqqs : psqqs_pf
/--
Multiply two expressions.
* `ps * 0 = 0`
* `ps * (q + qs) = (ps * q) + (ps * qs)`
-/
meta def mul : ex sum → ex sum → ring_exp_m (ex sum)
| ps qs@(ex.zero qs_i) := do
z ← ex_zero,
z_o ← mul_orig ps qs,
pf ← mk_proof ``mul_pf_zero [ps.orig, qs.orig] [qs.info],
pure $ z.set_info z_o pf
| ps qqs@(ex.sum qqs_i q qs) := do
psq ← mul_p ps q,
psqs ← mul ps qs,
psqqs ← add psq psqs,
psqqs_o ← mul_orig ps qqs,
pf ← mk_proof ``mul_pf_sum
[ps.orig, qqs.orig, q.orig, qs.orig, psqqs.pretty]
[qqs.info, psqqs.info],
pure $ psqqs.set_info psqqs_o pf
end multiplication
section exponentiation
lemma pow_e_pf_exp {pps p : α} {ps qs psqs : ℕ} :
pps = p ^ ps → ps * qs = psqs → pps ^ qs = p ^ psqs :=
λ pps_pf psqs_pf, calc
pps ^ qs = (p ^ ps) ^ qs : by rw [pps_pf]
... = p ^ (ps * qs) : symm (pow_mul _ _ _)
... = p ^ psqs : by rw [psqs_pf]
/--
Compute the exponentiation of two coefficients.
The returned value is of the form `ex.coeff _ (p ^ q)`,
with the proof of `expr.of_rat p ^ expr.of_rat q = expr.of_rat (p ^ q)`.
-/
meta def pow_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do
ctx ← get_context,
pq' ← mk_pow [p_p, q_p],
(pq_p, pq_pf) ← lift $ norm_num.eval_pow pq',
pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩
/--
Exponentiate two expressions.
* `(p ^ ps) ^ qs = p ^ (ps * qs)`
-/
meta def pow_e : ex exp → ex prod → ring_exp_m (ex exp)
| pps@(ex.exp pps_i p ps) qs := do
psqs ← in_exponent $ mul_pp ps qs,
ppsqs ← ex_exp p psqs,
ppsqs_o ← pow_orig pps qs,
pf ← mk_proof ``pow_e_pf_exp
[pps.orig, p.pretty, ps.pretty, qs.orig, psqs.pretty]
[pps.info, psqs.info],
pure $ ppsqs.set_info ppsqs_o pf
lemma pow_pp_pf_one {ps : α} {qs : ℕ} : ps = 1 → ps ^ qs = 1 :=
λ ps_pf, by rw [ps_pf, one_pow]
lemma pow_pf_c_c {ps ps' pq : α} {qs qs' : ℕ} :
ps = ps' → qs = qs' → ps' ^ qs' = pq → ps ^ qs = pq := by cc
lemma pow_pp_pf_c {ps ps' pqs : α} {qs qs' : ℕ} :
ps = ps' → qs = qs' → ps' ^ qs' = pqs → ps ^ qs = pqs * 1 :=
by simp; cc
lemma pow_pp_pf_prod {pps p ps pqs psqs : α} {qs : ℕ} : pps = p * ps →
p ^ qs = pqs → ps ^ qs = psqs → pps ^ qs = pqs * psqs :=
λ pps_pf pqs_pf psqs_pf, calc
pps ^ qs = (p * ps) ^ qs : by rw [pps_pf]
... = p ^ qs * ps ^ qs : mul_pow _ _ _
... = pqs * psqs : by rw [pqs_pf, psqs_pf]
/--
Exponentiate two expressions.
* `1 ^ qs = 1`
* `x ^ qs = x ^ qs` (for `x` coefficient)
* `(p * ps) ^ qs = p ^ qs + ps ^ qs`
-/
meta def pow_pp : ex prod → ex prod → ring_exp_m (ex prod)
| ps@(ex.coeff ps_i ⟨⟨1, 1, _, _⟩⟩) qs := do
o ← ex_one,
o_o ← pow_orig ps qs,
pf ← mk_proof ``pow_pp_pf_one [ps.orig, qs.orig] [ps.info],
pure $ o.set_info o_o pf
| ps@(ex.coeff ps_i x) qs@(ex.coeff qs_i y) := do
pq ← pow_coeff ps.pretty qs.pretty x y,
pq_o ← pow_orig ps qs,
pf ← mk_proof_or_refl pq.pretty ``pow_pf_c_c
[ps.orig, ps.pretty, pq.pretty, qs.orig, qs.pretty]
[ps.info, qs.info, pq.info],
pure $ pq.set_info pq_o pf
| ps@(ex.coeff ps_i x) qs := do
ps'' ← pure ps >>= prod_to_sum >>= ex_sum_b,
pqs ← ex_exp ps'' qs,
pqs_o ← pow_orig ps qs,
pf ← mk_proof_or_refl pqs.pretty ``pow_pp_pf_c
[ps.orig, ps.pretty, pqs.pretty, qs.orig, qs.pretty]
[ps.info, qs.info, pqs.info],
pqs' ← exp_to_prod pqs,
pure $ pqs'.set_info pqs_o pf
| pps@(ex.prod pps_i p ps) qs := do
pqs ← pow_e p qs,
psqs ← pow_pp ps qs,
ppsqs ← ex_prod pqs psqs,
ppsqs_o ← pow_orig pps qs,
pf ← mk_proof ``pow_pp_pf_prod
[pps.orig, p.pretty, ps.pretty, pqs.pretty, psqs.pretty, qs.orig]
[pps.info, pqs.info, psqs.info],
pure $ ppsqs.set_info ppsqs_o pf
lemma pow_p_pf_one {ps ps' : α} {qs : ℕ} : ps = ps' → qs = succ zero → ps ^ qs = ps' :=
λ ps_pf qs_pf, calc
ps ^ qs = ps' ^ 1 : by rw [ps_pf, qs_pf]
... = ps' : pow_one _
lemma pow_p_pf_zero {ps : α} {qs qs' : ℕ} : ps = 0 → qs = succ qs' → ps ^ qs = 0 :=
λ ps_pf qs_pf, calc
ps ^ qs = 0 ^ (succ qs') : by rw [ps_pf, qs_pf]
... = 0 : zero_pow (succ_pos qs')
lemma pow_p_pf_succ {ps pqqs : α} {qs qs' : ℕ} :
qs = succ qs' → ps * ps ^ qs' = pqqs → ps ^ qs = pqqs :=
λ qs_pf pqqs_pf, calc
ps ^ qs = ps ^ succ qs' : by rw [qs_pf]
... = ps * ps ^ qs' : pow_succ _ _
... = pqqs : by rw [pqqs_pf]
lemma pow_p_pf_singleton {pps p pqs : α} {qs : ℕ} :
pps = p + 0 → p ^ qs = pqs → pps ^ qs = pqs :=
λ pps_pf pqs_pf, by rw [pps_pf, add_zero, pqs_pf]
lemma pow_p_pf_cons {ps ps' : α} {qs qs' : ℕ} :
ps = ps' → qs = qs' → ps ^ qs = ps' ^ qs' := by cc
/--
Exponentiate two expressions.
* `ps ^ 1 = ps`
* `0 ^ qs = 0` (note that this is handled *after* `ps ^ 0 = 1`)
* `(p + 0) ^ qs = p ^ qs`
* `ps ^ (qs + 1) = ps * ps ^ qs` (note that this is handled *after* `p + 0 ^ qs = p ^ qs`)
* `ps ^ qs = ps ^ qs` (otherwise)
-/
meta def pow_p : ex sum → ex prod → ring_exp_m (ex sum)
| ps qs@(ex.coeff qs_i ⟨⟨1, 1, _, _⟩⟩) := do
ps_o ← pow_orig ps qs,
pf ← mk_proof ``pow_p_pf_one [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info],
pure $ ps.set_info ps_o pf
| ps@(ex.zero ps_i) qs@(ex.coeff qs_i ⟨⟨succ y, 1, _, _⟩⟩) := do
ctx ← get_context,
z ← ex_zero,
qs_pred ← lift $ expr.of_nat ctx.info_e.α y,
pf ← mk_proof ``pow_p_pf_zero [ps.orig, qs.orig, qs_pred] [ps.info, qs.info],
z_o ← pow_orig ps qs,
pure $ z.set_info z_o pf
| pps@(ex.sum pps_i p (ex.zero _)) qqs := do
pqs ← pow_pp p qqs,
pqs_o ← pow_orig pps qqs,
pf ← mk_proof ``pow_p_pf_singleton
[pps.orig, p.pretty, pqs.pretty, qqs.orig]
[pps.info, pqs.info],
prod_to_sum $ pqs.set_info pqs_o pf
| ps qs@(ex.coeff qs_i ⟨⟨int.of_nat (succ n), 1, den_pos, _⟩⟩) := do
qs' ← in_exponent $ ex_coeff ⟨int.of_nat n, 1, den_pos, coprime_one_right _⟩,
pqs ← pow_p ps qs',
pqqs ← mul ps pqs,
pqqs_o ← pow_orig ps qs,
pf ← mk_proof ``pow_p_pf_succ
[ps.orig, pqqs.pretty, qs.orig, qs'.pretty]
[qs.info, pqqs.info],
pure $ pqqs.set_info pqqs_o pf
| pps qqs := do -- fallback: treat them as atoms
pps' ← ex_sum_b pps,
psqs ← ex_exp pps' qqs,
psqs_o ← pow_orig pps qqs,
pf ← mk_proof_or_refl psqs.pretty ``pow_p_pf_cons
[pps.orig, pps.pretty, qqs.orig, qqs.pretty]
[pps.info, qqs.info],
exp_to_prod (psqs.set_info psqs_o pf) >>= prod_to_sum
lemma pow_pf_zero {ps : α} {qs : ℕ} : qs = 0 → ps ^ qs = 1 := λ qs_pf, calc
ps ^ qs = ps ^ 0 : by rw [qs_pf]
... = 1 : pow_zero _
lemma pow_pf_sum {ps psqqs : α} {qqs q qs : ℕ} : qqs = q + qs →
ps ^ q * ps ^ qs = psqqs → ps ^ qqs = psqqs := λ qqs_pf psqqs_pf, calc
ps ^ qqs = ps ^ (q + qs) : by rw [qqs_pf]
... = ps ^ q * ps ^ qs : pow_add _ _ _
... = psqqs : psqqs_pf
/--
Exponentiate two expressions.
* `ps ^ 0 = 1`
* `ps ^ (q + qs) = ps ^ q * ps ^ qs`
-/
meta def pow : ex sum → ex sum → ring_exp_m (ex sum)
| ps qs@(ex.zero qs_i) := do
o ← ex_one,
o_o ← pow_orig ps qs,
pf ← mk_proof ``pow_pf_zero [ps.orig, qs.orig] [qs.info],
prod_to_sum $ o.set_info o_o pf
| ps qqs@(ex.sum qqs_i q qs) := do
psq ← pow_p ps q,
psqs ← pow ps qs,
psqqs ← mul psq psqs,
psqqs_o ← pow_orig ps qqs,
pf ← mk_proof ``pow_pf_sum
[ps.orig, psqqs.pretty, qqs.orig, q.pretty, qs.pretty]
[qqs.info, psqqs.info],
pure $ psqqs.set_info psqqs_o pf
end exponentiation
lemma simple_pf_sum_zero {p p' : α} : p = p' → p + 0 = p' := by simp
lemma simple_pf_prod_one {p p' : α} : p = p' → p * 1 = p' := by simp
lemma simple_pf_prod_neg_one {α} [ring α] {p p' : α} : p = p' → p * -1 = - p' := by simp
lemma simple_pf_var_one (p : α) : p ^ 1 = p := by simp
lemma simple_pf_exp_one {p p' : α} : p = p' → p ^ 1 = p' := by simp
/--
Give a simpler, more human-readable representation of the normalized expression.
Normalized expressions might have the form `a^1 * 1 + 0`,
since the dummy operations reduce special cases in pattern-matching.
Humans prefer to read `a` instead.
This tactic gets rid of the dummy additions, multiplications and exponentiations.
Returns a normalized expression `e'` and a proof that `e.pretty = e'`.
-/
meta def ex.simple : Π {et : ex_type}, ex et → ring_exp_m (expr × expr)
| sum pps@(ex.sum pps_i p (ex.zero _)) := do
(p_p, p_pf) ← p.simple,
prod.mk p_p <$> mk_app_csr ``simple_pf_sum_zero [p.pretty, p_p, p_pf]
| sum (ex.sum pps_i p ps) := do
(p_p, p_pf) ← p.simple,
(ps_p, ps_pf) ← ps.simple,
prod.mk
<$> mk_add [p_p, ps_p]
<*> mk_app_csr ``sum_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf]
| prod (ex.prod pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do
(p_p, p_pf) ← p.simple,
prod.mk p_p <$> mk_app_csr ``simple_pf_prod_one [p.pretty, p_p, p_pf]
| prod pps@(ex.prod pps_i p (ex.coeff _ ⟨⟨-1, 1, _, _⟩⟩)) := do
ctx ← get_context,
match ctx.info_b.ring_instance with
| none := prod.mk pps.pretty <$> lift (mk_eq_refl pps.pretty)
| (some ringi) := do
(p_p, p_pf) ← p.simple,
prod.mk
<$> lift (mk_app ``has_neg.neg [p_p])
<*> mk_app_class ``simple_pf_prod_neg_one ringi [p.pretty, p_p, p_pf]
end
| prod (ex.prod pps_i p ps) := do
(p_p, p_pf) ← p.simple,
(ps_p, ps_pf) ← ps.simple,
prod.mk
<$> mk_mul [p_p, ps_p]
<*> mk_app_csr ``prod_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf]
| base (ex.sum_b pps_i ps) := ps.simple
| exp (ex.exp pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do
(p_p, p_pf) ← p.simple,
prod.mk p_p <$> mk_app_csr ``simple_pf_exp_one [p.pretty, p_p, p_pf]
| exp (ex.exp pps_i p ps) := do
(p_p, p_pf) ← p.simple,
(ps_p, ps_pf) ← in_exponent $ ps.simple,
prod.mk
<$> mk_pow [p_p, ps_p]
<*> mk_app_csr ``exp_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf]
| et ps := prod.mk ps.pretty <$> lift (mk_eq_refl ps.pretty)
/--
Performs a lookup of the atom `a` in the list of known atoms,
or allocates a new one.
If `a` is not definitionally equal to any of the list's entries,
a new atom is appended to the list and returned.
The index of this atom is kept track of in the second inductive argument.
This function is mostly useful in `resolve_atom`,
which updates the state with the new list of atoms.
-/
meta def resolve_atom_aux (a : expr) : list atom → ℕ → ring_exp_m (atom × list atom)
| [] n := let atm : atom := ⟨a, n⟩ in pure (atm, [atm])
| bas@(b :: as) n := do
ctx ← get_context,
(lift $ is_def_eq a b.value ctx.transp >> pure (b , bas)) <|> do
(atm, as') ← resolve_atom_aux as (succ n),
pure (atm, b :: as')
/--
Convert the expression to an atom:
either look up a definitionally equal atom,
or allocate it as a new atom.
You probably want to use `eval_base` if `eval` doesn't work
instead of directly calling `resolve_atom`,
since `eval_base` can also handle numerals.
-/
meta def resolve_atom (a : expr) : ring_exp_m atom := do
atoms ← reader_t.lift $ state_t.get,
(atm, atoms') ← resolve_atom_aux a atoms 0,
reader_t.lift $ state_t.put atoms',
pure atm
/--
Treat the expression atomically: as a coefficient or atom.
Handles cases where `eval` cannot treat the expression as a known operation
because it is just a number or single variable.
-/
meta def eval_base (ps : expr) : ring_exp_m (ex sum) :=
match ps.to_rat with
| some ⟨0, 1, _, _⟩ := ex_zero
| some x := ex_coeff x >>= prod_to_sum
| none := do
a ← resolve_atom ps,
atom_to_sum a
end
lemma negate_pf {α} [ring α] {ps ps' : α} : (-1) * ps = ps' → -ps = ps' := by simp
/--
Negate an expression by multiplying with `-1`.
Only works if there is a `ring` instance; otherwise it will `fail`.
-/
meta def negate (ps : ex sum) : ring_exp_m (ex sum) := do
ctx ← get_context,
match ctx.info_b.ring_instance with
| none := lift $ fail "internal error: negate called in semiring"
| (some ring_instance) := do
minus_one ← ex_coeff (-1) >>= prod_to_sum,
ps' ← mul minus_one ps,
ps_pf ← ps'.proof_term,
pf ← mk_app_class ``negate_pf ring_instance [ps.orig, ps'.pretty, ps_pf],
ps'_o ← lift $ mk_app ``has_neg.neg [ps.orig],
pure $ ps'.set_info ps'_o pf
end
lemma inverse_pf {α} [division_ring α] {ps ps_u ps_p e' e'' : α} :
ps = ps_u → ps_u = ps_p → ps_p ⁻¹ = e' → e' = e'' → ps ⁻¹ = e'' :=
by cc
/--
Invert an expression by simplifying, applying `has_inv.inv` and treating the result as an atom.
Only works if there is a `division_ring` instance; otherwise it will `fail`.
-/
meta def inverse (ps : ex sum) : ring_exp_m (ex sum) := do
ctx ← get_context,
dri ← match ctx.info_b.dr_instance with
| none := lift $ fail "division is only supported in a division ring"
| (some dri) := pure dri
end,
(ps_simple, ps_simple_pf) ← ps.simple,
e ← lift $ mk_app ``has_inv.inv [ps_simple],
(e', e_pf) ← lift (norm_num.derive e) <|> ((λ e_pf, (e, e_pf)) <$> lift (mk_eq_refl e)),
e'' ← eval_base e',
ps_pf ← ps.proof_term,
e''_pf ← e''.proof_term,
pf ← mk_app_class ``inverse_pf dri
[ ps.orig, ps.pretty, ps_simple, e', e''.pretty,
ps_pf, ps_simple_pf, e_pf, e''_pf],
e''_o ← lift $ mk_app ``has_inv.inv [ps.orig],
pure $ e''.set_info e''_o pf
lemma sub_pf {α} [ring α] {ps qs psqs : α} (h : ps + -qs = psqs) : ps - qs = psqs :=
by rwa sub_eq_add_neg
lemma div_pf {α} [division_ring α] {ps qs psqs : α} (h : ps * qs⁻¹ = psqs) : ps / qs = psqs :=
by rwa div_eq_mul_inv
end operations
section wiring
/-!
### `wiring` section
This section deals with going from `expr` to `ex` and back.
The main attraction is `eval`, which uses `add`, `mul`, etc.
to calculate an `ex` from a given `expr`.
Other functions use `ex`es to produce `expr`s together with a proof,
or produce the context to run `ring_exp_m` from an `expr`.
-/
open tactic
open ex_type
/--
Compute a normalized form (of type `ex`) from an expression (of type `expr`).
This is the main driver of the `ring_exp` tactic,
calling out to `add`, `mul`, `pow`, etc. to parse the `expr`.
-/
meta def eval : expr → ring_exp_m (ex sum)
| e@`(%%ps + %%qs) := do
ps' ← eval ps,
qs' ← eval qs,
add ps' qs'
| ps_o@`(nat.succ %%p_o) := do
ps' ← eval `(%%p_o + 1),
pf ← lift $ mk_app ``nat.succ_eq_add_one [p_o],
rewrite ps_o ps' pf
| e@`(%%ps - %%qs) := (do
ctx ← get_context,
ri ← match ctx.info_b.ring_instance with
| none := lift $ fail "subtraction is not directly supported in a semiring"
| (some ri) := pure ri
end,
ps' ← eval ps,
qs' ← eval qs >>= negate,
psqs ← add ps' qs',
psqs_pf ← psqs.proof_term,
pf ← mk_app_class ``sub_pf ri [ps, qs, psqs.pretty, psqs_pf],
pure (psqs.set_info e pf)) <|> eval_base e
| e@`(- %%ps) := do
ps' ← eval ps,
negate ps' <|> eval_base e
| e@`(%%ps * %%qs) := do
ps' ← eval ps,
qs' ← eval qs,
mul ps' qs'
| e@`(has_inv.inv %%ps) := do
ps' ← eval ps,
inverse ps' <|> eval_base e
| e@`(%%ps / %%qs) := do
ctx ← get_context,
dri ← match ctx.info_b.dr_instance with
| none := lift $ fail "division is only directly supported in a division ring"
| (some dri) := pure dri
end,
ps' ← eval ps,
qs' ← eval qs,
(do qs'' ← inverse qs',
psqs ← mul ps' qs'',
psqs_pf ← psqs.proof_term,
pf ← mk_app_class ``div_pf dri [ps, qs, psqs.pretty, psqs_pf],
pure (psqs.set_info e pf)) <|> eval_base e
| e@`(@has_pow.pow _ _ %%hp_instance %%ps %%qs) := do
ps' ← eval ps,
qs' ← in_exponent $ eval qs,
psqs ← pow ps' qs',
psqs_pf ← psqs.proof_term,
(do has_pow_pf ← match hp_instance with
| `(monoid.has_pow) := lift $ mk_eq_refl e
| _ := lift $ fail "has_pow instance must be nat.has_pow or monoid.has_pow"
end,
pf ← lift $ mk_eq_trans has_pow_pf psqs_pf,
pure $ psqs.set_info e pf) <|> eval_base e
| ps := eval_base ps
/--
Run `eval` on the expression and return the result together with normalization proof.
See also `eval_simple` if you want something that behaves like `norm_num`.
-/
meta def eval_with_proof (e : expr) : ring_exp_m (ex sum × expr) := do
e' ← eval e,
prod.mk e' <$> e'.proof_term
/--
Run `eval` on the expression and simplify the result.
Returns a simplified normalized expression, together with an equality proof.
See also `eval_with_proof` if you just want to check the equality of two expressions.
-/
meta def eval_simple (e : expr) : ring_exp_m (expr × expr) := do
(complicated, complicated_pf) ← eval_with_proof e,
(simple, simple_pf) ← complicated.simple,
prod.mk simple <$> lift (mk_eq_trans complicated_pf simple_pf)
/-- Compute the `eval_info` for a given type `α`. -/
meta def make_eval_info (α : expr) : tactic eval_info := do
u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
csr_instance ← mk_app ``comm_semiring [α] >>= mk_instance,
ring_instance ← (some <$> (mk_app ``ring [α] >>= mk_instance) <|> pure none),
dr_instance ← (some <$> (mk_app ``division_ring [α] >>= mk_instance) <|> pure none),
ha_instance ← mk_app ``has_add [α] >>= mk_instance,
hm_instance ← mk_app ``has_mul [α] >>= mk_instance,
hp_instance ← mk_mapp ``monoid.has_pow [some α, none],
z ← mk_mapp ``has_zero.zero [α, none],
o ← mk_mapp ``has_one.one [α, none],
pure ⟨α, u, csr_instance, ha_instance, hm_instance, hp_instance, ring_instance, dr_instance, z, o⟩
/-- Use `e` to build the context for running `mx`. -/
meta def run_ring_exp {α} (transp : transparency) (e : expr) (mx : ring_exp_m α) : tactic α := do
info_b ← infer_type e >>= make_eval_info,
info_e ← mk_const ``nat >>= make_eval_info,
(λ x : (_ × _), x.1) <$> (state_t.run (reader_t.run mx ⟨info_b, info_e, transp⟩) [])
/-- Repeatedly apply `eval_simple` on (sub)expressions. -/
meta def normalize (transp : transparency) (e : expr) : tactic (expr × expr) := do
(_, e', pf') ← ext_simplify_core () {}
simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do
(e'', pf) ← run_ring_exp transp e $ eval_simple e,
guard (¬ e'' =ₐ e),
return ((), e'', some pf, ff))
(λ _ _ _ _ _, failed) `eq e,
pure (e', pf')
end wiring
end tactic.ring_exp
namespace tactic.interactive
open interactive interactive.types lean.parser tactic tactic.ring_exp
local postfix `?`:9001 := optional
/--
Tactic for solving equations of *commutative* (semi)rings,
allowing variables in the exponent.
This version of `ring_exp` fails if the target is not an equality.
The variant `ring_exp_eq!` will use a more aggressive reducibility setting
to determine equality of atoms.
-/
meta def ring_exp_eq (red : parse (tk "!")?) : tactic unit := do
`(eq %%ps %%qs) ← target >>= whnf,
let transp := if red.is_some then semireducible else reducible,
((ps', ps_pf), (qs', qs_pf)) ← run_ring_exp transp ps $
prod.mk <$> eval_with_proof ps <*> eval_with_proof qs,
if ps'.eq qs'
then do
qs_pf_inv ← mk_eq_symm qs_pf,
pf ← mk_eq_trans ps_pf qs_pf_inv,
tactic.interactive.exact ``(%%pf)
else fail "ring_exp failed to prove equality"
/--
Tactic for evaluating expressions in *commutative* (semi)rings, allowing for variables in the
exponent.
This tactic extends `ring`: it should solve every goal that `ring` can solve.
Additionally, it knows how to evaluate expressions with complicated exponents
(where `ring` only understands constant exponents).
The variants `ring_exp!` and `ring_exp_eq!` use a more aggessive reducibility setting to determine
equality of atoms.
For example:
```lean
example (n : ℕ) (m : ℤ) : 2^(n+1) * m = 2 * 2^n * m := by ring_exp
example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring_exp
example (x y : ℕ) : x + id y = y + id x := by ring_exp!
```
-/
meta def ring_exp (red : parse (tk "!")?) (loc : parse location) : tactic unit :=
match loc with
| interactive.loc.ns [none] := ring_exp_eq red
| _ := failed
end <|>
do ns ← loc.get_locals,
let transp := if red.is_some then semireducible else reducible,
tt ← tactic.replace_at (normalize transp) ns loc.include_goal
| fail "ring_exp failed to simplify",
when loc.include_goal $ try tactic.reflexivity
add_tactic_doc
{ name := "ring_exp",
category := doc_category.tactic,
decl_names := [`tactic.interactive.ring_exp],
tags := ["arithmetic", "simplification", "decision procedure"] }
end tactic.interactive
namespace conv.interactive
open conv interactive
open tactic tactic.interactive (ring_exp_eq)
open tactic.ring_exp (normalize)
local postfix `?`:9001 := optional
/--
Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic
`ring_exp`.
-/
meta def ring_exp (red : parse (lean.parser.tk "!")?) : conv unit :=
let transp := if red.is_some then semireducible else reducible in
discharge_eq_lhs (ring_exp_eq red)
<|> replace_lhs (normalize transp)
<|> fail "ring_exp failed to simplify"
end conv.interactive
|
6cff566fb69407629ae13aebf9e5d44360807178
|
9dc8cecdf3c4634764a18254e94d43da07142918
|
/src/analysis/inner_product_space/projection.lean
|
65d4ad647837b2a9efff8945920d00a2895fa211
|
[
"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
| 57,342
|
lean
|
/-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Frédéric Dupuis, Heather Macbeth
-/
import analysis.convex.basic
import analysis.inner_product_space.symmetric
import analysis.normed_space.is_R_or_C
/-!
# The orthogonal projection
Given a nonempty complete subspace `K` of an inner product space `E`, this file constructs
`orthogonal_projection K : E →L[𝕜] K`, the orthogonal projection of `E` onto `K`. This map
satisfies: for any point `u` in `E`, the point `v = orthogonal_projection K u` in `K` minimizes the
distance `∥u - v∥` to `u`.
Also a linear isometry equivalence `reflection K : E ≃ₗᵢ[𝕜] E` is constructed, by choosing, for
each `u : E`, the point `reflection K u` to satisfy
`u + (reflection K u) = 2 • orthogonal_projection K u`.
Basic API for `orthogonal_projection` and `reflection` is developed.
Next, the orthogonal projection is used to prove a series of more subtle lemmas about the
the orthogonal complement of complete subspaces of `E` (the orthogonal complement itself was
defined in `analysis.inner_product_space.basic`); the lemma
`submodule.sup_orthogonal_of_is_complete`, stating that for a complete subspace `K` of `E` we have
`K ⊔ Kᗮ = ⊤`, is a typical example.
## References
The orthogonal projection construction is adapted from
* [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*]
* [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*]
The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html>
-/
noncomputable theory
open is_R_or_C real filter
open_locale big_operators topological_space
variables {𝕜 E F : Type*} [is_R_or_C 𝕜]
variables [inner_product_space 𝕜 E] [inner_product_space ℝ F]
local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y
local notation `absR` := has_abs.abs
/-! ### Orthogonal projection in inner product spaces -/
/--
Existence of minimizers
Let `u` be a point in a real inner product space, and let `K` be a nonempty complete convex subset.
Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`.
-/
-- FIXME this monolithic proof causes a deterministic timeout with `-T50000`
-- It should be broken in a sequence of more manageable pieces,
-- perhaps with individual statements for the three steps below.
theorem exists_norm_eq_infi_of_complete_convex {K : set F} (ne : K.nonempty) (h₁ : is_complete K)
(h₂ : convex ℝ K) : ∀ u : F, ∃ v ∈ K, ∥u - v∥ = ⨅ w : K, ∥u - w∥ := assume u,
begin
let δ := ⨅ w : K, ∥u - w∥,
letI : nonempty K := ne.to_subtype,
have zero_le_δ : 0 ≤ δ := le_cinfi (λ _, norm_nonneg _),
have δ_le : ∀ w : K, δ ≤ ∥u - w∥,
from cinfi_le ⟨0, set.forall_range_iff.2 $ λ _, norm_nonneg _⟩,
have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩,
-- Step 1: since `δ` is the infimum, can find a sequence `w : ℕ → K` in `K`
-- such that `∥u - w n∥ < δ + 1 / (n + 1)` (which implies `∥u - w n∥ --> δ`);
-- maybe this should be a separate lemma
have exists_seq : ∃ w : ℕ → K, ∀ n, ∥u - w n∥ < δ + 1 / (n + 1),
{ have hδ : ∀n:ℕ, δ < δ + 1 / (n + 1), from
λ n, lt_add_of_le_of_pos le_rfl nat.one_div_pos_of_nat,
have h := λ n, exists_lt_of_cinfi_lt (hδ n),
let w : ℕ → K := λ n, classical.some (h n),
exact ⟨w, λ n, classical.some_spec (h n)⟩ },
rcases exists_seq with ⟨w, hw⟩,
have norm_tendsto : tendsto (λ n, ∥u - w n∥) at_top (nhds δ),
{ have h : tendsto (λ n:ℕ, δ) at_top (nhds δ) := tendsto_const_nhds,
have h' : tendsto (λ n:ℕ, δ + 1 / (n + 1)) at_top (nhds δ),
{ convert h.add tendsto_one_div_add_at_top_nhds_0_nat, simp only [add_zero] },
exact tendsto_of_tendsto_of_tendsto_of_le_of_le h h'
(λ x, δ_le _) (λ x, le_of_lt (hw _)) },
-- Step 2: Prove that the sequence `w : ℕ → K` is a Cauchy sequence
have seq_is_cauchy : cauchy_seq (λ n, ((w n):F)),
{ rw cauchy_seq_iff_le_tendsto_0, -- splits into three goals
let b := λ n:ℕ, (8 * δ * (1/(n+1)) + 4 * (1/(n+1)) * (1/(n+1))),
use (λn, sqrt (b n)),
split,
-- first goal : `∀ (n : ℕ), 0 ≤ sqrt (b n)`
assume n, exact sqrt_nonneg _,
split,
-- second goal : `∀ (n m N : ℕ), N ≤ n → N ≤ m → dist ↑(w n) ↑(w m) ≤ sqrt (b N)`
assume p q N hp hq,
let wp := ((w p):F), let wq := ((w q):F),
let a := u - wq, let b := u - wp,
let half := 1 / (2:ℝ), let div := 1 / ((N:ℝ) + 1),
have : 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ =
2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) :=
calc
4 * ∥u - half•(wq + wp)∥ * ∥u - half•(wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥
= (2*∥u - half•(wq + wp)∥) * (2 * ∥u - half•(wq + wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by ring
... = (absR ((2:ℝ)) * ∥u - half•(wq + wp)∥) * (absR ((2:ℝ)) * ∥u - half•(wq+wp)∥) +
∥wp-wq∥*∥wp-wq∥ :
by { rw _root_.abs_of_nonneg, exact zero_le_two }
... = ∥(2:ℝ) • (u - half • (wq + wp))∥ * ∥(2:ℝ) • (u - half • (wq + wp))∥ +
∥wp-wq∥ * ∥wp-wq∥ :
by simp [norm_smul]
... = ∥a + b∥ * ∥a + b∥ + ∥a - b∥ * ∥a - b∥ :
begin
rw [smul_sub, smul_smul, mul_one_div_cancel (_root_.two_ne_zero : (2 : ℝ) ≠ 0),
← one_add_one_eq_two, add_smul],
simp only [one_smul],
have eq₁ : wp - wq = a - b, from (sub_sub_sub_cancel_left _ _ _).symm,
have eq₂ : u + u - (wq + wp) = a + b, show u + u - (wq + wp) = (u - wq) + (u - wp), abel,
rw [eq₁, eq₂],
end
... = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) : parallelogram_law_with_norm _ _,
have eq : δ ≤ ∥u - half • (wq + wp)∥,
{ rw smul_add,
apply δ_le', apply h₂,
repeat {exact subtype.mem _},
repeat {exact le_of_lt one_half_pos},
exact add_halves 1 },
have eq₁ : 4 * δ * δ ≤ 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥,
{ mono, mono, norm_num, apply mul_nonneg, norm_num, exact norm_nonneg _ },
have eq₂ : ∥a∥ * ∥a∥ ≤ (δ + div) * (δ + div) :=
mul_self_le_mul_self (norm_nonneg _)
(le_trans (le_of_lt $ hw q) (add_le_add_left (nat.one_div_le_one_div hq) _)),
have eq₂' : ∥b∥ * ∥b∥ ≤ (δ + div) * (δ + div) :=
mul_self_le_mul_self (norm_nonneg _)
(le_trans (le_of_lt $ hw p) (add_le_add_left (nat.one_div_le_one_div hp) _)),
rw dist_eq_norm,
apply nonneg_le_nonneg_of_sq_le_sq, { exact sqrt_nonneg _ },
rw mul_self_sqrt,
calc
∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥*∥a∥ + ∥b∥*∥b∥) -
4 * ∥u - half • (wq+wp)∥ * ∥u - half • (wq+wp)∥ : by { rw ← this, simp }
... ≤ 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) - 4 * δ * δ : sub_le_sub_left eq₁ _
... ≤ 2 * ((δ + div) * (δ + div) + (δ + div) * (δ + div)) - 4 * δ * δ :
sub_le_sub_right (mul_le_mul_of_nonneg_left (add_le_add eq₂ eq₂') (by norm_num)) _
... = 8 * δ * div + 4 * div * div : by ring,
exact add_nonneg
(mul_nonneg (mul_nonneg (by norm_num) zero_le_δ) (le_of_lt nat.one_div_pos_of_nat))
(mul_nonneg (mul_nonneg (by norm_num) nat.one_div_pos_of_nat.le) nat.one_div_pos_of_nat.le),
-- third goal : `tendsto (λ (n : ℕ), sqrt (b n)) at_top (𝓝 0)`
apply tendsto.comp,
{ convert continuous_sqrt.continuous_at, exact sqrt_zero.symm },
have eq₁ : tendsto (λ (n : ℕ), 8 * δ * (1 / (n + 1))) at_top (nhds (0:ℝ)),
{ convert (@tendsto_const_nhds _ _ _ (8 * δ) _).mul tendsto_one_div_add_at_top_nhds_0_nat,
simp only [mul_zero] },
have : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1))) at_top (nhds (0:ℝ)),
{ convert (@tendsto_const_nhds _ _ _ (4:ℝ) _).mul tendsto_one_div_add_at_top_nhds_0_nat,
simp only [mul_zero] },
have eq₂ : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1)) * (1 / (n + 1))) at_top (nhds (0:ℝ)),
{ convert this.mul tendsto_one_div_add_at_top_nhds_0_nat,
simp only [mul_zero] },
convert eq₁.add eq₂, simp only [add_zero] },
-- Step 3: By completeness of `K`, let `w : ℕ → K` converge to some `v : K`.
-- Prove that it satisfies all requirements.
rcases cauchy_seq_tendsto_of_is_complete h₁ (λ n, _) seq_is_cauchy with ⟨v, hv, w_tendsto⟩,
use v, use hv,
have h_cont : continuous (λ v, ∥u - v∥) :=
continuous.comp continuous_norm (continuous.sub continuous_const continuous_id),
have : tendsto (λ n, ∥u - w n∥) at_top (nhds ∥u - v∥),
convert (tendsto.comp h_cont.continuous_at w_tendsto),
exact tendsto_nhds_unique this norm_tendsto,
exact subtype.mem _
end
/-- Characterization of minimizers for the projection on a convex set in a real inner product
space. -/
theorem norm_eq_infi_iff_real_inner_le_zero {K : set F} (h : convex ℝ K) {u : F} {v : F}
(hv : v ∈ K) : ∥u - v∥ = (⨅ w : K, ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0 :=
iff.intro
begin
assume eq w hw,
let δ := ⨅ w : K, ∥u - w∥, let p := ⟪u - v, w - v⟫_ℝ, let q := ∥w - v∥^2,
letI : nonempty K := ⟨⟨v, hv⟩⟩,
have zero_le_δ : 0 ≤ δ,
apply le_cinfi, intro, exact norm_nonneg _,
have δ_le : ∀ w : K, δ ≤ ∥u - w∥,
assume w, apply cinfi_le, use (0:ℝ), rintros _ ⟨_, rfl⟩, exact norm_nonneg _,
have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩,
have : ∀θ:ℝ, 0 < θ → θ ≤ 1 → 2 * p ≤ θ * q,
assume θ hθ₁ hθ₂,
have : ∥u - v∥^2 ≤ ∥u - v∥^2 - 2 * θ * ⟪u - v, w - v⟫_ℝ + θ*θ*∥w - v∥^2 :=
calc
∥u - v∥^2 ≤ ∥u - (θ•w + (1-θ)•v)∥^2 :
begin
simp only [sq], apply mul_self_le_mul_self (norm_nonneg _),
rw [eq], apply δ_le',
apply h hw hv,
exacts [le_of_lt hθ₁, sub_nonneg.2 hθ₂, add_sub_cancel'_right _ _],
end
... = ∥(u - v) - θ • (w - v)∥^2 :
begin
have : u - (θ•w + (1-θ)•v) = (u - v) - θ • (w - v),
{ rw [smul_sub, sub_smul, one_smul],
simp only [sub_eq_add_neg, add_comm, add_left_comm, add_assoc, neg_add_rev] },
rw this
end
... = ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 :
begin
rw [norm_sub_sq, inner_smul_right, norm_smul],
simp only [sq],
show ∥u-v∥*∥u-v∥-2*(θ*inner(u-v)(w-v))+absR (θ)*∥w-v∥*(absR (θ)*∥w-v∥)=
∥u-v∥*∥u-v∥-2*θ*inner(u-v)(w-v)+θ*θ*(∥w-v∥*∥w-v∥),
rw abs_of_pos hθ₁, ring
end,
have eq₁ : ∥u-v∥^2-2*θ*inner(u-v)(w-v)+θ*θ*∥w-v∥^2=∥u-v∥^2+(θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)),
by abel,
rw [eq₁, le_add_iff_nonneg_right] at this,
have eq₂ : θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)=θ*(θ*∥w-v∥^2-2*inner(u-v)(w-v)), ring,
rw eq₂ at this,
have := le_of_sub_nonneg (nonneg_of_mul_nonneg_right this hθ₁),
exact this,
by_cases hq : q = 0,
{ rw hq at this,
have : p ≤ 0,
have := this (1:ℝ) (by norm_num) (by norm_num),
linarith,
exact this },
{ have q_pos : 0 < q,
apply lt_of_le_of_ne, exact sq_nonneg _, intro h, exact hq h.symm,
by_contradiction hp, rw not_le at hp,
let θ := min (1:ℝ) (p / q),
have eq₁ : θ*q ≤ p := calc
θ*q ≤ (p/q) * q : mul_le_mul_of_nonneg_right (min_le_right _ _) (sq_nonneg _)
... = p : div_mul_cancel _ hq,
have : 2 * p ≤ p := calc
2 * p ≤ θ*q : by { refine this θ (lt_min (by norm_num) (div_pos hp q_pos)) (by norm_num) }
... ≤ p : eq₁,
linarith }
end
begin
assume h,
letI : nonempty K := ⟨⟨v, hv⟩⟩,
apply le_antisymm,
{ apply le_cinfi, assume w,
apply nonneg_le_nonneg_of_sq_le_sq (norm_nonneg _),
have := h w w.2,
calc
∥u - v∥ * ∥u - v∥ ≤ ∥u - v∥ * ∥u - v∥ - 2 * inner (u - v) ((w:F) - v) : by linarith
... ≤ ∥u - v∥^2 - 2 * inner (u - v) ((w:F) - v) + ∥(w:F) - v∥^2 :
by { rw sq, refine le_add_of_nonneg_right _, exact sq_nonneg _ }
... = ∥(u - v) - (w - v)∥^2 : norm_sub_sq.symm
... = ∥u - w∥ * ∥u - w∥ :
by { have : (u - v) - (w - v) = u - w, abel, rw [this, sq] } },
{ show (⨅ (w : K), ∥u - w∥) ≤ (λw:K, ∥u - w∥) ⟨v, hv⟩,
apply cinfi_le, use 0, rintros y ⟨z, rfl⟩, exact norm_nonneg _ }
end
variables (K : submodule 𝕜 E)
/--
Existence of projections on complete subspaces.
Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace.
Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`.
This point `v` is usually called the orthogonal projection of `u` onto `K`.
-/
theorem exists_norm_eq_infi_of_complete_subspace
(h : is_complete (↑K : set E)) : ∀ u : E, ∃ v ∈ K, ∥u - v∥ = ⨅ w : (K : set E), ∥u - w∥ :=
begin
letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E,
letI : module ℝ E := restrict_scalars.module ℝ 𝕜 E,
let K' : submodule ℝ E := submodule.restrict_scalars ℝ K,
exact exists_norm_eq_infi_of_complete_convex ⟨0, K'.zero_mem⟩ h K'.convex
end
/--
Characterization of minimizers in the projection on a subspace, in the real case.
Let `u` be a point in a real inner product space, and let `K` be a nonempty subspace.
Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if
for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`).
This is superceded by `norm_eq_infi_iff_inner_eq_zero` that gives the same conclusion over
any `is_R_or_C` field.
-/
theorem norm_eq_infi_iff_real_inner_eq_zero (K : submodule ℝ F) {u : F} {v : F}
(hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set F), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫_ℝ = 0 :=
iff.intro
begin
assume h,
have h : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0,
{ rwa [norm_eq_infi_iff_real_inner_le_zero] at h, exacts [K.convex, hv] },
assume w hw,
have le : ⟪u - v, w⟫_ℝ ≤ 0,
let w' := w + v,
have : w' ∈ K := submodule.add_mem _ hw hv,
have h₁ := h w' this,
have h₂ : w' - v = w, simp only [add_neg_cancel_right, sub_eq_add_neg],
rw h₂ at h₁, exact h₁,
have ge : ⟪u - v, w⟫_ℝ ≥ 0,
let w'' := -w + v,
have : w'' ∈ K := submodule.add_mem _ (submodule.neg_mem _ hw) hv,
have h₁ := h w'' this,
have h₂ : w'' - v = -w, simp only [neg_inj, add_neg_cancel_right, sub_eq_add_neg],
rw [h₂, inner_neg_right] at h₁,
linarith,
exact le_antisymm le ge
end
begin
assume h,
have : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0,
assume w hw,
let w' := w - v,
have : w' ∈ K := submodule.sub_mem _ hw hv,
have h₁ := h w' this,
exact le_of_eq h₁,
rwa norm_eq_infi_iff_real_inner_le_zero,
exacts [submodule.convex _, hv]
end
/--
Characterization of minimizers in the projection on a subspace.
Let `u` be a point in an inner product space, and let `K` be a nonempty subspace.
Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if
for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`)
-/
theorem norm_eq_infi_iff_inner_eq_zero {u : E} {v : E}
(hv : v ∈ K) : ∥u - v∥ = (⨅ w : K, ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫ = 0 :=
begin
letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E,
letI : module ℝ E := restrict_scalars.module ℝ 𝕜 E,
let K' : submodule ℝ E := K.restrict_scalars ℝ,
split,
{ assume H,
have A : ∀ w ∈ K, re ⟪u - v, w⟫ = 0 := (norm_eq_infi_iff_real_inner_eq_zero K' hv).1 H,
assume w hw,
apply ext,
{ simp [A w hw] },
{ symmetry, calc
im (0 : 𝕜) = 0 : im.map_zero
... = re ⟪u - v, (-I) • w⟫ : (A _ (K.smul_mem (-I) hw)).symm
... = re ((-I) * ⟪u - v, w⟫) : by rw inner_smul_right
... = im ⟪u - v, w⟫ : by simp } },
{ assume H,
have : ∀ w ∈ K', ⟪u - v, w⟫_ℝ = 0,
{ assume w hw,
rw [real_inner_eq_re_inner, H w hw],
exact zero_re' },
exact (norm_eq_infi_iff_real_inner_eq_zero K' hv).2 this }
end
section orthogonal_projection
variables [complete_space K]
/-- The orthogonal projection onto a complete subspace, as an
unbundled function. This definition is only intended for use in
setting up the bundled version `orthogonal_projection` and should not
be used once that is defined. -/
def orthogonal_projection_fn (v : E) :=
(exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some
variables {K}
/-- The unbundled orthogonal projection is in the given subspace.
This lemma is only intended for use in setting up the bundled version
and should not be used once that is defined. -/
lemma orthogonal_projection_fn_mem (v : E) : orthogonal_projection_fn K v ∈ K :=
(exists_norm_eq_infi_of_complete_subspace K
(complete_space_coe_iff_is_complete.mp ‹_›) v).some_spec.some
/-- The characterization of the unbundled orthogonal projection. This
lemma is only intended for use in setting up the bundled version
and should not be used once that is defined. -/
lemma orthogonal_projection_fn_inner_eq_zero (v : E) :
∀ w ∈ K, ⟪v - orthogonal_projection_fn K v, w⟫ = 0 :=
begin
rw ←norm_eq_infi_iff_inner_eq_zero K (orthogonal_projection_fn_mem v),
exact (exists_norm_eq_infi_of_complete_subspace K
(complete_space_coe_iff_is_complete.mp ‹_›) v).some_spec.some_spec
end
/-- The unbundled orthogonal projection is the unique point in `K`
with the orthogonality property. This lemma is only intended for use
in setting up the bundled version and should not be used once that is
defined. -/
lemma eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero
{u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) :
orthogonal_projection_fn K u = v :=
begin
rw [←sub_eq_zero, ←inner_self_eq_zero],
have hvs : orthogonal_projection_fn K u - v ∈ K :=
submodule.sub_mem K (orthogonal_projection_fn_mem u) hvm,
have huo : ⟪u - orthogonal_projection_fn K u, orthogonal_projection_fn K u - v⟫ = 0 :=
orthogonal_projection_fn_inner_eq_zero u _ hvs,
have huv : ⟪u - v, orthogonal_projection_fn K u - v⟫ = 0 := hvo _ hvs,
have houv : ⟪(u - v) - (u - orthogonal_projection_fn K u), orthogonal_projection_fn K u - v⟫ = 0,
{ rw [inner_sub_left, huo, huv, sub_zero] },
rwa sub_sub_sub_cancel_left at houv
end
variables (K)
lemma orthogonal_projection_fn_norm_sq (v : E) :
∥v∥ * ∥v∥ = ∥v - (orthogonal_projection_fn K v)∥ * ∥v - (orthogonal_projection_fn K v)∥
+ ∥orthogonal_projection_fn K v∥ * ∥orthogonal_projection_fn K v∥ :=
begin
set p := orthogonal_projection_fn K v,
have h' : ⟪v - p, p⟫ = 0,
{ exact orthogonal_projection_fn_inner_eq_zero _ _ (orthogonal_projection_fn_mem v) },
convert norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (v - p) p h' using 2;
simp,
end
/-- The orthogonal projection onto a complete subspace. -/
def orthogonal_projection : E →L[𝕜] K :=
linear_map.mk_continuous
{ to_fun := λ v, ⟨orthogonal_projection_fn K v, orthogonal_projection_fn_mem v⟩,
map_add' := λ x y, begin
have hm : orthogonal_projection_fn K x + orthogonal_projection_fn K y ∈ K :=
submodule.add_mem K (orthogonal_projection_fn_mem x) (orthogonal_projection_fn_mem y),
have ho :
∀ w ∈ K, ⟪x + y - (orthogonal_projection_fn K x + orthogonal_projection_fn K y), w⟫ = 0,
{ intros w hw,
rw [add_sub_add_comm, inner_add_left, orthogonal_projection_fn_inner_eq_zero _ w hw,
orthogonal_projection_fn_inner_eq_zero _ w hw, add_zero] },
ext,
simp [eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hm ho]
end,
map_smul' := λ c x, begin
have hm : c • orthogonal_projection_fn K x ∈ K :=
submodule.smul_mem K _ (orthogonal_projection_fn_mem x),
have ho : ∀ w ∈ K, ⟪c • x - c • orthogonal_projection_fn K x, w⟫ = 0,
{ intros w hw,
rw [←smul_sub, inner_smul_left, orthogonal_projection_fn_inner_eq_zero _ w hw, mul_zero] },
ext,
simp [eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hm ho]
end }
1
(λ x, begin
simp only [one_mul, linear_map.coe_mk],
refine le_of_pow_le_pow 2 (norm_nonneg _) (by norm_num) _,
change ∥orthogonal_projection_fn K x∥ ^ 2 ≤ ∥x∥ ^ 2,
nlinarith [orthogonal_projection_fn_norm_sq K x]
end)
variables {K}
@[simp]
lemma orthogonal_projection_fn_eq (v : E) :
orthogonal_projection_fn K v = (orthogonal_projection K v : E) :=
rfl
/-- The characterization of the orthogonal projection. -/
@[simp]
lemma orthogonal_projection_inner_eq_zero (v : E) :
∀ w ∈ K, ⟪v - orthogonal_projection K v, w⟫ = 0 :=
orthogonal_projection_fn_inner_eq_zero v
/-- The difference of `v` from its orthogonal projection onto `K` is in `Kᗮ`. -/
@[simp] lemma sub_orthogonal_projection_mem_orthogonal (v : E) :
v - orthogonal_projection K v ∈ Kᗮ :=
begin
intros w hw,
rw inner_eq_zero_sym,
exact orthogonal_projection_inner_eq_zero _ _ hw
end
/-- The orthogonal projection is the unique point in `K` with the
orthogonality property. -/
lemma eq_orthogonal_projection_of_mem_of_inner_eq_zero
{u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) :
(orthogonal_projection K u : E) = v :=
eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hvm hvo
/-- The orthogonal projection of `y` on `U` minimizes the distance `∥y - x∥` for `x ∈ U`. -/
lemma orthogonal_projection_minimal {U : submodule 𝕜 E} [complete_space U] (y : E) :
∥y - orthogonal_projection U y∥ = ⨅ x : U, ∥y - x∥ :=
begin
rw norm_eq_infi_iff_inner_eq_zero _ (submodule.coe_mem _),
exact orthogonal_projection_inner_eq_zero _
end
/-- The orthogonal projections onto equal subspaces are coerced back to the same point in `E`. -/
lemma eq_orthogonal_projection_of_eq_submodule
{K' : submodule 𝕜 E} [complete_space K'] (h : K = K') (u : E) :
(orthogonal_projection K u : E) = (orthogonal_projection K' u : E) :=
begin
change orthogonal_projection_fn K u = orthogonal_projection_fn K' u,
congr,
exact h
end
/-- The orthogonal projection sends elements of `K` to themselves. -/
@[simp] lemma orthogonal_projection_mem_subspace_eq_self (v : K) : orthogonal_projection K v = v :=
by { ext, apply eq_orthogonal_projection_of_mem_of_inner_eq_zero; simp }
/-- A point equals its orthogonal projection if and only if it lies in the subspace. -/
lemma orthogonal_projection_eq_self_iff {v : E} :
(orthogonal_projection K v : E) = v ↔ v ∈ K :=
begin
refine ⟨λ h, _, λ h, eq_orthogonal_projection_of_mem_of_inner_eq_zero h _⟩,
{ rw ← h,
simp },
{ simp }
end
lemma linear_isometry.map_orthogonal_projection {E E' : Type*} [inner_product_space 𝕜 E]
[inner_product_space 𝕜 E'] (f : E →ₗᵢ[𝕜] E') (p : submodule 𝕜 E) [complete_space p]
(x : E) :
f (orthogonal_projection p x) = orthogonal_projection (p.map f.to_linear_map) (f x) :=
begin
refine (eq_orthogonal_projection_of_mem_of_inner_eq_zero _ $
λ y hy, _).symm,
refine submodule.apply_coe_mem_map _ _,
rcases hy with ⟨x', hx', rfl : f x' = y⟩,
rw [← f.map_sub, f.inner_map_map, orthogonal_projection_inner_eq_zero x x' hx']
end
lemma linear_isometry.map_orthogonal_projection' {E E' : Type*} [inner_product_space 𝕜 E]
[inner_product_space 𝕜 E'] (f : E →ₗᵢ[𝕜] E') (p : submodule 𝕜 E) [complete_space p]
(x : E) :
f (orthogonal_projection p x) = orthogonal_projection (p.map f) (f x) :=
begin
refine (eq_orthogonal_projection_of_mem_of_inner_eq_zero _ $
λ y hy, _).symm,
refine submodule.apply_coe_mem_map _ _,
rcases hy with ⟨x', hx', rfl : f x' = y⟩,
rw [← f.map_sub, f.inner_map_map, orthogonal_projection_inner_eq_zero x x' hx']
end
/-- Orthogonal projection onto the `submodule.map` of a subspace. -/
lemma orthogonal_projection_map_apply {E E' : Type*} [inner_product_space 𝕜 E]
[inner_product_space 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') (p : submodule 𝕜 E) [complete_space p]
(x : E') :
(orthogonal_projection (p.map (f.to_linear_equiv : E →ₗ[𝕜] E')) x : E')
= f (orthogonal_projection p (f.symm x)) :=
by simpa only [f.coe_to_linear_isometry, f.apply_symm_apply]
using (f.to_linear_isometry.map_orthogonal_projection p (f.symm x)).symm
/-- The orthogonal projection onto the trivial submodule is the zero map. -/
@[simp] lemma orthogonal_projection_bot : orthogonal_projection (⊥ : submodule 𝕜 E) = 0 :=
by ext
variables (K)
/-- The orthogonal projection has norm `≤ 1`. -/
lemma orthogonal_projection_norm_le : ∥orthogonal_projection K∥ ≤ 1 :=
linear_map.mk_continuous_norm_le _ (by norm_num) _
variables (𝕜)
lemma smul_orthogonal_projection_singleton {v : E} (w : E) :
(∥v∥ ^ 2 : 𝕜) • (orthogonal_projection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v :=
begin
suffices : ↑(orthogonal_projection (𝕜 ∙ v) ((∥v∥ ^ 2 : 𝕜) • w)) = ⟪v, w⟫ • v,
{ simpa using this },
apply eq_orthogonal_projection_of_mem_of_inner_eq_zero,
{ rw submodule.mem_span_singleton,
use ⟪v, w⟫ },
{ intros x hx,
obtain ⟨c, rfl⟩ := submodule.mem_span_singleton.mp hx,
have hv : ↑∥v∥ ^ 2 = ⟪v, v⟫ := by { norm_cast, simp [norm_sq_eq_inner] },
simp [inner_sub_left, inner_smul_left, inner_smul_right, map_div₀, mul_comm, hv,
inner_product_space.conj_sym, hv] }
end
/-- Formula for orthogonal projection onto a single vector. -/
lemma orthogonal_projection_singleton {v : E} (w : E) :
(orthogonal_projection (𝕜 ∙ v) w : E) = (⟪v, w⟫ / ∥v∥ ^ 2) • v :=
begin
by_cases hv : v = 0,
{ rw [hv, eq_orthogonal_projection_of_eq_submodule (submodule.span_zero_singleton 𝕜)],
{ simp },
{ apply_instance } },
have hv' : ∥v∥ ≠ 0 := ne_of_gt (norm_pos_iff.mpr hv),
have key : ((∥v∥ ^ 2 : 𝕜)⁻¹ * ∥v∥ ^ 2) • ↑(orthogonal_projection (𝕜 ∙ v) w)
= ((∥v∥ ^ 2 : 𝕜)⁻¹ * ⟪v, w⟫) • v,
{ simp [mul_smul, smul_orthogonal_projection_singleton 𝕜 w] },
convert key;
field_simp [hv']
end
/-- Formula for orthogonal projection onto a single unit vector. -/
lemma orthogonal_projection_unit_singleton {v : E} (hv : ∥v∥ = 1) (w : E) :
(orthogonal_projection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v :=
by { rw ← smul_orthogonal_projection_singleton 𝕜 w, simp [hv] }
end orthogonal_projection
section reflection
variables {𝕜} (K) [complete_space K]
/-- Auxiliary definition for `reflection`: the reflection as a linear equivalence. -/
def reflection_linear_equiv : E ≃ₗ[𝕜] E :=
linear_equiv.of_involutive
(bit0 (K.subtype.comp (orthogonal_projection K).to_linear_map) - linear_map.id)
(λ x, by simp [bit0])
/-- Reflection in a complete subspace of an inner product space. The word "reflection" is
sometimes understood to mean specifically reflection in a codimension-one subspace, and sometimes
more generally to cover operations such as reflection in a point. The definition here, of
reflection in a subspace, is a more general sense of the word that includes both those common
cases. -/
def reflection : E ≃ₗᵢ[𝕜] E :=
{ norm_map' := begin
intros x,
let w : K := orthogonal_projection K x,
let v := x - w,
have : ⟪v, w⟫ = 0 := orthogonal_projection_inner_eq_zero x w w.2,
convert norm_sub_eq_norm_add this using 2,
{ rw [linear_equiv.coe_mk, reflection_linear_equiv,
linear_equiv.to_fun_eq_coe, linear_equiv.coe_of_involutive,
linear_map.sub_apply, linear_map.id_apply, bit0, linear_map.add_apply,
linear_map.comp_apply, submodule.subtype_apply,
continuous_linear_map.to_linear_map_eq_coe, continuous_linear_map.coe_coe],
dsimp [w, v],
abel, },
{ simp only [add_sub_cancel'_right, eq_self_iff_true], }
end,
..reflection_linear_equiv K }
variables {K}
/-- The result of reflecting. -/
lemma reflection_apply (p : E) : reflection K p = bit0 ↑(orthogonal_projection K p) - p := rfl
/-- Reflection is its own inverse. -/
@[simp] lemma reflection_symm : (reflection K).symm = reflection K := rfl
/-- Reflection is its own inverse. -/
@[simp] lemma reflection_inv : (reflection K)⁻¹ = reflection K := rfl
variables (K)
/-- Reflecting twice in the same subspace. -/
@[simp] lemma reflection_reflection (p : E) : reflection K (reflection K p) = p :=
(reflection K).left_inv p
/-- Reflection is involutive. -/
lemma reflection_involutive : function.involutive (reflection K) := reflection_reflection K
/-- Reflection is involutive. -/
@[simp] lemma reflection_trans_reflection :
(reflection K).trans (reflection K) = linear_isometry_equiv.refl 𝕜 E :=
linear_isometry_equiv.ext $ reflection_involutive K
/-- Reflection is involutive. -/
@[simp] lemma reflection_mul_reflection : reflection K * reflection K = 1 :=
reflection_trans_reflection _
variables {K}
/-- A point is its own reflection if and only if it is in the subspace. -/
lemma reflection_eq_self_iff (x : E) : reflection K x = x ↔ x ∈ K :=
begin
rw [←orthogonal_projection_eq_self_iff, reflection_apply, sub_eq_iff_eq_add', ← two_smul 𝕜,
← two_smul' 𝕜],
refine (smul_right_injective E _).eq_iff,
exact two_ne_zero
end
lemma reflection_mem_subspace_eq_self {x : E} (hx : x ∈ K) : reflection K x = x :=
(reflection_eq_self_iff x).mpr hx
/-- Reflection in the `submodule.map` of a subspace. -/
lemma reflection_map_apply {E E' : Type*} [inner_product_space 𝕜 E] [inner_product_space 𝕜 E']
(f : E ≃ₗᵢ[𝕜] E') (K : submodule 𝕜 E) [complete_space K] (x : E') :
reflection (K.map (f.to_linear_equiv : E →ₗ[𝕜] E')) x = f (reflection K (f.symm x)) :=
by simp [bit0, reflection_apply, orthogonal_projection_map_apply f K x]
/-- Reflection in the `submodule.map` of a subspace. -/
lemma reflection_map {E E' : Type*} [inner_product_space 𝕜 E] [inner_product_space 𝕜 E']
(f : E ≃ₗᵢ[𝕜] E') (K : submodule 𝕜 E) [complete_space K] :
reflection (K.map (f.to_linear_equiv : E →ₗ[𝕜] E')) = f.symm.trans ((reflection K).trans f) :=
linear_isometry_equiv.ext $ reflection_map_apply f K
/-- Reflection through the trivial subspace {0} is just negation. -/
@[simp] lemma reflection_bot : reflection (⊥ : submodule 𝕜 E) = linear_isometry_equiv.neg 𝕜 :=
by ext; simp [reflection_apply]
end reflection
section orthogonal
/-- If `K₁` is complete and contained in `K₂`, `K₁` and `K₁ᗮ ⊓ K₂` span `K₂`. -/
lemma submodule.sup_orthogonal_inf_of_complete_space {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂)
[complete_space K₁] : K₁ ⊔ (K₁ᗮ ⊓ K₂) = K₂ :=
begin
ext x,
rw submodule.mem_sup,
let v : K₁ := orthogonal_projection K₁ x,
have hvm : x - v ∈ K₁ᗮ := sub_orthogonal_projection_mem_orthogonal x,
split,
{ rintro ⟨y, hy, z, hz, rfl⟩,
exact K₂.add_mem (h hy) hz.2 },
{ exact λ hx, ⟨v, v.prop, x - v, ⟨hvm, K₂.sub_mem hx (h v.prop)⟩, add_sub_cancel'_right _ _⟩ }
end
variables {K}
/-- If `K` is complete, `K` and `Kᗮ` span the whole space. -/
lemma submodule.sup_orthogonal_of_complete_space [complete_space K] : K ⊔ Kᗮ = ⊤ :=
begin
convert submodule.sup_orthogonal_inf_of_complete_space (le_top : K ≤ ⊤),
simp
end
variables (K)
/-- If `K` is complete, any `v` in `E` can be expressed as a sum of elements of `K` and `Kᗮ`. -/
lemma submodule.exists_sum_mem_mem_orthogonal [complete_space K] (v : E) :
∃ (y ∈ K) (z ∈ Kᗮ), v = y + z :=
begin
have h_mem : v ∈ K ⊔ Kᗮ := by simp [submodule.sup_orthogonal_of_complete_space],
obtain ⟨y, hy, z, hz, hyz⟩ := submodule.mem_sup.mp h_mem,
exact ⟨y, hy, z, hz, hyz.symm⟩
end
/-- If `K` is complete, then the orthogonal complement of its orthogonal complement is itself. -/
@[simp] lemma submodule.orthogonal_orthogonal [complete_space K] : Kᗮᗮ = K :=
begin
ext v,
split,
{ obtain ⟨y, hy, z, hz, rfl⟩ := K.exists_sum_mem_mem_orthogonal v,
intros hv,
have hz' : z = 0,
{ have hyz : ⟪z, y⟫ = 0 := by simp [hz y hy, inner_eq_zero_sym],
simpa [inner_add_right, hyz] using hv z hz },
simp [hy, hz'] },
{ intros hv w hw,
rw inner_eq_zero_sym,
exact hw v hv }
end
lemma submodule.orthogonal_orthogonal_eq_closure [complete_space E] :
Kᗮᗮ = K.topological_closure :=
begin
refine le_antisymm _ _,
{ convert submodule.orthogonal_orthogonal_monotone K.submodule_topological_closure,
haveI : complete_space K.topological_closure :=
K.is_closed_topological_closure.complete_space_coe,
rw K.topological_closure.orthogonal_orthogonal },
{ exact K.topological_closure_minimal K.le_orthogonal_orthogonal Kᗮ.is_closed_orthogonal }
end
variables {K}
/-- If `K` is complete, `K` and `Kᗮ` are complements of each other. -/
lemma submodule.is_compl_orthogonal_of_complete_space [complete_space K] : is_compl K Kᗮ :=
⟨K.orthogonal_disjoint, le_of_eq submodule.sup_orthogonal_of_complete_space.symm⟩
@[simp] lemma submodule.orthogonal_eq_bot_iff [complete_space (K : set E)] :
Kᗮ = ⊥ ↔ K = ⊤ :=
begin
refine ⟨_, λ h, by rw [h, submodule.top_orthogonal_eq_bot] ⟩,
intro h,
have : K ⊔ Kᗮ = ⊤ := submodule.sup_orthogonal_of_complete_space,
rwa [h, sup_comm, bot_sup_eq] at this,
end
/-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the
orthogonal projection. -/
lemma eq_orthogonal_projection_of_mem_orthogonal
[complete_space K] {u v : E} (hv : v ∈ K) (hvo : u - v ∈ Kᗮ) :
(orthogonal_projection K u : E) = v :=
eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hv (λ w, inner_eq_zero_sym.mp ∘ (hvo w))
/-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the
orthogonal projection. -/
lemma eq_orthogonal_projection_of_mem_orthogonal'
[complete_space K] {u v z : E} (hv : v ∈ K) (hz : z ∈ Kᗮ) (hu : u = v + z) :
(orthogonal_projection K u : E) = v :=
eq_orthogonal_projection_of_mem_orthogonal hv (by simpa [hu])
/-- The orthogonal projection onto `K` of an element of `Kᗮ` is zero. -/
lemma orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero
[complete_space K] {v : E} (hv : v ∈ Kᗮ) :
orthogonal_projection K v = 0 :=
by { ext, convert eq_orthogonal_projection_of_mem_orthogonal _ _; simp [hv] }
/-- The reflection in `K` of an element of `Kᗮ` is its negation. -/
lemma reflection_mem_subspace_orthogonal_complement_eq_neg
[complete_space K] {v : E} (hv : v ∈ Kᗮ) :
reflection K v = - v :=
by simp [reflection_apply, orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero hv]
/-- The orthogonal projection onto `Kᗮ` of an element of `K` is zero. -/
lemma orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero
[complete_space E] {v : E} (hv : v ∈ K) :
orthogonal_projection Kᗮ v = 0 :=
orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero (K.le_orthogonal_orthogonal hv)
/-- If `U ≤ V`, then projecting on `V` and then on `U` is the same as projecting on `U`. -/
lemma orthogonal_projection_orthogonal_projection_of_le {U V : submodule 𝕜 E} [complete_space U]
[complete_space V] (h : U ≤ V) (x : E) :
orthogonal_projection U (orthogonal_projection V x) = orthogonal_projection U x :=
eq.symm $ by simpa only [sub_eq_zero, map_sub] using
orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero
(submodule.orthogonal_le h (sub_orthogonal_projection_mem_orthogonal x))
/-- Given a monotone family `U` of complete submodules of `E` and a fixed `x : E`,
the orthogonal projection of `x` on `U i` tends to the orthogonal projection of `x` on
`(⨆ i, U i).topological_closure` along `at_top`. -/
lemma orthogonal_projection_tendsto_closure_supr [complete_space E] {ι : Type*}
[semilattice_sup ι] (U : ι → submodule 𝕜 E) [∀ i, complete_space (U i)]
(hU : monotone U) (x : E) :
filter.tendsto (λ i, (orthogonal_projection (U i) x : E)) at_top
(𝓝 (orthogonal_projection (⨆ i, U i).topological_closure x : E)) :=
begin
casesI is_empty_or_nonempty ι,
{ rw filter_eq_bot_of_is_empty (at_top : filter ι),
exact tendsto_bot },
let y := (orthogonal_projection (⨆ i, U i).topological_closure x : E),
have proj_x : ∀ i, orthogonal_projection (U i) x = orthogonal_projection (U i) y :=
λ i, (orthogonal_projection_orthogonal_projection_of_le
((le_supr U i).trans (supr U).submodule_topological_closure) _).symm,
suffices : ∀ ε > 0, ∃ I, ∀ i ≥ I, ∥(orthogonal_projection (U i) y : E) - y∥ < ε,
{ simpa only [proj_x, normed_add_comm_group.tendsto_at_top] using this },
intros ε hε,
obtain ⟨a, ha, hay⟩ : ∃ a ∈ ⨆ i, U i, dist y a < ε,
{ have y_mem : y ∈ (⨆ i, U i).topological_closure := submodule.coe_mem _,
rw [← set_like.mem_coe, submodule.topological_closure_coe, metric.mem_closure_iff] at y_mem,
exact y_mem ε hε },
rw dist_eq_norm at hay,
obtain ⟨I, hI⟩ : ∃ I, a ∈ U I,
{ rwa [submodule.mem_supr_of_directed _ (hU.directed_le)] at ha },
refine ⟨I, λ i (hi : I ≤ i), _⟩,
rw [norm_sub_rev, orthogonal_projection_minimal],
refine lt_of_le_of_lt _ hay,
change _ ≤ ∥y - (⟨a, hU hi hI⟩ : U i)∥,
exact cinfi_le ⟨0, set.forall_range_iff.mpr $ λ _, norm_nonneg _⟩ _,
end
/-- Given a monotone family `U` of complete submodules of `E` with dense span supremum,
and a fixed `x : E`, the orthogonal projection of `x` on `U i` tends to `x` along `at_top`. -/
lemma orthogonal_projection_tendsto_self [complete_space E] {ι : Type*} [semilattice_sup ι]
(U : ι → submodule 𝕜 E) [∀ t, complete_space (U t)] (hU : monotone U)
(x : E) (hU' : ⊤ ≤ (⨆ t, U t).topological_closure) :
filter.tendsto (λ t, (orthogonal_projection (U t) x : E)) at_top (𝓝 x) :=
begin
rw ← eq_top_iff at hU',
convert orthogonal_projection_tendsto_closure_supr U hU x,
rw orthogonal_projection_eq_self_iff.mpr _,
rw hU',
trivial
end
/-- The orthogonal complement satisfies `Kᗮᗮᗮ = Kᗮ`. -/
lemma submodule.triorthogonal_eq_orthogonal [complete_space E] : Kᗮᗮᗮ = Kᗮ :=
begin
rw Kᗮ.orthogonal_orthogonal_eq_closure,
exact K.is_closed_orthogonal.submodule_topological_closure_eq,
end
/-- The closure of `K` is the full space iff `Kᗮ` is trivial. -/
lemma submodule.topological_closure_eq_top_iff [complete_space E] :
K.topological_closure = ⊤ ↔ Kᗮ = ⊥ :=
begin
rw ←submodule.orthogonal_orthogonal_eq_closure,
split; intro h,
{ rw [←submodule.triorthogonal_eq_orthogonal, h, submodule.top_orthogonal_eq_bot] },
{ rw [h, submodule.bot_orthogonal_eq_top] }
end
/-- The reflection in `Kᗮ` of an element of `K` is its negation. -/
lemma reflection_mem_subspace_orthogonal_precomplement_eq_neg
[complete_space E] {v : E} (hv : v ∈ K) :
reflection Kᗮ v = -v :=
reflection_mem_subspace_orthogonal_complement_eq_neg (K.le_orthogonal_orthogonal hv)
/-- The orthogonal projection onto `(𝕜 ∙ v)ᗮ` of `v` is zero. -/
lemma orthogonal_projection_orthogonal_complement_singleton_eq_zero [complete_space E] (v : E) :
orthogonal_projection (𝕜 ∙ v)ᗮ v = 0 :=
orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero
(submodule.mem_span_singleton_self v)
/-- The reflection in `(𝕜 ∙ v)ᗮ` of `v` is `-v`. -/
lemma reflection_orthogonal_complement_singleton_eq_neg [complete_space E] (v : E) :
reflection (𝕜 ∙ v)ᗮ v = -v :=
reflection_mem_subspace_orthogonal_precomplement_eq_neg (submodule.mem_span_singleton_self v)
lemma reflection_sub [complete_space F] {v w : F} (h : ∥v∥ = ∥w∥) :
reflection (ℝ ∙ (v - w))ᗮ v = w :=
begin
set R : F ≃ₗᵢ[ℝ] F := reflection (ℝ ∙ (v - w))ᗮ,
suffices : R v + R v = w + w,
{ apply smul_right_injective F (by norm_num : (2:ℝ) ≠ 0),
simpa [two_smul] using this },
have h₁ : R (v - w) = -(v - w) := reflection_orthogonal_complement_singleton_eq_neg (v - w),
have h₂ : R (v + w) = v + w,
{ apply reflection_mem_subspace_eq_self,
apply mem_orthogonal_singleton_of_inner_left,
rw real_inner_add_sub_eq_zero_iff,
exact h },
convert congr_arg2 (+) h₂ h₁ using 1,
{ simp },
{ abel }
end
variables (K)
/-- In a complete space `E`, a vector splits as the sum of its orthogonal projections onto a
complete submodule `K` and onto the orthogonal complement of `K`.-/
lemma eq_sum_orthogonal_projection_self_orthogonal_complement
[complete_space E] [complete_space K] (w : E) :
w = (orthogonal_projection K w : E) + (orthogonal_projection Kᗮ w : E) :=
begin
obtain ⟨y, hy, z, hz, hwyz⟩ := K.exists_sum_mem_mem_orthogonal w,
convert hwyz,
{ exact eq_orthogonal_projection_of_mem_orthogonal' hy hz hwyz },
{ rw add_comm at hwyz,
refine eq_orthogonal_projection_of_mem_orthogonal' hz _ hwyz,
simp [hy] }
end
/-- The Pythagorean theorem, for an orthogonal projection.-/
lemma norm_sq_eq_add_norm_sq_projection
(x : E) (S : submodule 𝕜 E) [complete_space E] [complete_space S] :
∥x∥^2 = ∥orthogonal_projection S x∥^2 + ∥orthogonal_projection Sᗮ x∥^2 :=
begin
let p1 := orthogonal_projection S,
let p2 := orthogonal_projection Sᗮ,
have x_decomp : x = p1 x + p2 x :=
eq_sum_orthogonal_projection_self_orthogonal_complement S x,
have x_orth : ⟪ (p1 x : E), p2 x ⟫ = 0 :=
submodule.inner_right_of_mem_orthogonal (set_like.coe_mem (p1 x)) (set_like.coe_mem (p2 x)),
nth_rewrite 0 [x_decomp],
simp only [sq, norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero ((p1 x) : E) (p2 x) x_orth,
add_left_inj, mul_eq_mul_left_iff, norm_eq_zero, true_or, eq_self_iff_true,
submodule.coe_norm, submodule.coe_eq_zero]
end
/-- In a complete space `E`, the projection maps onto a complete subspace `K` and its orthogonal
complement sum to the identity. -/
lemma id_eq_sum_orthogonal_projection_self_orthogonal_complement
[complete_space E] [complete_space K] :
continuous_linear_map.id 𝕜 E
= K.subtypeL.comp (orthogonal_projection K)
+ Kᗮ.subtypeL.comp (orthogonal_projection Kᗮ) :=
by { ext w, exact eq_sum_orthogonal_projection_self_orthogonal_complement K w }
@[simp] lemma inner_orthogonal_projection_eq_of_mem_right [complete_space K] (u : K) (v : E) :
⟪orthogonal_projection K v, u⟫ = ⟪v, u⟫ :=
calc ⟪orthogonal_projection K v, u⟫
= ⟪(orthogonal_projection K v : E), u⟫ : K.coe_inner _ _
... = ⟪(orthogonal_projection K v : E), u⟫ + ⟪v - orthogonal_projection K v, u⟫ :
by rw [orthogonal_projection_inner_eq_zero _ _ (submodule.coe_mem _), add_zero]
... = ⟪v, u⟫ :
by rw [← inner_add_left, add_sub_cancel'_right]
@[simp] lemma inner_orthogonal_projection_eq_of_mem_left [complete_space K] (u : K) (v : E) :
⟪u, orthogonal_projection K v⟫ = ⟪(u : E), v⟫ :=
by rw [← inner_conj_sym, ← inner_conj_sym (u : E), inner_orthogonal_projection_eq_of_mem_right]
/-- The orthogonal projection is self-adjoint. -/
lemma inner_orthogonal_projection_left_eq_right
[complete_space K] (u v : E) :
⟪↑(orthogonal_projection K u), v⟫ = ⟪u, orthogonal_projection K v⟫ :=
by rw [← inner_orthogonal_projection_eq_of_mem_left, inner_orthogonal_projection_eq_of_mem_right]
/-- The orthogonal projection is symmetric. -/
lemma orthogonal_projection_is_symmetric
[complete_space K] :
(K.subtypeL ∘L orthogonal_projection K : E →ₗ[𝕜] E).is_symmetric :=
inner_orthogonal_projection_left_eq_right K
open finite_dimensional
/-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁`
containined in it, the dimensions of `K₁` and the intersection of its
orthogonal subspace with `K₂` add to that of `K₂`. -/
lemma submodule.finrank_add_inf_finrank_orthogonal {K₁ K₂ : submodule 𝕜 E}
[finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) :
finrank 𝕜 K₁ + finrank 𝕜 (K₁ᗮ ⊓ K₂ : submodule 𝕜 E) = finrank 𝕜 K₂ :=
begin
haveI := submodule.finite_dimensional_of_le h,
haveI := proper_is_R_or_C 𝕜 K₁,
have hd := submodule.dim_sup_add_dim_inf_eq K₁ (K₁ᗮ ⊓ K₂),
rw [←inf_assoc, (submodule.orthogonal_disjoint K₁).eq_bot, bot_inf_eq, finrank_bot,
submodule.sup_orthogonal_inf_of_complete_space h] at hd,
rw add_zero at hd,
exact hd.symm
end
/-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁`
containined in it, the dimensions of `K₁` and the intersection of its
orthogonal subspace with `K₂` add to that of `K₂`. -/
lemma submodule.finrank_add_inf_finrank_orthogonal' {K₁ K₂ : submodule 𝕜 E}
[finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) {n : ℕ} (h_dim : finrank 𝕜 K₁ + n = finrank 𝕜 K₂) :
finrank 𝕜 (K₁ᗮ ⊓ K₂ : submodule 𝕜 E) = n :=
by { rw ← add_right_inj (finrank 𝕜 K₁),
simp [submodule.finrank_add_inf_finrank_orthogonal h, h_dim] }
/-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to
that of `E`. -/
lemma submodule.finrank_add_finrank_orthogonal [finite_dimensional 𝕜 E] (K : submodule 𝕜 E) :
finrank 𝕜 K + finrank 𝕜 Kᗮ = finrank 𝕜 E :=
begin
convert submodule.finrank_add_inf_finrank_orthogonal (le_top : K ≤ ⊤) using 1,
{ rw inf_top_eq },
{ simp }
end
/-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to
that of `E`. -/
lemma submodule.finrank_add_finrank_orthogonal' [finite_dimensional 𝕜 E] {K : submodule 𝕜 E} {n : ℕ}
(h_dim : finrank 𝕜 K + n = finrank 𝕜 E) :
finrank 𝕜 Kᗮ = n :=
by { rw ← add_right_inj (finrank 𝕜 K), simp [submodule.finrank_add_finrank_orthogonal, h_dim] }
local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ
/-- In a finite-dimensional inner product space, the dimension of the orthogonal complement of the
span of a nonzero vector is one less than the dimension of the space. -/
lemma finrank_orthogonal_span_singleton {n : ℕ} [_i : fact (finrank 𝕜 E = n + 1)]
{v : E} (hv : v ≠ 0) :
finrank 𝕜 (𝕜 ∙ v)ᗮ = n :=
submodule.finrank_add_finrank_orthogonal' $ by simp [finrank_span_singleton hv, _i.elim, add_comm]
/-- An element `φ` of the orthogonal group of `F` can be factored as a product of reflections, and
specifically at most as many reflections as the dimension of the complement of the fixed subspace
of `φ`. -/
lemma linear_isometry_equiv.reflections_generate_dim_aux [finite_dimensional ℝ F] {n : ℕ}
(φ : F ≃ₗᵢ[ℝ] F)
(hn : finrank ℝ (continuous_linear_map.id ℝ F - φ.to_continuous_linear_equiv).kerᗮ ≤ n) :
∃ l : list F, l.length ≤ n ∧ φ = (l.map (λ v, reflection (ℝ ∙ v)ᗮ)).prod :=
begin
-- We prove this by strong induction on `n`, the dimension of the orthogonal complement of the
-- fixed subspace of the endomorphism `φ`
induction n with n IH generalizing φ,
{ -- Base case: `n = 0`, the fixed subspace is the whole space, so `φ = id`
refine ⟨[], rfl.le, show φ = 1, from _⟩,
have : (continuous_linear_map.id ℝ F - φ.to_continuous_linear_equiv).ker = ⊤,
{ rwa [le_zero_iff, finrank_eq_zero, submodule.orthogonal_eq_bot_iff] at hn },
symmetry,
ext x,
have := linear_map.congr_fun (linear_map.ker_eq_top.mp this) x,
rwa [continuous_linear_map.coe_sub, linear_map.zero_apply, linear_map.sub_apply, sub_eq_zero]
at this },
{ -- Inductive step. Let `W` be the fixed subspace of `φ`. We suppose its complement to have
-- dimension at most n + 1.
let W := (continuous_linear_map.id ℝ F - φ.to_continuous_linear_equiv).ker,
have hW : ∀ w ∈ W, φ w = w := λ w hw, (sub_eq_zero.mp hw).symm,
by_cases hn' : finrank ℝ Wᗮ ≤ n,
{ obtain ⟨V, hV₁, hV₂⟩ := IH φ hn',
exact ⟨V, hV₁.trans n.le_succ, hV₂⟩ },
-- Take a nonzero element `v` of the orthogonal complement of `W`.
haveI : nontrivial Wᗮ := nontrivial_of_finrank_pos (by linarith [zero_le n] : 0 < finrank ℝ Wᗮ),
obtain ⟨v, hv⟩ := exists_ne (0 : Wᗮ),
have hφv : φ v ∈ Wᗮ,
{ intros w hw,
rw [← hW w hw, linear_isometry_equiv.inner_map_map],
exact v.prop w hw },
have hv' : (v:F) ∉ W,
{ intros h,
exact hv ((submodule.mem_left_iff_eq_zero_of_disjoint W.orthogonal_disjoint).mp h) },
-- Let `ρ` be the reflection in `v - φ v`; this is designed to swap `v` and `φ v`
let x : F := v - φ v,
let ρ := reflection (ℝ ∙ x)ᗮ,
-- Notation: Let `V` be the fixed subspace of `φ.trans ρ`
let V := (continuous_linear_map.id ℝ F - (φ.trans ρ).to_continuous_linear_equiv).ker,
have hV : ∀ w, ρ (φ w) = w → w ∈ V,
{ intros w hw,
change w - ρ (φ w) = 0,
rw [sub_eq_zero, hw] },
-- Everything fixed by `φ` is fixed by `φ.trans ρ`
have H₂V : W ≤ V,
{ intros w hw,
apply hV,
rw hW w hw,
refine reflection_mem_subspace_eq_self _,
apply mem_orthogonal_singleton_of_inner_left,
exact submodule.sub_mem _ v.prop hφv _ hw },
-- `v` is also fixed by `φ.trans ρ`
have H₁V : (v : F) ∈ V,
{ apply hV,
have : ρ v = φ v := reflection_sub (φ.norm_map v).symm,
rw ←this,
exact reflection_reflection _ _, },
-- By dimension-counting, the complement of the fixed subspace of `φ.trans ρ` has dimension at
-- most `n`
have : finrank ℝ Vᗮ ≤ n,
{ change finrank ℝ Wᗮ ≤ n + 1 at hn,
have : finrank ℝ W + 1 ≤ finrank ℝ V :=
submodule.finrank_lt_finrank_of_lt (set_like.lt_iff_le_and_exists.2 ⟨H₂V, v, H₁V, hv'⟩),
have : finrank ℝ V + finrank ℝ Vᗮ = finrank ℝ F := V.finrank_add_finrank_orthogonal,
have : finrank ℝ W + finrank ℝ Wᗮ = finrank ℝ F := W.finrank_add_finrank_orthogonal,
linarith },
-- So apply the inductive hypothesis to `φ.trans ρ`
obtain ⟨l, hl, hφl⟩ := IH (ρ * φ) this,
-- Prepend `ρ` to the factorization into reflections obtained for `φ.trans ρ`; this gives a
-- factorization into reflections for `φ`.
refine ⟨x :: l, nat.succ_le_succ hl, _⟩,
rw [list.map_cons, list.prod_cons],
have := congr_arg ((*) ρ) hφl,
rwa [←mul_assoc, reflection_mul_reflection, one_mul] at this, }
end
/-- The orthogonal group of `F` is generated by reflections; specifically each element `φ` of the
orthogonal group is a product of at most as many reflections as the dimension of `F`.
Special case of the **Cartan–Dieudonné theorem**. -/
lemma linear_isometry_equiv.reflections_generate_dim [finite_dimensional ℝ F] (φ : F ≃ₗᵢ[ℝ] F) :
∃ l : list F, l.length ≤ finrank ℝ F ∧ φ = (l.map (λ v, reflection (ℝ ∙ v)ᗮ)).prod :=
let ⟨l, hl₁, hl₂⟩ := φ.reflections_generate_dim_aux le_rfl in
⟨l, hl₁.trans (submodule.finrank_le _), hl₂⟩
/-- The orthogonal group of `F` is generated by reflections. -/
lemma linear_isometry_equiv.reflections_generate [finite_dimensional ℝ F] :
subgroup.closure (set.range (λ v : F, reflection (ℝ ∙ v)ᗮ)) = ⊤ :=
begin
rw subgroup.eq_top_iff',
intros φ,
rcases φ.reflections_generate_dim with ⟨l, _, rfl⟩,
apply (subgroup.closure _).list_prod_mem,
intros x hx,
rcases list.mem_map.mp hx with ⟨a, _, hax⟩,
exact subgroup.subset_closure ⟨a, hax⟩,
end
end orthogonal
section orthogonal_family
variables {ι : Type*}
/-- An orthogonal family of subspaces of `E` satisfies `direct_sum.is_internal` (that is,
they provide an internal direct sum decomposition of `E`) if and only if their span has trivial
orthogonal complement. -/
lemma orthogonal_family.is_internal_iff_of_is_complete [decidable_eq ι]
{V : ι → submodule 𝕜 E} (hV : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ))
(hc : is_complete (↑(supr V) : set E)) :
direct_sum.is_internal V ↔ (supr V)ᗮ = ⊥ :=
begin
haveI : complete_space ↥(supr V) := hc.complete_space_coe,
simp only [direct_sum.is_internal_submodule_iff_independent_and_supr_eq_top, hV.independent,
true_and, submodule.orthogonal_eq_bot_iff]
end
/-- An orthogonal family of subspaces of `E` satisfies `direct_sum.is_internal` (that is,
they provide an internal direct sum decomposition of `E`) if and only if their span has trivial
orthogonal complement. -/
lemma orthogonal_family.is_internal_iff [decidable_eq ι] [finite_dimensional 𝕜 E]
{V : ι → submodule 𝕜 E} (hV : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) :
direct_sum.is_internal V ↔ (supr V)ᗮ = ⊥ :=
begin
haveI h := finite_dimensional.proper_is_R_or_C 𝕜 ↥(supr V),
exact hV.is_internal_iff_of_is_complete
(complete_space_coe_iff_is_complete.mp infer_instance)
end
end orthogonal_family
section orthonormal_basis
variables {𝕜 E} {v : set E}
open finite_dimensional submodule set
/-- An orthonormal set in an `inner_product_space` is maximal, if and only if the orthogonal
complement of its span is empty. -/
lemma maximal_orthonormal_iff_orthogonal_complement_eq_bot (hv : orthonormal 𝕜 (coe : v → E)) :
(∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ (span 𝕜 v)ᗮ = ⊥ :=
begin
rw submodule.eq_bot_iff,
split,
{ contrapose!,
-- ** direction 1: nonempty orthogonal complement implies nonmaximal
rintros ⟨x, hx', hx⟩,
-- take a nonzero vector and normalize it
let e := (∥x∥⁻¹ : 𝕜) • x,
have he : ∥e∥ = 1 := by simp [e, norm_smul_inv_norm hx],
have he' : e ∈ (span 𝕜 v)ᗮ := smul_mem' _ _ hx',
have he'' : e ∉ v,
{ intros hev,
have : e = 0,
{ have : e ∈ (span 𝕜 v) ⊓ (span 𝕜 v)ᗮ := ⟨subset_span hev, he'⟩,
simpa [(span 𝕜 v).inf_orthogonal_eq_bot] using this },
have : e ≠ 0 := hv.ne_zero ⟨e, hev⟩,
contradiction },
-- put this together with `v` to provide a candidate orthonormal basis for the whole space
refine ⟨insert e v, v.subset_insert e, ⟨_, _⟩, (v.ne_insert_of_not_mem he'').symm⟩,
{ -- show that the elements of `insert e v` have unit length
rintros ⟨a, ha'⟩,
cases eq_or_mem_of_mem_insert ha' with ha ha,
{ simp [ha, he] },
{ exact hv.1 ⟨a, ha⟩ } },
{ -- show that the elements of `insert e v` are orthogonal
have h_end : ∀ a ∈ v, ⟪a, e⟫ = 0,
{ intros a ha,
exact he' a (submodule.subset_span ha) },
rintros ⟨a, ha'⟩,
cases eq_or_mem_of_mem_insert ha' with ha ha,
{ rintros ⟨b, hb'⟩ hab',
have hb : b ∈ v,
{ refine mem_of_mem_insert_of_ne hb' _,
intros hbe',
apply hab',
simp [ha, hbe'] },
rw inner_eq_zero_sym,
simpa [ha] using h_end b hb },
rintros ⟨b, hb'⟩ hab',
cases eq_or_mem_of_mem_insert hb' with hb hb,
{ simpa [hb] using h_end a ha },
have : (⟨a, ha⟩ : v) ≠ ⟨b, hb⟩,
{ intros hab'',
apply hab',
simpa using hab'' },
exact hv.2 this } },
{ -- ** direction 2: empty orthogonal complement implies maximal
simp only [subset.antisymm_iff],
rintros h u (huv : v ⊆ u) hu,
refine ⟨_, huv⟩,
intros x hxu,
refine ((mt (h x)) (hu.ne_zero ⟨x, hxu⟩)).imp_symm _,
intros hxv y hy,
have hxv' : (⟨x, hxu⟩ : u) ∉ (coe ⁻¹' v : set u) := by simp [huv, hxv],
obtain ⟨l, hl, rfl⟩ :
∃ l ∈ finsupp.supported 𝕜 𝕜 (coe ⁻¹' v : set u), (finsupp.total ↥u E 𝕜 coe) l = y,
{ rw ← finsupp.mem_span_image_iff_total,
simp [huv, inter_eq_self_of_subset_left, hy] },
exact hu.inner_finsupp_eq_zero hxv' hl }
end
variables [finite_dimensional 𝕜 E]
/-- An orthonormal set in a finite-dimensional `inner_product_space` is maximal, if and only if it
is a basis. -/
lemma maximal_orthonormal_iff_basis_of_finite_dimensional
(hv : orthonormal 𝕜 (coe : v → E)) :
(∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ ∃ b : basis v 𝕜 E, ⇑b = coe :=
begin
haveI := proper_is_R_or_C 𝕜 (span 𝕜 v),
rw maximal_orthonormal_iff_orthogonal_complement_eq_bot hv,
have hv_compl : is_complete (span 𝕜 v : set E) := (span 𝕜 v).complete_of_finite_dimensional,
rw submodule.orthogonal_eq_bot_iff,
have hv_coe : range (coe : v → E) = v := by simp,
split,
{ refine λ h, ⟨basis.mk hv.linear_independent _, basis.coe_mk _ _⟩,
convert h.ge },
{ rintros ⟨h, coe_h⟩,
rw [← h.span_eq, coe_h, hv_coe] }
end
end orthonormal_basis
|
8555c35574f91d29e0ca46b7e601e99b4312e0ab
|
a047a4718edfa935d17231e9e6ecec8c7b701e05
|
/src/data/finsupp.lean
|
b923bcd89d2c4daca5d5711dd5081e9e93c04ea5
|
[
"Apache-2.0"
] |
permissive
|
utensil-contrib/mathlib
|
bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767
|
b91909e77e219098a2f8cc031f89d595fe274bd2
|
refs/heads/master
| 1,668,048,976,965
| 1,592,442,701,000
| 1,592,442,701,000
| 273,197,855
| 0
| 0
| null | 1,592,472,812,000
| 1,592,472,811,000
| null |
UTF-8
|
Lean
| false
| false
| 70,968
|
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, Scott Morrison
-/
import algebra.module
import data.fintype.card
/-!
# Type of functions with finite support
For any type `α` and a type `β` with zero, we define the type `finsupp α β` of finitely supported
functions from `α` to `β`, i.e. the functions which are zero everywhere on `α` except on a finite
set. We write this in infix notation as `α →₀ β`.
Functions with finite support provide the basis for the following concrete instances:
* `ℕ →₀ α`: Polynomials (where `α` is a ring)
* `(σ →₀ ℕ) →₀ α`: Multivariate Polynomials (again `α` is a ring, and `σ` are variable names)
* `α →₀ ℕ`: Multisets
* `α →₀ ℤ`: Abelian groups freely generated by `α`
* `β →₀ α`: Linear combinations over `β` where `α` is the scalar ring
Most of the theory assumes that the range is a commutative monoid. This gives us the big sum
operator as a powerful way to construct `finsupp` elements.
A general piece of advice is to not use `α →₀ β` directly, as the type class setup might not be a
good fit. Defining a copy and selecting the instances that are best suited for the application works
better.
## Implementation notes
This file is a `noncomputable theory` and uses classical logic throughout.
## Notation
This file defines `α →₀ β` as notation for `finsupp α β`.
-/
noncomputable theory
open_locale classical big_operators
open finset
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Type*}
{α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*}
/-- `finsupp α β`, denoted `α →₀ β`, is the type of functions `f : α → β` such that
`f x = 0` for all but finitely many `x`. -/
structure finsupp (α : Type*) (β : Type*) [has_zero β] :=
(support : finset α)
(to_fun : α → β)
(mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0)
infixr ` →₀ `:25 := finsupp
namespace finsupp
/-! ### Basic declarations about `finsupp` -/
section basic
variable [has_zero β]
instance : has_coe_to_fun (α →₀ β) := ⟨λ_, α → β, to_fun⟩
instance : has_zero (α →₀ β) := ⟨⟨∅, (λ_, 0), λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩
@[simp] lemma zero_apply {a : α} : (0 : α →₀ β) a = 0 :=
rfl
@[simp] lemma support_zero : (0 : α →₀ β).support = ∅ :=
rfl
instance : inhabited (α →₀ β) := ⟨0⟩
@[simp] lemma mem_support_iff {f : α →₀ β} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 :=
f.mem_support_to_fun
lemma not_mem_support_iff {f : α →₀ β} {a} : a ∉ f.support ↔ f a = 0 :=
not_iff_comm.1 mem_support_iff.symm
@[ext]
lemma ext : ∀{f g : α →₀ β}, (∀a, f a = g a) → f = g
| ⟨s, f, hf⟩ ⟨t, g, hg⟩ h :=
begin
have : f = g, { funext a, exact h a },
subst this,
have : s = t, { ext a, exact (hf a).trans (hg a).symm },
subst this
end
lemma ext_iff {f g : α →₀ β} : f = g ↔ (∀a:α, f a = g a) :=
⟨by rintros rfl a; refl, ext⟩
@[simp] lemma support_eq_empty {f : α →₀ β} : f.support = ∅ ↔ f = 0 :=
⟨assume h, ext $ assume a, by_contradiction $ λ H, (finset.ext_iff.1 h a).1 $
mem_support_iff.2 H, by rintro rfl; refl⟩
instance finsupp.decidable_eq [decidable_eq α] [decidable_eq β] : decidable_eq (α →₀ β) :=
assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a))
⟨assume ⟨h₁, h₂⟩, ext $ assume a,
if h : a ∈ f.support then h₂ a h else
have hf : f a = 0, by rwa [mem_support_iff, not_not] at h,
have hg : g a = 0, by rwa [h₁, mem_support_iff, not_not] at h,
by rw [hf, hg],
by rintro rfl; exact ⟨rfl, λ _ _, rfl⟩⟩
lemma finite_supp (f : α →₀ β) : set.finite {a | f a ≠ 0} :=
⟨fintype.of_finset f.support (λ _, mem_support_iff)⟩
lemma support_subset_iff {s : set α} {f : α →₀ β} :
↑f.support ⊆ s ↔ (∀a∉s, f a = 0) :=
by simp only [set.subset_def, mem_coe, mem_support_iff];
exact forall_congr (assume a, @not_imp_comm _ _ (classical.dec _) (classical.dec _))
/-- Given `fintype α`, `equiv_fun_on_fintype` is the `equiv` between `α →₀ β` and `α → β`.
(All functions on a finite type are finitely supported.) -/
def equiv_fun_on_fintype [fintype α] : (α →₀ β) ≃ (α → β) :=
⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp only [true_and, finset.mem_univ,
iff_self, finset.mem_filter, finset.filter_congr_decidable, forall_true_iff]),
begin intro f, ext a, refl end,
begin intro f, ext a, refl end⟩
end basic
/-! ### Declarations about `single` -/
section single
variables [has_zero β] {a a' : α} {b : β}
/-- `single a b` is the finitely supported function which has
value `b` at `a` and zero otherwise. -/
def single (a : α) (b : β) : α →₀ β :=
⟨if b = 0 then ∅ else {a}, λ a', if a = a' then b else 0, λ a', begin
by_cases hb : b = 0; by_cases a = a';
simp only [hb, h, if_pos, if_false, mem_singleton],
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨λ _, hb, λ _, rfl⟩ },
{ exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ }
end⟩
lemma single_apply : (single a b : α →₀ β) a' = if a = a' then b else 0 :=
rfl
@[simp] lemma single_eq_same : (single a b : α →₀ β) a = b :=
if_pos rfl
@[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ β) a' = 0 :=
if_neg h
@[simp] lemma single_zero : (single a 0 : α →₀ β) = 0 :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, single_eq_same, zero_apply] },
{ rw [single_eq_of_ne h, zero_apply] }
end
lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} :=
if_neg hb
lemma support_single_subset : (single a b).support ⊆ {a} :=
show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _]
lemma injective_single (a : α) : function.injective (single a : β → α →₀ β) :=
assume b₁ b₂ eq,
have (single a b₁ : α →₀ β) a = (single a b₂ : α →₀ β) a, by rw eq,
by rwa [single_eq_same, single_eq_same] at this
lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : β) :
single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) :=
begin
split,
{ assume eq,
by_cases a₁ = a₂,
{ refine or.inl ⟨h, _⟩,
rwa [h, (injective_single a₂).eq_iff] at eq },
{ rw [ext_iff] at eq,
have h₁ := eq a₁,
have h₂ := eq a₂,
simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂,
exact or.inr ⟨h₁, h₂.symm⟩ } },
{ rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩),
{ refl },
{ rw [single_zero, single_zero] } }
end
lemma single_left_inj (h : b ≠ 0) :
single a b = single a' b ↔ a = a' :=
⟨λ H, by simpa only [h, single_eq_single_iff,
and_false, or_false, eq_self_iff_true, and_true] using H,
λ H, by rw [H]⟩
lemma single_eq_zero : single a b = 0 ↔ b = 0 :=
⟨λ h, by { rw ext_iff at h, simpa only [single_eq_same, zero_apply] using h a },
λ h, by rw [h, single_zero]⟩
lemma single_swap {α β : Type*} [has_zero β] (a₁ a₂ : α) (b : β) :
(single a₁ b : α → β) a₂ = (single a₂ b : α → β) a₁ :=
by simp only [single_apply]; ac_refl
lemma unique_single [unique α] (x : α →₀ β) : x = single (default α) (x (default α)) :=
by ext i; simp only [unique.eq_default i, single_eq_same]
@[simp] lemma unique_single_eq_iff [unique α] {b' : β} :
single a b = single a' b' ↔ b = b' :=
begin
rw [single_eq_single_iff],
split,
{ rintros (⟨_, rfl⟩ | ⟨rfl, rfl⟩); refl },
{ intro h, left, exact ⟨subsingleton.elim _ _, h⟩ }
end
end single
/-! ### Declarations about `on_finset` -/
section on_finset
variables [has_zero β]
/-- `on_finset s f hf` is the finsupp function representing `f` restricted to the finset `s`.
The function needs to be `0` outside of `s`. Use this when the set needs to be filtered anyways,
otherwise a better set representation is often available. -/
def on_finset (s : finset α) (f : α → β) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ β :=
⟨s.filter (λa, f a ≠ 0), f,
assume a, classical.by_cases
(assume h : f a = 0, by rw mem_filter; exact ⟨and.right, λ H, (H h).elim⟩)
(assume h : f a ≠ 0, by rw mem_filter; simp only [iff_true_intro h, hf a h, true_and])⟩
@[simp] lemma on_finset_apply {s : finset α} {f : α → β} {hf a} :
(on_finset s f hf : α →₀ β) a = f a :=
rfl
@[simp] lemma support_on_finset_subset {s : finset α} {f : α → β} {hf} :
(on_finset s f hf).support ⊆ s :=
filter_subset _
end on_finset
/-! ### Declarations about `map_range` -/
section map_range
variables [has_zero β₁] [has_zero β₂]
/-- The composition of `f : β₁ → β₂` and `g : α →₀ β₁` is
`map_range f hf g : α →₀ β₂`, well-defined when `f 0 = 0`. -/
def map_range (f : β₁ → β₂) (hf : f 0 = 0) (g : α →₀ β₁) : α →₀ β₂ :=
on_finset g.support (f ∘ g) $
assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf
@[simp] lemma map_range_apply {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {a : α} :
map_range f hf g a = f (g a) :=
rfl
@[simp] lemma map_range_zero {f : β₁ → β₂} {hf : f 0 = 0} : map_range f hf (0 : α →₀ β₁) = 0 :=
ext $ λ a, by simp only [hf, zero_apply, map_range_apply]
lemma support_map_range {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} :
(map_range f hf g).support ⊆ g.support :=
support_on_finset_subset
@[simp] lemma map_range_single {f : β₁ → β₂} {hf : f 0 = 0} {a : α} {b : β₁} :
map_range f hf (single a b) = single a (f b) :=
ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf]
end map_range
/-! ### Declarations about `emb_domain` -/
section emb_domain
variables [has_zero β]
/-- Given `f : α₁ ↪ α₂` and `v : α₁ →₀ β`, `emb_domain f v : α₂ →₀ β`
is the finitely supported function whose value at `f a : α₂` is `v a`.
For a `b : α₂` outside the range of `f`, it is zero. -/
def emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) : α₂ →₀ β :=
begin
refine ⟨v.support.map f, λa₂,
if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩,
{ rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩,
exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.inj hb) },
{ assume a₂,
split_ifs,
{ simp only [h, true_iff, ne.def],
rw [← not_mem_support_iff, not_not],
apply finset.choose_mem },
{ simp only [h, ne.def, ne_self_iff_false] } }
end
lemma support_emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) :
(emb_domain f v).support = v.support.map f :=
rfl
lemma emb_domain_zero (f : α₁ ↪ α₂) : (emb_domain f 0 : α₂ →₀ β) = 0 :=
rfl
lemma emb_domain_apply (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₁) :
emb_domain f v (f a) = v a :=
begin
change dite _ _ _ = _,
split_ifs; rw [finset.mem_map' f] at h,
{ refine congr_arg (v : α₁ → β) (f.inj' _),
exact finset.choose_property (λa₁, f a₁ = f a) _ _ },
{ exact (not_mem_support_iff.1 h).symm }
end
lemma emb_domain_notin_range (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) :
emb_domain f v a = 0 :=
begin
refine dif_neg (mt (assume h, _) h),
rcases finset.mem_map.1 h with ⟨a, h, rfl⟩,
exact set.mem_range_self a
end
lemma emb_domain_inj {f : α₁ ↪ α₂} {l₁ l₂ : α₁ →₀ β} :
emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ :=
⟨λ h, ext $ λ a, by simpa only [emb_domain_apply] using ext_iff.1 h (f a),
λ h, by rw h⟩
lemma emb_domain_map_range
{β₁ β₂ : Type*} [has_zero β₁] [has_zero β₂]
(f : α₁ ↪ α₂) (g : β₁ → β₂) (p : α₁ →₀ β₁) (hg : g 0 = 0) :
emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) :=
begin
ext a,
by_cases a ∈ set.range f,
{ rcases h with ⟨a', rfl⟩,
rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] },
{ rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption }
end
lemma single_of_emb_domain_single
(l : α₁ →₀ β) (f : α₁ ↪ α₂) (a : α₂) (b : β) (hb : b ≠ 0)
(h : l.emb_domain f = single a b) :
∃ x, l = single x b ∧ f x = a :=
begin
have h_map_support : finset.map f (l.support) = {a},
by rw [←support_emb_domain, h, support_single_ne_zero hb]; refl,
have ha : a ∈ finset.map f (l.support),
by simp only [h_map_support, finset.mem_singleton],
rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩,
use c,
split,
{ ext d,
rw [← emb_domain_apply f l, h],
by_cases h_cases : c = d,
{ simp only [eq.symm h_cases, hc₂, single_eq_same] },
{ rw [single_apply, single_apply, if_neg, if_neg h_cases],
by_contra hfd,
exact h_cases (f.inj (hc₂.trans hfd)) } },
{ exact hc₂ }
end
end emb_domain
/-! ### Declarations about `zip_with` -/
section zip_with
variables [has_zero β] [has_zero β₁] [has_zero β₂]
/-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying
`zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and it is well-defined when `f 0 0 = 0`. -/
def zip_with (f : β₁ → β₂ → β) (hf : f 0 0 = 0) (g₁ : α →₀ β₁) (g₂ : α →₀ β₂) : (α →₀ β) :=
on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H,
begin
simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib],
rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf
end
@[simp] lemma zip_with_apply
{f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} {a : α} :
zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) :=
rfl
lemma support_zip_with {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} :
(zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support :=
support_on_finset_subset
end zip_with
/-! ### Declarations about `erase` -/
section erase
/-- `erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to
`0`. -/
def erase [has_zero β] (a : α) (f : α →₀ β) : α →₀ β :=
⟨f.support.erase a, (λa', if a' = a then 0 else f a'),
assume a', by rw [mem_erase, mem_support_iff]; split_ifs;
[exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩,
exact and_iff_right h]⟩
@[simp] lemma support_erase [has_zero β] {a : α} {f : α →₀ β} :
(f.erase a).support = f.support.erase a :=
rfl
@[simp] lemma erase_same [has_zero β] {a : α} {f : α →₀ β} : (f.erase a) a = 0 :=
if_pos rfl
@[simp] lemma erase_ne [has_zero β] {a a' : α} {f : α →₀ β} (h : a' ≠ a) : (f.erase a) a' = f a' :=
if_neg h
@[simp] lemma erase_single [has_zero β] {a : α} {b : β} : (erase a (single a b)) = 0 := begin
ext s, by_cases hs : s = a,
{ rw [hs, erase_same], refl },
{ rw [erase_ne hs], exact single_eq_of_ne (ne.symm hs) }
end
lemma erase_single_ne [has_zero β] {a a' : α} {b : β} (h : a ≠ a') : (erase a (single a' b)) = single a' b :=
begin
ext s, by_cases hs : s = a,
{ rw [hs, erase_same, single_eq_of_ne (h.symm)] },
{ rw [erase_ne hs] }
end
end erase
/-!
### Declarations about `sum` and `prod`
In most of this section, the domain `β` is assumed to be an `add_monoid`.
-/
-- [to_additive sum] for finsupp.prod doesn't work, the equation lemmas are not generated
/-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/
def sum [has_zero β] [add_comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ :=
∑ a in f.support, g a (f a)
/-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/
@[to_additive]
def prod [has_zero β] [comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ :=
∏ a in f.support, g a (f a)
@[to_additive]
lemma prod_fintype [fintype α] [has_zero β] [comm_monoid γ]
(f : α →₀ β) (g : α → β → γ) (h : ∀ i, g i 0 = 1) :
f.prod g = ∏ i, g i (f i) :=
begin
classical,
rw [finsupp.prod, ← fintype.prod_extend_by_one, finset.prod_congr rfl],
intros i hi,
split_ifs with hif hif,
{ refl },
{ rw finsupp.not_mem_support_iff at hif,
rw [hif, h] }
end
@[to_additive]
lemma prod_map_range_index [has_zero β₁] [has_zero β₂] [comm_monoid γ]
{f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {h : α → β₂ → γ} (h0 : ∀a, h a 0 = 1) :
(map_range f hf g).prod h = g.prod (λa b, h a (f b)) :=
finset.prod_subset support_map_range $ λ _ _ H,
by rw [not_mem_support_iff.1 H, h0]
@[to_additive]
lemma prod_zero_index [add_comm_monoid β] [comm_monoid γ] {h : α → β → γ} :
(0 : α →₀ β).prod h = 1 :=
rfl
@[to_additive]
lemma prod_comm {α' : Type*} [has_zero β] {β' : Type*} [has_zero β'] (f : α →₀ β) (g : α' →₀ β')
[comm_monoid γ] (h : α → β → α' → β' → γ) :
f.prod (λ x v, g.prod (λ x' v', h x v x' v')) = g.prod (λ x' v', f.prod (λ x v, h x v x' v')) :=
begin
dsimp [finsupp.prod],
rw finset.prod_comm,
end
@[simp, to_additive]
lemma prod_ite_eq [has_zero β] [comm_monoid γ] (f : α →₀ β) (a : α) (b : α → β → γ) :
f.prod (λ x v, ite (a = x) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 :=
by { dsimp [finsupp.prod], rw f.support.prod_ite_eq, }
/-- A restatement of `prod_ite_eq` with the equality test reversed. -/
@[simp, to_additive "A restatement of `sum_ite_eq` with the equality test reversed."]
lemma prod_ite_eq' [has_zero β] [comm_monoid γ] (f : α →₀ β) (a : α) (b : α → β → γ) :
f.prod (λ x v, ite (x = a) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 :=
by { dsimp [finsupp.prod], rw f.support.prod_ite_eq', }
@[simp] lemma prod_pow [fintype α] [comm_monoid γ] (f : α →₀ ℕ) (g : α → γ) :
f.prod (λ a b, g a ^ b) = ∏ a, g a ^ (f a) :=
begin
apply prod_subset (finset.subset_univ _),
intros a _ ha,
simp only [finsupp.not_mem_support_iff.mp ha, pow_zero]
end
section add_monoid
variables [add_monoid β]
@[to_additive]
lemma prod_single_index [comm_monoid γ] {a : α} {b : β} {h : α → β → γ} (h_zero : h a 0 = 1) :
(single a b).prod h = h a b :=
begin
by_cases h : b = 0,
{ simp only [h, h_zero, single_zero]; refl },
{ simp only [finsupp.prod, support_single_ne_zero h, prod_singleton, single_eq_same] }
end
instance : has_add (α →₀ β) := ⟨zip_with (+) (add_zero 0)⟩
@[simp] lemma add_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ + g₂) a = g₁ a + g₂ a :=
rfl
lemma support_add {g₁ g₂ : α →₀ β} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support :=
support_zip_with
lemma support_add_eq {g₁ g₂ : α →₀ β} (h : disjoint g₁.support g₂.support) :
(g₁ + g₂).support = g₁.support ∪ g₂.support :=
le_antisymm support_zip_with $ assume a ha,
(finset.mem_union.1 ha).elim
(assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, add_zero])
(assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, zero_add])
@[simp] lemma single_add {a : α} {b₁ b₂ : β} : single a (b₁ + b₂) = single a b₁ + single a b₂ :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] },
{ rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] }
end
instance : add_monoid (α →₀ β) :=
{ add_monoid .
zero := 0,
add := (+),
add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _,
zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _,
add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ }
/-- Evaluation of a function `f : α →₀ β` at a point as an additive monoid homomorphism. -/
def eval_add_hom (a : α) : (α →₀ β) →+ β := ⟨λ g, g a, zero_apply, λ _ _, add_apply⟩
@[simp] lemma eval_add_hom_apply (a : α) (g : α →₀ β) : eval_add_hom a g = g a := rfl
lemma single_add_erase {a : α} {f : α →₀ β} : single a (f a) + f.erase a = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero]
else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)]
lemma erase_add_single {a : α} {f : α →₀ β} : f.erase a + single a (f a) = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add]
else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)]
@[simp] lemma erase_add (a : α) (f f' : α →₀ β) : erase a (f + f') = erase a f + erase a f' :=
begin
ext s, by_cases hs : s = a,
{ rw [hs, add_apply, erase_same, erase_same, erase_same, add_zero] },
rw [add_apply, erase_ne hs, erase_ne hs, erase_ne hs, add_apply],
end
@[elab_as_eliminator]
protected theorem induction {p : (α →₀ β) → Prop} (f : α →₀ β)
(h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) :
p f :=
suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma induction₂ {p : (α →₀ β) → Prop} (f : α →₀ β)
(h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) :
p f :=
suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma map_range_add [add_monoid β₁] [add_monoid β₂]
{f : β₁ → β₂} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ β₁) :
map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ :=
ext $ λ a, by simp only [hf', add_apply, map_range_apply]
end add_monoid
section nat_sub
instance nat_sub : has_sub (α →₀ ℕ) := ⟨zip_with (λ m n, m - n) (nat.sub_zero 0)⟩
@[simp] lemma nat_sub_apply {g₁ g₂ : α →₀ ℕ} {a : α} :
(g₁ - g₂) a = g₁ a - g₂ a :=
rfl
@[simp] lemma single_sub {a : α} {n₁ n₂ : ℕ} : single a (n₁ - n₂) = single a n₁ - single a n₂ :=
begin
ext f,
by_cases h : (a = f),
{ rw [h, nat_sub_apply, single_eq_same, single_eq_same, single_eq_same] },
rw [nat_sub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h]
end
-- These next two lemmas are used in developing
-- the partial derivative on `mv_polynomial`.
lemma sub_single_one_add {a : α} {u u' : α →₀ ℕ} (h : u a ≠ 0) :
u - single a 1 + u' = u + u' - single a 1 :=
begin
ext b,
rw [add_apply, nat_sub_apply, nat_sub_apply, add_apply],
by_cases h : a = b,
{ rw [←h, single_eq_same], cases (u a), { contradiction }, { simp }, },
{ simp [h], }
end
lemma add_sub_single_one {a : α} {u u' : α →₀ ℕ} (h : u' a ≠ 0) :
u + (u' - single a 1) = u + u' - single a 1 :=
begin
ext b,
rw [add_apply, nat_sub_apply, nat_sub_apply, add_apply],
by_cases h : a = b,
{ rw [←h, single_eq_same], cases (u' a), { contradiction }, { simp }, },
{ simp [h], }
end
end nat_sub
instance [add_comm_monoid β] : add_comm_monoid (α →₀ β) :=
{ add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _,
.. finsupp.add_monoid }
instance [add_group β] : add_group (α →₀ β) :=
{ neg := map_range (has_neg.neg) neg_zero,
add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _,
.. finsupp.add_monoid }
lemma single_multiset_sum [add_comm_monoid β] (s : multiset β) (a : α) :
single a s.sum = (s.map (single a)).sum :=
multiset.induction_on s single_zero $ λ a s ih,
by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons]
lemma single_finset_sum [add_comm_monoid β] (s : finset γ) (f : γ → β) (a : α) :
single a (∑ b in s, f b) = ∑ b in s, single a (f b) :=
begin
transitivity,
apply single_multiset_sum,
rw [multiset.map_map],
refl
end
lemma single_sum [has_zero γ] [add_comm_monoid β] (s : δ →₀ γ) (f : δ → γ → β) (a : α) :
single a (s.sum f) = s.sum (λd c, single a (f d c)) :=
single_finset_sum _ _ _
@[to_additive]
lemma prod_neg_index [add_group β] [comm_monoid γ]
{g : α →₀ β} {h : α → β → γ} (h0 : ∀a, h a 0 = 1) :
(-g).prod h = g.prod (λa b, h a (- b)) :=
prod_map_range_index h0
@[simp] lemma neg_apply [add_group β] {g : α →₀ β} {a : α} : (- g) a = - g a :=
rfl
@[simp] lemma sub_apply [add_group β] {g₁ g₂ : α →₀ β} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a :=
rfl
@[simp] lemma support_neg [add_group β] {f : α →₀ β} : support (-f) = support f :=
finset.subset.antisymm
support_map_range
(calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm
... ⊆ support (- f) : support_map_range)
instance [add_comm_group β] : add_comm_group (α →₀ β) :=
{ add_comm := add_comm, ..finsupp.add_group }
@[simp] lemma sum_apply [has_zero β₁] [add_comm_monoid β]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {a₂ : α} :
(f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) :=
(eval_add_hom a₂ : (α →₀ β) →+ _).map_sum _ _
lemma support_sum [has_zero β₁] [add_comm_monoid β]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → (α →₀ β)} :
(f.sum g).support ⊆ f.support.bind (λa, (g a (f a)).support) :=
have ∀a₁ : α, f.sum (λ (a : α₁) (b : β₁), (g a b) a₁) ≠ 0 →
(∃ (a : α₁), f a ≠ 0 ∧ ¬ (g a (f a)) a₁ = 0),
from assume a₁ h,
let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in
⟨a, mem_support_iff.mp ha, ne⟩,
by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply, exists_prop]
using this
@[simp] lemma sum_zero [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} :
f.sum (λa b, (0 : γ)) = 0 :=
finset.sum_const_zero
@[simp] lemma sum_add [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β}
{h₁ h₂ : α → β → γ} :
f.sum (λa b, h₁ a b + h₂ a b) = f.sum h₁ + f.sum h₂ :=
finset.sum_add_distrib
@[simp] lemma sum_neg [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β}
{h : α → β → γ} : f.sum (λa b, - h a b) = - f.sum h :=
f.support.sum_hom (@has_neg.neg γ _)
@[simp] lemma sum_sub [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β}
{h₁ h₂ : α → β → γ} :
f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ :=
by rw [sub_eq_add_neg, ←sum_neg, ←sum_add]; refl
@[simp] lemma sum_single [add_comm_monoid β] (f : α →₀ β) :
f.sum single = f :=
have ∀a:α, f.sum (λa' b, ite (a' = a) b 0) =
∑ a' in {a}, ite (a' = a) (f a') 0,
begin
intro a,
by_cases h : a ∈ f.support,
{ have : ({a} : finset α) ⊆ f.support,
{ simpa only [finset.subset_iff, mem_singleton, forall_eq] },
refine (finset.sum_subset this (λ _ _ H, _)).symm,
exact if_neg (mt mem_singleton.2 H) },
{ transitivity (∑ a in f.support, (0 : β)),
{ refine (finset.sum_congr rfl $ λ a' ha', if_neg _),
rintro rfl, exact h ha' },
{ rw [sum_const_zero, sum_singleton, if_pos rfl, not_mem_support_iff.1 h] } }
end,
ext $ assume a, by simp only [sum_apply, single_apply, this, sum_singleton, if_pos]
@[to_additive]
lemma prod_add_index [add_comm_monoid β] [comm_monoid γ] {f g : α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f + g).prod h = f.prod h * g.prod h :=
have f_eq : ∏ a in f.support ∪ g.support, h a (f a) = f.prod h,
from (finset.prod_subset (finset.subset_union_left _ _) $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm,
have g_eq : ∏ a in f.support ∪ g.support, h a (g a) = g.prod h,
from (finset.prod_subset (finset.subset_union_right _ _) $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm,
calc ∏ a in (f + g).support, h a ((f + g) a) =
∏ a in f.support ∪ g.support, h a ((f + g) a) :
finset.prod_subset support_add $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]
... = (∏ a in f.support ∪ g.support, h a (f a)) *
(∏ a in f.support ∪ g.support, h a (g a)) :
by simp only [add_apply, h_add, finset.prod_mul_distrib]
... = _ : by rw [f_eq, g_eq]
lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β}
{h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) :
(f - g).sum h = f.sum h - g.sum h :=
have h_zero : ∀a, h a 0 = 0,
from assume a,
have h a (0 - 0) = h a 0 - h a 0, from h_sub a 0 0,
by simpa only [sub_self] using this,
have h_neg : ∀a b, h a (- b) = - h a b,
from assume a b,
have h a (0 - b) = h a 0 - h a b, from h_sub a 0 b,
by simpa only [h_zero, zero_sub] using this,
have h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂,
from assume a b₁ b₂,
have h a (b₁ - (- b₂)) = h a b₁ - h a (- b₂), from h_sub a b₁ (-b₂),
by simpa only [h_neg, sub_neg_eq_add] using this,
calc (f - g).sum h = (f + - g).sum h : rfl
... = f.sum h + - g.sum h : by simp only [sum_add_index h_zero h_add, sum_neg_index h_zero,
h_neg, sum_neg]
... = f.sum h - g.sum h : rfl
@[to_additive]
lemma prod_finset_sum_index [add_comm_monoid β] [comm_monoid γ]
{s : finset ι} {g : ι → α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
∏ i in s, (g i).prod h = (∑ i in s, g i).prod h :=
finset.induction_on s rfl $ λ a s has ih,
by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add]
@[to_additive]
lemma prod_sum_index
[add_comm_monoid β₁] [add_comm_monoid β] [comm_monoid γ]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f.sum g).prod h = f.prod (λa b, (g a b).prod h) :=
(prod_finset_sum_index h_zero h_add).symm
lemma multiset_sum_sum_index
[add_comm_monoid β] [add_comm_monoid γ]
(f : multiset (α →₀ β)) (h : α → β → γ)
(h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : β), h a (b₁ + b₂) = h a b₁ + h a b₂) :
(f.sum.sum h) = (f.map $ λg:α →₀ β, g.sum h).sum :=
multiset.induction_on f rfl $ assume a s ih,
by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih]
lemma multiset_map_sum [has_zero β] {f : α →₀ β} {m : γ → δ} {h : α → β → multiset γ} :
multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) :=
(f.support.sum_hom _).symm
lemma multiset_sum_sum [has_zero β] [add_comm_monoid γ] {f : α →₀ β} {h : α → β → multiset γ} :
multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) :=
(f.support.sum_hom multiset.sum).symm
section map_range
variables
[add_comm_monoid β₁] [add_comm_monoid β₂]
(f : β₁ → β₂) [hf : is_add_monoid_hom f]
instance is_add_monoid_hom_map_range :
is_add_monoid_hom (map_range f hf.map_zero : (α →₀ β₁) → (α →₀ β₂)) :=
{ map_zero := map_range_zero, map_add := λ a b, map_range_add hf.map_add _ _ }
lemma map_range_multiset_sum (m : multiset (α →₀ β₁)) :
map_range f hf.map_zero m.sum = (m.map $ λx, map_range f hf.map_zero x).sum :=
(m.sum_hom (map_range f hf.map_zero)).symm
lemma map_range_finset_sum {ι : Type*} (s : finset ι) (g : ι → (α →₀ β₁)) :
map_range f hf.map_zero (∑ x in s, g x) = ∑ x in s, map_range f hf.map_zero (g x) :=
by rw [finset.sum.equations._eqn_1, map_range_multiset_sum, multiset.map_map]; refl
end map_range
/-! ### Declarations about `map_domain` -/
section map_domain
variables [add_comm_monoid β] {v v₁ v₂ : α →₀ β}
/-- Given `f : α₁ → α₂` and `v : α₁ →₀ β`, `map_domain f v : α₂ →₀ β`
is the finitely supported function whose value at `a : α₂` is the sum
of `v x` over all `x` such that `f x = a`. -/
def map_domain (f : α₁ → α₂) (v : α₁ →₀ β) : α₂ →₀ β :=
v.sum $ λa, single (f a)
lemma map_domain_apply {f : α₁ → α₂} (hf : function.injective f) (x : α₁ →₀ β) (a : α₁) :
map_domain f x (f a) = x a :=
begin
rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same],
{ assume b _ hba, exact single_eq_of_ne (hf.ne hba) },
{ simp only [(∉), (≠), not_not, mem_support_iff],
assume h,
rw [h, single_zero],
refl }
end
lemma map_domain_notin_range {f : α₁ → α₂} (x : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) :
map_domain f x a = 0 :=
begin
rw [map_domain, sum_apply, sum],
exact finset.sum_eq_zero
(assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _)
end
lemma map_domain_id : map_domain id v = v :=
sum_single _
lemma map_domain_comp {f : α → α₁} {g : α₁ → α₂} :
map_domain (g ∘ f) v = map_domain g (map_domain f v) :=
begin
refine ((sum_sum_index _ _).trans _).symm,
{ intros, exact single_zero },
{ intros, exact single_add },
refine sum_congr rfl (λ _ _, sum_single_index _),
{ exact single_zero }
end
lemma map_domain_single {f : α → α₁} {a : α} {b : β} : map_domain f (single a b) = single (f a) b :=
sum_single_index single_zero
@[simp] lemma map_domain_zero {f : α → α₂} : map_domain f 0 = (0 : α₂ →₀ β) :=
sum_zero_index
lemma map_domain_congr {f g : α → α₂} (h : ∀x∈v.support, f x = g x) :
v.map_domain f = v.map_domain g :=
finset.sum_congr rfl $ λ _ H, by simp only [h _ H]
lemma map_domain_add {f : α → α₂} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ :=
sum_add_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_finset_sum {f : α → α₂} {s : finset ι} {v : ι → α →₀ β} :
map_domain f (∑ i in s, v i) = ∑ i in s, map_domain f (v i) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_sum [has_zero β₁] {f : α → α₂} {s : α →₀ β₁} {v : α → β₁ → α →₀ β} :
map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_support {f : α → α₂} {s : α →₀ β} :
(s.map_domain f).support ⊆ s.support.image f :=
finset.subset.trans support_sum $
finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $
by rw [finset.bind_singleton]; exact subset.refl _
@[to_additive]
lemma prod_map_domain_index [comm_monoid γ] {f : α → α₂} {s : α →₀ β}
{h : α₂ → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(s.map_domain f).prod h = s.prod (λa b, h (f a) b) :=
(prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _)
lemma emb_domain_eq_map_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) :
emb_domain f v = map_domain f v :=
begin
ext a,
by_cases a ∈ set.range f,
{ rcases h with ⟨a, rfl⟩,
rw [map_domain_apply f.inj, emb_domain_apply] },
{ rw [map_domain_notin_range, emb_domain_notin_range]; assumption }
end
lemma injective_map_domain {f : α₁ → α₂} (hf : function.injective f) :
function.injective (map_domain f : (α₁ →₀ β) → (α₂ →₀ β)) :=
begin
assume v₁ v₂ eq, ext a,
have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq },
rwa [map_domain_apply hf, map_domain_apply hf] at this,
end
end map_domain
/-! ### Declarations about `comap_domain` -/
section comap_domain
/-- Given `f : α₁ → α₂`, `l : α₂ →₀ γ` and a proof `hf` that `f` is injective on
the preimage of `l.support`, `comap_domain f l hf` is the finitely supported function
from `α₁` to `γ` given by composing `l` with `f`. -/
def comap_domain {α₁ α₂ γ : Type*} [has_zero γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : α₁ →₀ γ :=
{ support := l.support.preimage hf,
to_fun := (λ a, l (f a)),
mem_support_to_fun :=
begin
intros a,
simp only [finset.mem_def.symm, finset.mem_preimage],
exact l.mem_support_to_fun (f a),
end }
@[simp]
lemma comap_domain_apply {α₁ α₂ γ : Type*} [has_zero γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' ↑l.support)) (a : α₁) :
comap_domain f l hf a = l (f a) :=
rfl
lemma sum_comap_domain {α₁ α₂ β γ : Type*} [has_zero β] [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ β) (g : α₂ → β → γ)
(hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) :
(comap_domain f l hf.inj_on).sum (g ∘ f) = l.sum g :=
begin
simp [sum],
simp [comap_domain, finset.sum_preimage f _ _ (λ (x : α₂), g x (l x))]
end
lemma eq_zero_of_comap_domain_eq_zero {α₁ α₂ γ : Type*} [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) :
comap_domain f l hf.inj_on = 0 → l = 0 :=
begin
rw [← support_eq_empty, ← support_eq_empty, comap_domain],
simp only [finset.ext_iff, finset.not_mem_empty, iff_false, mem_preimage],
assume h a ha,
cases hf.2.2 ha with b hb,
exact h b (hb.2.symm ▸ ha)
end
lemma map_domain_comap_domain {α₁ α₂ γ : Type*} [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ γ)
(hf : function.injective f) (hl : ↑l.support ⊆ set.range f):
map_domain f (comap_domain f l (hf.inj_on _)) = l :=
begin
ext a,
by_cases h_cases: a ∈ set.range f,
{ rcases set.mem_range.1 h_cases with ⟨b, hb⟩,
rw [hb.symm, map_domain_apply hf, comap_domain_apply] },
{ rw map_domain_notin_range _ _ h_cases,
by_contra h_contr,
apply h_cases (hl $ finset.mem_coe.2 $ mem_support_iff.2 $ λ h, h_contr h.symm) }
end
end comap_domain
/-! ### Declarations about `filter` -/
section filter
section has_zero
variables [has_zero β] (p : α → Prop) (f : α →₀ β)
/-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/
def filter (p : α → Prop) (f : α →₀ β) : α →₀ β :=
on_finset f.support (λa, if p a then f a else 0) $ λ a H,
mem_support_iff.2 $ λ h, by rw [h, if_t_t] at H; exact H rfl
@[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a :=
if_pos h
@[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 :=
if_neg h
@[simp] lemma support_filter : (f.filter p).support = f.support.filter p :=
finset.ext $ assume a, if H : p a
then by simp only [mem_support_iff, filter_apply_pos _ _ H, mem_filter, H, and_true]
else by simp only [mem_support_iff, filter_apply_neg _ _ H, mem_filter, H, and_false, ne.def,
ne_self_iff_false]
lemma filter_zero : (0 : α →₀ β).filter p = 0 :=
by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty]
@[simp] lemma filter_single_of_pos
{a : α} {b : β} (h : p a) : (single a b).filter p = single a b :=
ext $ λ x, begin
by_cases h' : p x,
{ simp only [h', filter_apply_pos] },
{ simp only [h', filter_apply_neg, not_false_iff],
rw single_eq_of_ne, rintro rfl, exact h' h }
end
@[simp] lemma filter_single_of_neg
{a : α} {b : β} (h : ¬ p a) : (single a b).filter p = 0 :=
ext $ λ x, begin
by_cases h' : p x,
{ simp only [h', filter_apply_pos, zero_apply], rw single_eq_of_ne, rintro rfl, exact h h' },
{ simp only [h', finsupp.zero_apply, not_false_iff, filter_apply_neg] }
end
end has_zero
lemma filter_pos_add_filter_neg [add_monoid β] (f : α →₀ β) (p : α → Prop) :
f.filter p + f.filter (λa, ¬ p a) = f :=
ext $ assume a, if H : p a
then by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_not, add_zero]
else by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_false_iff, zero_add]
end filter
/-! ### Declarations about `frange` -/
section frange
variables [has_zero β]
/-- `frange f` is the image of `f` on the support of `f`. -/
def frange (f : α →₀ β) : finset β := finset.image f f.support
theorem mem_frange {f : α →₀ β} {y : β} :
y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y :=
finset.mem_image.trans
⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩,
λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩
theorem zero_not_mem_frange {f : α →₀ β} : (0:β) ∉ f.frange :=
λ H, (mem_frange.1 H).1 rfl
theorem frange_single {x : α} {y : β} : frange (single x y) ⊆ {y} :=
λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸
(by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc])
end frange
/-! ### Declarations about `subtype_domain` -/
section subtype_domain
variables {α' : Type*} [has_zero δ] {p : α → Prop}
section zero
variables [has_zero β] {v v' : α' →₀ β}
/-- `subtype_domain p f` is the restriction of the finitely supported function
`f` to the subtype `p`. -/
def subtype_domain (p : α → Prop) (f : α →₀ β) : (subtype p →₀ β) :=
⟨f.support.subtype p, f ∘ subtype.val, λ a, by simp only [mem_subtype, mem_support_iff]⟩
@[simp] lemma support_subtype_domain {f : α →₀ β} :
(subtype_domain p f).support = f.support.subtype p :=
rfl
@[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ β} :
(subtype_domain p v) a = v (a.val) :=
rfl
@[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ β) = 0 :=
rfl
@[to_additive]
lemma prod_subtype_domain_index [comm_monoid γ] {v : α →₀ β}
{h : α → β → γ} (hp : ∀x∈v.support, p x) :
(v.subtype_domain p).prod (λa b, h a.1 b) = v.prod h :=
prod_bij (λp _, p.val)
(λ _, mem_subtype.1)
(λ _ _, rfl)
(λ _ _ _ _, subtype.eq)
(λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩)
end zero
section monoid
variables [add_monoid β] {v v' : α' →₀ β}
@[simp] lemma subtype_domain_add {v v' : α →₀ β} :
(v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p :=
ext $ λ _, rfl
instance subtype_domain.is_add_monoid_hom :
is_add_monoid_hom (subtype_domain p : (α →₀ β) → subtype p →₀ β) :=
{ map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero }
@[simp] lemma filter_add {v v' : α →₀ β} :
(v + v').filter p = v.filter p + v'.filter p :=
ext $ λ a, begin
by_cases p a,
{ simp only [h, filter_apply_pos, add_apply] },
{ simp only [h, add_zero, add_apply, not_false_iff, filter_apply_neg] }
end
instance filter.is_add_monoid_hom (p : α → Prop) :
is_add_monoid_hom (filter p : (α →₀ β) → (α →₀ β)) :=
{ map_zero := filter_zero p, map_add := λ x y, filter_add }
end monoid
section comm_monoid
variables [add_comm_monoid β]
lemma subtype_domain_sum {s : finset γ} {h : γ → α →₀ β} :
(∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p :=
eq.symm (s.sum_hom _)
lemma subtype_domain_finsupp_sum {s : γ →₀ δ} {h : γ → δ → α →₀ β} :
(s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) :=
subtype_domain_sum
lemma filter_sum (s : finset γ) (f : γ → α →₀ β) :
(∑ a in s, f a).filter p = ∑ a in s, filter p (f a) :=
(s.sum_hom (filter p)).symm
end comm_monoid
section group
variables [add_group β] {v v' : α' →₀ β}
@[simp] lemma subtype_domain_neg {v : α →₀ β} :
(- v).subtype_domain p = - v.subtype_domain p :=
ext $ λ _, rfl
@[simp] lemma subtype_domain_sub {v v' : α →₀ β} :
(v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p :=
ext $ λ _, rfl
end group
end subtype_domain
/-! ### Declarations relating `finsupp` to `multiset` -/
section multiset
/-- Given `f : α →₀ ℕ`, `f.to_multiset` is the multiset with multiplicities given by the values of
`f` on the elements of `α`. -/
def to_multiset (f : α →₀ ℕ) : multiset α :=
f.sum (λa n, n •ℕ {a})
lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 :=
rfl
lemma to_multiset_add (m n : α →₀ ℕ) :
(m + n).to_multiset = m.to_multiset + n.to_multiset :=
sum_add_index (assume a, zero_nsmul _) (assume a b₁ b₂, add_nsmul _ _ _)
lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = n •ℕ {a} :=
by rw [to_multiset, sum_single_index]; apply zero_nsmul
instance is_add_monoid_hom.to_multiset : is_add_monoid_hom (to_multiset : _ → multiset α) :=
{ map_zero := to_multiset_zero, map_add := to_multiset_add }
lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.card_zero, sum_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.card_add, ih, sum_add_index, to_multiset_single,
sum_single_index, multiset.card_smul, multiset.singleton_eq_singleton,
multiset.card_singleton, mul_one]; intros; refl }
end
lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) :
f.to_multiset.map g = (f.map_domain g).to_multiset :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single,
to_multiset_single, to_multiset_add, to_multiset_single,
is_add_monoid_hom.map_nsmul (multiset.map g)],
refl }
end
lemma prod_to_multiset [comm_monoid α] (f : α →₀ ℕ) :
f.to_multiset.prod = f.prod (λa n, a ^ n) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index,
finsupp.prod_single_index, multiset.prod_smul, multiset.singleton_eq_singleton,
multiset.prod_singleton],
{ exact pow_zero a },
{ exact pow_zero },
{ exact pow_add } }
end
lemma to_finset_to_multiset (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.to_finset_zero, support_zero] },
{ assume a n f ha hn ih,
rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq,
support_single_ne_zero hn, multiset.to_finset_nsmul _ _ hn,
multiset.singleton_eq_singleton, multiset.to_finset_cons, multiset.to_finset_zero],
refl,
refine disjoint.mono_left support_single_subset _,
rwa [finset.singleton_disjoint] }
end
@[simp] lemma count_to_multiset (f : α →₀ ℕ) (a : α) :
f.to_multiset.count a = f a :=
calc f.to_multiset.count a = f.sum (λx n, (n •ℕ {x} : multiset α).count a) :
(f.support.sum_hom $ multiset.count a).symm
... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_smul]
... = f.sum (λx n, n * (x :: 0 : multiset α).count a) : rfl
... = f a * (a :: 0 : multiset α).count a : sum_eq_single _
(λ a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero])
(λ H, by simp only [not_mem_support_iff.1 H, zero_mul])
... = f a : by simp only [multiset.count_singleton, mul_one]
/-- Given `m : multiset α`, `of_multiset m` is the finitely supported function from `α` to `ℕ`
given by the multiplicities of the elements of `α` in `m`. -/
def of_multiset (m : multiset α) : α →₀ ℕ :=
on_finset m.to_finset (λa, m.count a) $ λ a H, multiset.mem_to_finset.2 $
by_contradiction (mt multiset.count_eq_zero.2 H)
@[simp] lemma of_multiset_apply (m : multiset α) (a : α) :
of_multiset m a = m.count a :=
rfl
/-- `equiv_multiset` defines an `equiv` between finitely supported functions
from `α` to `ℕ` and multisets on `α`. -/
def equiv_multiset : (α →₀ ℕ) ≃ (multiset α) :=
⟨ to_multiset, of_multiset,
assume f, finsupp.ext $ λ a, by rw [of_multiset_apply, count_to_multiset],
assume m, multiset.ext.2 $ λ a, by rw [count_to_multiset, of_multiset_apply] ⟩
lemma mem_support_multiset_sum [add_comm_monoid β]
{s : multiset (α →₀ β)} (a : α) :
a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ β).support :=
multiset.induction_on s false.elim
begin
assume f s ih ha,
by_cases a ∈ f.support,
{ exact ⟨f, multiset.mem_cons_self _ _, h⟩ },
{ simp only [multiset.sum_cons, mem_support_iff, add_apply,
not_mem_support_iff.1 h, zero_add] at ha,
rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩,
exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ }
end
lemma mem_support_finset_sum [add_comm_monoid β]
{s : finset γ} {h : γ → α →₀ β} (a : α) (ha : a ∈ (∑ c in s, h c).support) : ∃c∈s, a ∈ (h c).support :=
let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in
let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in
⟨c, hc, eq.symm ▸ hfa⟩
lemma mem_support_single [has_zero β] (a a' : α) (b : β) :
a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 :=
⟨λ H : (a ∈ ite _ _ _), if h : b = 0
then by rw if_pos h at H; exact H.elim
else ⟨by rw if_neg h at H; exact mem_singleton.1 H, h⟩,
λ ⟨h1, h2⟩, show a ∈ ite _ _ _, by rw [if_neg h2]; exact mem_singleton.2 h1⟩
end multiset
/-! ### Declarations about `curry` and `uncurry` -/
section curry_uncurry
/-- Given a finitely supported function `f` from a product type `α × β` to `γ`,
`curry f` is the "curried" finitely supported function from `α` to the type of
finitely supported functions from `β` to `γ`. -/
protected def curry [add_comm_monoid γ]
(f : (α × β) →₀ γ) : α →₀ (β →₀ γ) :=
f.sum $ λp c, single p.1 (single p.2 c)
lemma sum_curry_index
[add_comm_monoid γ] [add_comm_monoid δ]
(f : (α × β) →₀ γ) (g : α → β → γ → δ)
(hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) :
f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) :=
begin
rw [finsupp.curry],
transitivity,
{ exact sum_sum_index (assume a, sum_zero_index)
(assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) },
congr, funext p c,
transitivity,
{ exact sum_single_index sum_zero_index },
exact sum_single_index (hg₀ _ _)
end
/-- Given a finitely supported function `f` from `α` to the type of
finitely supported functions from `β` to `γ`,
`uncurry f` is the "uncurried" finitely supported function from `α × β` to `γ`. -/
protected def uncurry [add_comm_monoid γ] (f : α →₀ (β →₀ γ)) : (α × β) →₀ γ :=
f.sum $ λa g, g.sum $ λb c, single (a, b) c
/-- `finsupp_prod_equiv` defines the `equiv` between `((α × β) →₀ γ)` and `(α →₀ (β →₀ γ))` given by
currying and uncurrying. -/
def finsupp_prod_equiv [add_comm_monoid γ] : ((α × β) →₀ γ) ≃ (α →₀ (β →₀ γ)) :=
by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [
finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff,
forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single]
lemma filter_curry [add_comm_monoid β] (f : α₁ × α₂ →₀ β) (p : α₁ → Prop) :
(f.filter (λa:α₁×α₂, p a.1)).curry = f.curry.filter p :=
begin
rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum,
@filter_sum _ (α₂ →₀ β) _ p _ f.support _],
rw [support_filter, sum_filter],
refine finset.sum_congr rfl _,
rintros ⟨a₁, a₂⟩ ha,
dsimp only,
split_ifs,
{ rw [filter_apply_pos, filter_single_of_pos]; exact h },
{ rwa [filter_single_of_neg] }
end
lemma support_curry [add_comm_monoid β] (f : α₁ × α₂ →₀ β) :
f.curry.support ⊆ f.support.image prod.fst :=
begin
rw ← finset.bind_singleton,
refine finset.subset.trans support_sum _,
refine finset.bind_mono (assume a _, support_single_subset)
end
end curry_uncurry
section
variables [group γ] [mul_action γ α] [add_comm_monoid β]
/--
Scalar multiplication by a group element g,
given by precomposition with the action of g⁻¹ on the domain.
-/
def comap_has_scalar : has_scalar γ (α →₀ β) :=
{ smul := λ g f, f.comap_domain (λ a, g⁻¹ • a)
(λ a a' m m' h, by simpa [←mul_smul] using (congr_arg (λ a, g • a) h)) }
local attribute [instance] comap_has_scalar
/--
Scalar multiplication by a group element,
given by precomposition with the action of g⁻¹ on the domain,
is multiplicative in g.
-/
def comap_mul_action : mul_action γ (α →₀ β) :=
{ one_smul := λ f, by { ext, dsimp [(•)], simp, },
mul_smul := λ g g' f, by { ext, dsimp [(•)], simp [mul_smul], }, }
local attribute [instance] comap_mul_action
/--
Scalar multiplication by a group element,
given by precomposition with the action of g⁻¹ on the domain,
is additive in the second argument.
-/
def comap_distrib_mul_action :
distrib_mul_action γ (α →₀ β) :=
{ smul_zero := λ g, by { ext, dsimp [(•)], simp, },
smul_add := λ g f f', by { ext, dsimp [(•)], simp, }, }
/--
Scalar multiplication by a group element on finitely supported functions on a group,
given by precomposition with the action of g⁻¹. -/
def comap_distrib_mul_action_self :
distrib_mul_action γ (γ →₀ β) :=
@finsupp.comap_distrib_mul_action γ β γ _ (mul_action.regular γ) _
@[simp]
lemma comap_smul_single (g : γ) (a : α) (b : β) :
g • single a b = single (g • a) b :=
begin
ext a',
dsimp [(•)],
by_cases h : g • a = a',
{ subst h, simp [←mul_smul], },
{ simp [single_eq_of_ne h], rw [single_eq_of_ne],
rintro rfl, simpa [←mul_smul] using h, }
end
@[simp]
lemma comap_smul_apply (g : γ) (f : α →₀ β) (a : α) :
(g • f) a = f (g⁻¹ • a) := rfl
end
section
instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : has_scalar γ (α →₀ β) :=
⟨λa v, v.map_range ((•) a) (smul_zero _)⟩
variables (α β)
@[simp] lemma smul_apply' {R:semiring γ} [add_comm_monoid β] [semimodule γ β]
{a : α} {b : γ} {v : α →₀ β} : (b • v) a = b • (v a) :=
rfl
instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : semimodule γ (α →₀ β) :=
{ smul := (•),
smul_add := λ a x y, ext $ λ _, smul_add _ _ _,
add_smul := λ a x y, ext $ λ _, add_smul _ _ _,
one_smul := λ x, ext $ λ _, one_smul _ _,
mul_smul := λ r s x, ext $ λ _, mul_smul _ _ _,
zero_smul := λ x, ext $ λ _, zero_smul _ _,
smul_zero := λ x, ext $ λ _, smul_zero _ }
variables {α β} (γ)
/-- Evaluation at point as a linear map. This version assumes that the codomain is a semimodule
over some semiring. See also `leval`. -/
def leval' [semiring γ] [add_comm_monoid β] [semimodule γ β] (a : α) :
(α →₀ β) →ₗ[γ] β :=
⟨λ g, g a, λ _ _, add_apply, λ _ _, rfl⟩
@[simp] lemma coe_leval' [semiring γ] [add_comm_monoid β] [semimodule γ β] (a : α) (g : α →₀ β) :
leval' γ a g = g a :=
rfl
variable {γ}
/-- Evaluation at point as a linear map. This version assumes that the codomain is a semiring. -/
def leval [semiring β] (a : α) : (α →₀ β) →ₗ[β] β := leval' β a
@[simp] lemma coe_leval [semiring β] (a : α) (g : α →₀ β) : leval a g = g a := rfl
lemma support_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {g : α →₀ β} :
(b • g).support ⊆ g.support :=
λ a, by simp only [smul_apply', mem_support_iff, ne.def]; exact mt (λ h, h.symm ▸ smul_zero _)
section
variables {α' : Type*} [has_zero δ] {p : α → Prop}
@[simp] lemma filter_smul {R : semiring γ} [add_comm_monoid β] [semimodule γ β]
{b : γ} {v : α →₀ β} : (b • v).filter p = b • v.filter p :=
ext $ λ a, begin
by_cases p a,
{ simp only [h, smul_apply', filter_apply_pos] },
{ simp only [h, smul_apply', not_false_iff, filter_apply_neg, smul_zero] }
end
end
lemma map_domain_smul {α'} {R : semiring γ} [add_comm_monoid β] [semimodule γ β]
{f : α → α'} (b : γ) (v : α →₀ β) : map_domain f (b • v) = b • map_domain f v :=
begin
change map_domain f (map_range _ _ _) = map_range _ _ _,
apply finsupp.induction v, { simp only [map_domain_zero, map_range_zero] },
intros a b v' hv₁ hv₂ IH,
rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add,
map_range_single, map_domain_single, map_domain_single, map_range_single];
apply smul_add
end
@[simp] lemma smul_single {R : semiring γ} [add_comm_monoid β] [semimodule γ β]
(c : γ) (a : α) (b : β) : c • finsupp.single a b = finsupp.single a (c • b) :=
ext $ λ a', by by_cases a = a';
[{ subst h, simp only [smul_apply', single_eq_same] },
simp only [h, smul_apply', ne.def, not_false_iff, single_eq_of_ne, smul_zero]]
@[simp] lemma smul_single' {R : semiring γ}
(c : γ) (a : α) (b : γ) : c • finsupp.single a b = finsupp.single a (c * b) :=
smul_single _ _ _
end
@[simp] lemma smul_apply [semiring β] {a : α} {b : β} {v : α →₀ β} :
(b • v) a = b • (v a) :=
rfl
lemma sum_smul_index [ring β] [add_comm_monoid γ] {g : α →₀ β} {b : β} {h : α → β → γ}
(h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) :=
finsupp.sum_map_range_index h0
section
variables [semiring β] [semiring γ]
lemma sum_mul (b : γ) (s : α →₀ β) {f : α → β → γ} :
(s.sum f) * b = s.sum (λ a c, (f a (s a)) * b) :=
by simp only [finsupp.sum, finset.sum_mul]
lemma mul_sum (b : γ) (s : α →₀ β) {f : α → β → γ} :
b * (s.sum f) = s.sum (λ a c, b * (f a (s a))) :=
by simp only [finsupp.sum, finset.mul_sum]
protected lemma eq_zero_of_zero_eq_one
(zero_eq_one : (0 : β) = 1) (l : α →₀ β) : l = 0 :=
by ext i; simp only [eq_zero_of_zero_eq_one β zero_eq_one (l i), finsupp.zero_apply]
end
/-- Given an `add_comm_monoid β` and `s : set α`, `restrict_support_equiv s β` is the `equiv`
between the subtype of finitely supported functions with support contained in `s` and
the type of finitely supported functions from `s`. -/
def restrict_support_equiv (s : set α) (β : Type*) [add_comm_monoid β] :
{f : α →₀ β // ↑f.support ⊆ s } ≃ (s →₀ β):=
begin
refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩,
{ refine set.subset.trans (finset.coe_subset.2 map_domain_support) _,
rw [finset.coe_image, set.image_subset_iff],
exact assume x hx, x.2 },
{ rintros ⟨f, hf⟩,
apply subtype.eq,
ext a,
dsimp only,
refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _),
{ rcases h with ⟨x, rfl⟩,
rw [map_domain_apply subtype.val_injective, subtype_domain_apply] },
{ convert map_domain_notin_range _ _ h,
rw [← not_mem_support_iff],
refine mt _ h,
exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } },
{ assume f,
ext ⟨a, ha⟩,
dsimp only,
rw [subtype_domain_apply, map_domain_apply subtype.val_injective] }
end
/-- Given `add_comm_monoid β` and `e : α₁ ≃ α₂`, `dom_congr e` is the corresponding `equiv` between
`α₁ →₀ β` and `α₂ →₀ β`. -/
protected def dom_congr [add_comm_monoid β] (e : α₁ ≃ α₂) : (α₁ →₀ β) ≃ (α₂ →₀ β) :=
⟨map_domain e, map_domain e.symm,
begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.symm_apply_apply],
exact map_domain_id
end,
begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.apply_symm_apply],
exact map_domain_id
end⟩
/-! ### Declarations about sigma types -/
section sigma
variables {αs : ι → Type*} [has_zero β] (l : (Σ i, αs i) →₀ β)
/-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β` and
an index element `i : ι`, `split l i` is the `i`th component of `l`,
a finitely supported function from `as i` to `β`. -/
def split (i : ι) : αs i →₀ β :=
l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2)
lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ :=
begin
dunfold split,
rw comap_domain_apply
end
/-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`,
`split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/
def split_support : finset ι := l.support.image sigma.fst
lemma mem_split_support_iff_nonzero (i : ι) :
i ∈ split_support l ↔ split l i ≠ 0 :=
begin
rw [split_support, mem_image, ne.def, ← support_eq_empty, ← ne.def,
← finset.nonempty_iff_ne_empty, split, comap_domain, finset.nonempty],
simp only [exists_prop, finset.mem_preimage, exists_and_distrib_right, exists_eq_right,
mem_support_iff, sigma.exists, ne.def]
end
/-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and
an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a
finitely supported function from the index type `ι` to `γ` given by composing `g i` with
`split l i`. -/
def split_comp [has_zero γ] (g : Π i, (αs i →₀ β) → γ)
(hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ γ :=
{ support := split_support l,
to_fun := λ i, g i (split l i),
mem_support_to_fun :=
begin
intros i,
rw [mem_split_support_iff_nonzero, not_iff_not, hg],
end }
lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) :=
by simp only [finset.ext_iff, split_support, split, comap_domain, mem_image,
mem_preimage, sigma.forall, mem_sigma]; tauto
lemma sigma_sum [add_comm_monoid γ] (f : (Σ (i : ι), αs i) → β → γ) :
l.sum f = ∑ i in split_support l, (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b) :=
by simp only [sum, sigma_support, sum_sigma, split_apply]
end sigma
end finsupp
/-! ### Declarations relating `multiset` to `finsupp` -/
namespace multiset
/-- Given a multiset `s`, `s.to_finsupp` returns the finitely supported function on `ℕ` given by
the multiplicities of the elements of `s`. -/
def to_finsupp (s : multiset α) : α →₀ ℕ :=
{ support := s.to_finset,
to_fun := λ a, s.count a,
mem_support_to_fun := λ a,
begin
rw mem_to_finset,
convert not_iff_not_of_iff (count_eq_zero.symm),
rw not_not
end }
@[simp] lemma to_finsupp_support (s : multiset α) :
s.to_finsupp.support = s.to_finset :=
rfl
@[simp] lemma to_finsupp_apply (s : multiset α) (a : α) :
s.to_finsupp a = s.count a :=
rfl
@[simp] lemma to_finsupp_zero :
to_finsupp (0 : multiset α) = 0 :=
finsupp.ext $ λ a, count_zero a
@[simp] lemma to_finsupp_add (s t : multiset α) :
to_finsupp (s + t) = to_finsupp s + to_finsupp t :=
finsupp.ext $ λ a, count_add a s t
lemma to_finsupp_singleton (a : α) :
to_finsupp {a} = finsupp.single a 1 :=
finsupp.ext $ λ b,
if h : a = b then by rw [to_finsupp_apply, finsupp.single_apply, h, if_pos rfl,
singleton_eq_singleton, count_singleton] else
begin
rw [to_finsupp_apply, finsupp.single_apply, if_neg h, count_eq_zero,
singleton_eq_singleton, mem_singleton],
rintro rfl, exact h rfl
end
namespace to_finsupp
instance : is_add_monoid_hom (to_finsupp : multiset α → α →₀ ℕ) :=
{ map_zero := to_finsupp_zero,
map_add := to_finsupp_add }
end to_finsupp
@[simp] lemma to_finsupp_to_multiset (s : multiset α) :
s.to_finsupp.to_multiset = s :=
ext.2 $ λ a, by rw [finsupp.count_to_multiset, to_finsupp_apply]
end multiset
/-! ### Declarations about order(ed) instances on `finsupp` -/
namespace finsupp
variables {σ : Type*}
instance [preorder α] [has_zero α] : preorder (σ →₀ α) :=
{ le := λ f g, ∀ s, f s ≤ g s,
le_refl := λ f s, le_refl _,
le_trans := λ f g h Hfg Hgh s, le_trans (Hfg s) (Hgh s) }
instance [partial_order α] [has_zero α] : partial_order (σ →₀ α) :=
{ le_antisymm := λ f g hfg hgf, ext $ λ s, le_antisymm (hfg s) (hgf s),
.. finsupp.preorder }
instance [ordered_cancel_add_comm_monoid α] :
add_left_cancel_semigroup (σ →₀ α) :=
{ add_left_cancel := λ a b c h, ext $ λ s,
by { rw ext_iff at h, exact add_left_cancel (h s) },
.. finsupp.add_monoid }
instance [ordered_cancel_add_comm_monoid α] :
add_right_cancel_semigroup (σ →₀ α) :=
{ add_right_cancel := λ a b c h, ext $ λ s,
by { rw ext_iff at h, exact add_right_cancel (h s) },
.. finsupp.add_monoid }
instance [ordered_cancel_add_comm_monoid α] :
ordered_cancel_add_comm_monoid (σ →₀ α) :=
{ add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s),
le_of_add_le_add_left := λ a b c h s, le_of_add_le_add_left (h s),
.. finsupp.add_comm_monoid, .. finsupp.partial_order,
.. finsupp.add_left_cancel_semigroup, .. finsupp.add_right_cancel_semigroup }
lemma le_iff [canonically_ordered_add_monoid α] (f g : σ →₀ α) :
f ≤ g ↔ ∀ s ∈ f.support, f s ≤ g s :=
⟨λ h s hs, h s,
λ h s, if H : s ∈ f.support then h s H else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩
@[simp] lemma add_eq_zero_iff [canonically_ordered_add_monoid α] (f g : σ →₀ α) :
f + g = 0 ↔ f = 0 ∧ g = 0 :=
begin
split,
{ assume h,
split,
all_goals
{ ext s,
suffices H : f s + g s = 0,
{ rw add_eq_zero_iff at H, cases H, assumption },
show (f + g) s = 0,
rw h, refl } },
{ rintro ⟨rfl, rfl⟩, rw add_zero }
end
attribute [simp] to_multiset_zero to_multiset_add
@[simp] lemma to_multiset_to_finsupp (f : σ →₀ ℕ) :
f.to_multiset.to_finsupp = f :=
ext $ λ s, by rw [multiset.to_finsupp_apply, count_to_multiset]
lemma to_multiset_strict_mono : strict_mono (@to_multiset σ) :=
λ m n h,
begin
rw lt_iff_le_and_ne at h ⊢, cases h with h₁ h₂,
split,
{ rw multiset.le_iff_count, intro s, erw [count_to_multiset m s, count_to_multiset], exact h₁ s },
{ intro H, apply h₂, replace H := congr_arg multiset.to_finsupp H,
simpa only [to_multiset_to_finsupp] using H }
end
lemma sum_id_lt_of_lt (m n : σ →₀ ℕ) (h : m < n) :
m.sum (λ _, id) < n.sum (λ _, id) :=
begin
rw [← card_to_multiset, ← card_to_multiset],
apply multiset.card_lt_of_lt,
exact to_multiset_strict_mono h
end
variable (σ)
/-- The order on `σ →₀ ℕ` is well-founded.-/
lemma lt_wf : well_founded (@has_lt.lt (σ →₀ ℕ) _) :=
subrelation.wf (sum_id_lt_of_lt) $ inv_image.wf _ nat.lt_wf
instance decidable_le : decidable_rel (@has_le.le (σ →₀ ℕ) _) :=
λ m n, by rw le_iff; apply_instance
variable {σ}
/-- The `finsupp` counterpart of `multiset.antidiagonal`: the antidiagonal of
`s : σ →₀ ℕ` consists of all pairs `(t₁, t₂) : (σ →₀ ℕ) × (σ →₀ ℕ)` such that `t₁ + t₂ = s`.
The finitely supported function `antidiagonal s` is equal to the multiplicities of these pairs. -/
def antidiagonal (f : σ →₀ ℕ) : ((σ →₀ ℕ) × (σ →₀ ℕ)) →₀ ℕ :=
(f.to_multiset.antidiagonal.map (prod.map multiset.to_finsupp multiset.to_finsupp)).to_finsupp
lemma mem_antidiagonal_support {f : σ →₀ ℕ} {p : (σ →₀ ℕ) × (σ →₀ ℕ)} :
p ∈ (antidiagonal f).support ↔ p.1 + p.2 = f :=
begin
erw [multiset.mem_to_finset, multiset.mem_map],
split,
{ rintros ⟨⟨a, b⟩, h, rfl⟩,
rw multiset.mem_antidiagonal at h,
simpa only [to_multiset_to_finsupp, multiset.to_finsupp_add]
using congr_arg multiset.to_finsupp h},
{ intro h,
refine ⟨⟨p.1.to_multiset, p.2.to_multiset⟩, _, _⟩,
{ simpa only [multiset.mem_antidiagonal, to_multiset_add]
using congr_arg to_multiset h},
{ rw [prod.map, to_multiset_to_finsupp, to_multiset_to_finsupp, prod.mk.eta] } }
end
@[simp] lemma antidiagonal_zero : antidiagonal (0 : σ →₀ ℕ) = single (0,0) 1 :=
by rw [← multiset.to_finsupp_singleton]; refl
lemma swap_mem_antidiagonal_support {n : σ →₀ ℕ} {f} (hf : f ∈ (antidiagonal n).support) :
f.swap ∈ (antidiagonal n).support :=
by simpa only [mem_antidiagonal_support, add_comm, prod.swap] using hf
/-- Let `n : σ →₀ ℕ` be a finitely supported function.
The set of `m : σ →₀ ℕ` that are coordinatewise less than or equal to `n`,
is a finite set. -/
lemma finite_le_nat (n : σ →₀ ℕ) : set.finite {m | m ≤ n} :=
begin
let I := {i // i ∈ n.support},
let k : ℕ := ∑ i in n.support, n i,
let f : (σ →₀ ℕ) → (I → fin (k + 1)) := λ m i, m i,
have hf : ∀ m ≤ n, ∀ i, (f m i : ℕ) = m i,
{ intros m hm i,
apply fin.coe_coe_of_lt,
calc m i ≤ n i : hm i
... < k + 1 : nat.lt_succ_iff.mpr (single_le_sum (λ _ _, nat.zero_le _) i.2) },
have f_im : set.finite (f '' {m | m ≤ n}) := set.finite.of_fintype _,
suffices f_inj : set.inj_on f {m | m ≤ n},
{ exact set.finite_of_finite_image f_inj f_im },
intros m₁ m₂ h₁ h₂ h,
ext i,
by_cases hi : i ∈ n.support,
{ replace h := congr_fun h ⟨i, hi⟩,
rwa [fin.ext_iff, ← fin.coe_eq_val, ← fin.coe_eq_val, hf m₁ h₁, hf m₂ h₂] at h },
{ rw not_mem_support_iff at hi,
specialize h₁ i,
specialize h₂ i,
rw [hi, nat.le_zero_iff] at h₁ h₂,
rw [h₁, h₂] }
end
/-- Let `n : σ →₀ ℕ` be a finitely supported function.
The set of `m : σ →₀ ℕ` that are coordinatewise less than or equal to `n`,
but not equal to `n` everywhere, is a finite set. -/
lemma finite_lt_nat (n : σ →₀ ℕ) : set.finite {m | m < n} :=
set.finite_subset (finite_le_nat n) $ λ m, le_of_lt
end finsupp
|
321dd4c1b51a13ab02006b68638a97439f709c82
|
b2fe74b11b57d362c13326bc5651244f111fa6f4
|
/src/data/int/basic.lean
|
2015b2070ce701b6e85b485688ef0f89aa2298cc
|
[
"Apache-2.0"
] |
permissive
|
midfield/mathlib
|
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
|
775edc615ecec631d65b6180dbcc7bc26c3abc26
|
refs/heads/master
| 1,675,330,551,921
| 1,608,304,514,000
| 1,608,304,514,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 51,281
|
lean
|
/-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
The integers, with addition, multiplication, and subtraction.
-/
import data.nat.basic
import algebra.order_functions
open nat
namespace int
instance : inhabited ℤ := ⟨int.zero⟩
instance : nontrivial ℤ :=
⟨⟨0, 1, int.zero_ne_one⟩⟩
instance : comm_ring int :=
{ add := int.add,
add_assoc := int.add_assoc,
zero := int.zero,
zero_add := int.zero_add,
add_zero := int.add_zero,
neg := int.neg,
add_left_neg := int.add_left_neg,
add_comm := int.add_comm,
mul := int.mul,
mul_assoc := int.mul_assoc,
one := int.one,
one_mul := int.one_mul,
mul_one := int.mul_one,
sub := int.sub,
left_distrib := int.distrib_left,
right_distrib := int.distrib_right,
mul_comm := int.mul_comm }
/-! ### Extra instances to short-circuit type class resolution -/
-- instance : has_sub int := by apply_instance -- This is in core
instance : add_comm_monoid int := by apply_instance
instance : add_monoid int := by apply_instance
instance : monoid int := by apply_instance
instance : comm_monoid int := by apply_instance
instance : comm_semigroup int := by apply_instance
instance : semigroup int := by apply_instance
instance : add_comm_semigroup int := by apply_instance
instance : add_semigroup int := by apply_instance
instance : comm_semiring int := by apply_instance
instance : semiring int := by apply_instance
instance : ring int := by apply_instance
instance : distrib int := by apply_instance
instance : linear_ordered_comm_ring int :=
{ add_le_add_left := @int.add_le_add_left,
mul_pos := @int.mul_pos,
zero_le_one := le_of_lt int.zero_lt_one,
.. int.comm_ring, .. int.linear_order, .. int.nontrivial }
instance : linear_ordered_add_comm_group int :=
by apply_instance
theorem abs_eq_nat_abs : ∀ a : ℤ, abs a = nat_abs a
| (n : ℕ) := abs_of_nonneg $ coe_zero_le _
| -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _
theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a :=
by rw [abs_eq_nat_abs]; refl
theorem sign_mul_abs (a : ℤ) : sign a * abs a = a :=
by rw [abs_eq_nat_abs, sign_mul_nat_abs]
@[simp] lemma default_eq_zero : default ℤ = 0 := rfl
meta instance : has_to_format ℤ := ⟨λ z, to_string z⟩
meta instance : has_reflect ℤ := by tactic.mk_has_reflect_instance
attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ
attribute [simp] int.of_nat_eq_coe int.bodd
@[simp] theorem add_def {a b : ℤ} : int.add a b = a + b := rfl
@[simp] theorem mul_def {a b : ℤ} : int.mul a b = a * b := rfl
@[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl
@[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl
@[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl
@[simp, norm_cast]
theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n
@[simp, norm_cast]
theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n
@[simp, norm_cast]
theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n
@[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n :=
by rw [← int.coe_nat_zero, coe_nat_lt]
@[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 :=
by rw [← int.coe_nat_zero, coe_nat_inj']
theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 :=
not_congr coe_nat_eq_zero
@[simp] lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _)
lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n :=
⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h),
λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩
lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n)
@[simp, norm_cast] theorem coe_nat_abs (n : ℕ) : abs (n : ℤ) = n :=
abs_of_nonneg (coe_nat_nonneg n)
/-! ### succ and pred -/
/-- Immediate successor of an integer: `succ n = n + 1` -/
def succ (a : ℤ) := a + 1
/-- Immediate predecessor of an integer: `pred n = n - 1` -/
def pred (a : ℤ) := a - 1
theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl
theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _
theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _
theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _
theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a :=
by rw [neg_succ, succ_pred]
theorem neg_pred (a : ℤ) : -pred a = succ (-a) :=
by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg]
theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a :=
by rw [neg_pred, pred_succ]
theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n
theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n
theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n
theorem lt_succ_self (a : ℤ) : a < succ a :=
lt_add_of_pos_right _ zero_lt_one
theorem pred_self_lt (a : ℤ) : pred a < a :=
sub_lt_self _ zero_lt_one
theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl
theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b :=
@add_le_add_iff_right _ _ a b 1
lemma le_add_one {a b : ℤ} (h : a ≤ b) : a ≤ b + 1 :=
le_of_lt (int.lt_add_one_iff.mpr h)
theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b :=
sub_lt_iff_lt_add.trans lt_add_one_iff
theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b :=
le_sub_iff_add_le
@[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop}
(i : ℤ) (hz : p 0) (hp : ∀i : ℕ, p i → p (i + 1)) (hn : ∀i : ℕ, p (-i) → p (-i - 1)) : p i :=
begin
induction i,
{ induction i,
{ exact hz },
{ exact hp _ i_ih } },
{ have : ∀n:ℕ, p (- n),
{ intro n, induction n,
{ simp [hz] },
{ convert hn _ n_ih using 1, simp [sub_eq_neg_add] } },
exact this (i + 1) }
end
/-- Inductively define a function on `ℤ` by defining it at `b`, for the `succ` of a number greater
than `b`, and the `pred` of a number less than `b`. -/
protected def induction_on' {C : ℤ → Sort*} (z : ℤ) (b : ℤ) :
C b → (∀ k, b ≤ k → C k → C (k + 1)) → (∀ k ≤ b, C k → C (k - 1)) → C z :=
λ H0 Hs Hp,
begin
rw ←sub_add_cancel z b,
induction (z - b) with n n,
{ induction n with n ih, { rwa [of_nat_zero, zero_add] },
rw [of_nat_succ, add_assoc, add_comm 1 b, ←add_assoc],
exact Hs _ (le_add_of_nonneg_left (of_nat_nonneg _)) ih },
{ induction n with n ih,
{ rw [neg_succ_of_nat_eq, ←of_nat_eq_coe, of_nat_zero, zero_add, neg_add_eq_sub],
exact Hp _ (le_refl _) H0 },
{ rw [neg_succ_of_nat_coe', nat.succ_eq_add_one, ←neg_succ_of_nat_coe, sub_add_eq_add_sub],
exact Hp _ (le_of_lt (add_lt_of_neg_of_le (neg_succ_lt_zero _) (le_refl _))) ih } }
end
/-! ### nat abs -/
attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one
theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b :=
begin
have : ∀ (a b : ℕ), nat_abs (sub_nat_nat a (nat.succ b)) ≤ nat.succ (a + b),
{ refine (λ a b : ℕ, sub_nat_nat_elim a b.succ
(λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl);
intros i n e,
{ subst e, rw [add_comm _ i, add_assoc],
exact nat.le_add_right i (b.succ + b).succ },
{ apply succ_le_succ,
rw [← succ.inj e, ← add_assoc, add_comm],
apply nat.le_add_right } },
cases a; cases b with b b; simp [nat_abs, nat.succ_add];
try {refl}; [skip, rw add_comm a b]; apply this
end
theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n :=
by cases n; refl
theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) :=
by cases a; cases b;
simp only [← int.mul_def, int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs]
lemma nat_abs_mul_nat_abs_eq {a b : ℤ} {c : ℕ} (h : a * b = (c : ℤ)) :
a.nat_abs * b.nat_abs = c :=
by rw [← nat_abs_mul, h, nat_abs_of_nat]
@[simp] lemma nat_abs_mul_self' (a : ℤ) : (nat_abs a * nat_abs a : ℤ) = a * a :=
by rw [← int.coe_nat_mul, nat_abs_mul_self]
theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 :=
by simp [neg_succ_of_nat_eq, sub_eq_neg_add]
lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 :=
λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h
@[simp] lemma nat_abs_eq_zero {a : ℤ} : a.nat_abs = 0 ↔ a = 0 :=
⟨int.eq_zero_of_nat_abs_eq_zero, λ h, h.symm ▸ rfl⟩
lemma nat_abs_lt_nat_abs_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) :
a.nat_abs < b.nat_abs :=
begin
lift b to ℕ using le_trans w₁ (le_of_lt w₂),
lift a to ℕ using w₁,
simpa using w₂,
end
lemma nat_abs_eq_iff_mul_self_eq {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a * a = b * b :=
begin
rw [← abs_eq_iff_mul_self_eq, abs_eq_nat_abs, abs_eq_nat_abs],
exact int.coe_nat_inj'.symm
end
lemma nat_abs_lt_iff_mul_self_lt {a b : ℤ} : a.nat_abs < b.nat_abs ↔ a * a < b * b :=
begin
rw [← abs_lt_iff_mul_self_lt, abs_eq_nat_abs, abs_eq_nat_abs],
exact int.coe_nat_lt.symm
end
lemma nat_abs_le_iff_mul_self_le {a b : ℤ} : a.nat_abs ≤ b.nat_abs ↔ a * a ≤ b * b :=
begin
rw [← abs_le_iff_mul_self_le, abs_eq_nat_abs, abs_eq_nat_abs],
exact int.coe_nat_le.symm
end
lemma nat_abs_eq_iff_sq_eq {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a ^ 2 = b ^ 2 :=
by { rw [pow_two, pow_two], exact nat_abs_eq_iff_mul_self_eq }
lemma nat_abs_lt_iff_sq_lt {a b : ℤ} : a.nat_abs < b.nat_abs ↔ a ^ 2 < b ^ 2 :=
by { rw [pow_two, pow_two], exact nat_abs_lt_iff_mul_self_lt }
lemma nat_abs_le_iff_sq_le {a b : ℤ} : a.nat_abs ≤ b.nat_abs ↔ a ^ 2 ≤ b ^ 2 :=
by { rw [pow_two, pow_two], exact nat_abs_le_iff_mul_self_le }
/-! ### `/` -/
@[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl
@[simp, norm_cast] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl
theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : 0 < b) :
-[1+m] / b = -(m / b + 1) :=
match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end
@[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b)
| (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl
| (m : ℕ) (n+1:ℕ) := rfl
| 0 -[1+ n] := rfl
| (m+1:ℕ) -[1+ n] := (neg_neg _).symm
| -[1+ m] 0 := rfl
| -[1+ m] (n+1:ℕ) := rfl
| -[1+ m] -[1+ n] := rfl
theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) :=
match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ :=
by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl
end
protected theorem div_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a / b :=
match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _
end
protected theorem div_nonpos {a b : ℤ} (Ha : 0 ≤ a) (Hb : b ≤ 0) : a / b ≤ 0 :=
nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb)
theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 :=
match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _
end
-- Will be generalized to Euclidean domains.
protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0
| 0 := rfl
| (n+1:ℕ) := rfl
| -[1+ n] := rfl
local attribute [simp] -- Will be generalized to Euclidean domains.
protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0
| 0 := rfl
| (n+1:ℕ) := rfl
| -[1+ n] := rfl
@[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a
| 0 := rfl
| (n+1:ℕ) := congr_arg of_nat (nat.div_one _)
| -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _)
theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 :=
match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 :=
congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2
end
theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 :=
match b, abs b, abs_eq_nat_abs b, H2 with
| (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2
| -[1+ n], ._, rfl, H2 := neg_injective $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2
end
protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) :
(a + b * c) / c = a / c + b :=
have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from
λ k n a, match a with
| (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos
| -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ =
n - (m / k.succ + 1 : ℕ), begin
cases lt_or_ge m (n*k.succ) with h h,
{ rw [← int.coe_nat_sub h,
← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)],
apply congr_arg of_nat,
rw [mul_comm, nat.mul_sub_div], rwa mul_comm },
{ change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) =
↑n - ((m / nat.succ k : ℕ) + 1),
rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ),
← int.coe_nat_sub h,
← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h),
← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'],
{ apply congr_arg neg_succ_of_nat,
rw [mul_comm, nat.sub_mul_div], rwa mul_comm } }
end
end,
have ∀ {a b c : ℤ}, 0 < c → (a + b * c) / c = a / c + b, from
λ a b c H, match c, eq_succ_of_zero_lt H, b with
| ._, ⟨k, rfl⟩, (n : ℕ) := this
| ._, ⟨k, rfl⟩, -[1+ n] :=
show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from
eq_sub_of_add_eq $ by rw [← this, sub_add_cancel]
end,
match lt_trichotomy c 0 with
| or.inl hlt := neg_inj.1 $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg];
apply this (neg_pos_of_neg hlt)
| or.inr (or.inl heq) := absurd heq H
| or.inr (or.inr hgt) := this hgt
end
protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) :
(a + b * c) / b = a / b + c :=
by rw [mul_comm, int.add_mul_div_right _ _ H]
@[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a :=
by have := int.add_mul_div_right 0 a H;
rwa [zero_add, int.zero_div, zero_add] at this
@[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b :=
by rw [mul_comm, int.mul_div_cancel _ H]
@[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 :=
by have := int.mul_div_cancel 1 H; rwa one_mul at this
/-! ### mod -/
theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl
@[simp, norm_cast] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl
theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : 0 < b) :
-[1+m] % b = b - 1 - m % b :=
by rw [sub_sub, add_comm]; exact
match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end
@[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b
| (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _)
| -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _)
@[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b :=
abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _)
local attribute [simp] -- Will be generalized to Euclidean domains.
theorem zero_mod (b : ℤ) : 0 % b = 0 :=
congr_arg of_nat $ nat.zero_mod _
local attribute [simp] -- Will be generalized to Euclidean domains.
theorem mod_zero : ∀ (a : ℤ), a % 0 = a
| (m : ℕ) := congr_arg of_nat $ nat.mod_zero _
| -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _
local attribute [simp] -- Will be generalized to Euclidean domains.
theorem mod_one : ∀ (a : ℤ), a % 1 = 0
| (m : ℕ) := congr_arg of_nat $ nat.mod_one _
| -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl
theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a :=
match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 :=
congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2)
end
theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → 0 ≤ a % b
| (m : ℕ) n H := coe_zero_le _
| -[1+ m] n H :=
sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H)
theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : 0 < b) : a % b < b :=
match a, b, eq_succ_of_zero_lt H with
| (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _))
| -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _)
end
theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b :=
by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos.2 H)
theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] :=
begin
rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)],
apply eq_neg_of_eq_neg,
rw [neg_sub, sub_sub_self, add_right_comm],
exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm
end
theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a
| (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _)
| (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _)
| 0 -[1+ n] := rfl
| (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _,
by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _)
| -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl
| -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ
| -[1+ m] -[1+ n] := mod_add_div_aux m n.succ
theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) :=
eq_sub_of_add_eq (mod_add_div _ _)
@[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c :=
if cz : c = 0 then by rw [cz, mul_zero, add_zero] else
by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz,
mul_add, mul_comm, add_sub_add_right_eq_sub]
@[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b :=
by rw [mul_comm, add_mul_mod_self]
@[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b :=
by have := add_mul_mod_self_left a b 1; rwa mul_one at this
@[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a :=
by rw [add_comm, add_mod_self]
@[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n :=
by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm;
rwa [add_right_comm, mod_add_div] at this
@[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k :=
by rw [add_comm, mod_add_mod, add_comm]
lemma add_mod (a b n : ℤ) : (a + b) % n = ((a % n) + (b % n)) % n :=
by rw [add_mod_mod, mod_add_mod]
theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) :
(m + i) % n = (k + i) % n :=
by rw [← mod_add_mod, ← mod_add_mod k, H]
theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) :
(i + m) % n = (i + k) % n :=
by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm]
theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔
m % n = k % n :=
⟨λ H, by have := add_mod_eq_add_mod_right (-i) H;
rwa [add_neg_cancel_right, add_neg_cancel_right] at this,
add_mod_eq_add_mod_right _⟩
theorem mod_add_cancel_left {m n k i : ℤ} :
(i + m) % n = (i + k) % n ↔ m % n = k % n :=
by rw [add_comm, add_comm i, mod_add_cancel_right]
theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔
m % n = k % n :=
mod_add_cancel_right _
theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 :=
(mod_sub_cancel_right k).symm.trans $ by simp
@[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 :=
by rw [← zero_add (a * b), add_mul_mod_self, zero_mod]
@[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 :=
by rw [mul_comm, mul_mod_left]
lemma mul_mod (a b n : ℤ) : (a * b) % n = ((a % n) * (b % n)) % n :=
begin
conv_lhs {
rw [←mod_add_div a n, ←mod_add_div b n, right_distrib, left_distrib, left_distrib,
mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left,
mul_comm _ (n * (b / n)), mul_assoc, add_mul_mod_self_left] }
end
@[simp] lemma neg_mod_two (i : ℤ) : (-i) % 2 = i % 2 :=
begin
apply int.mod_eq_mod_iff_mod_sub_eq_zero.mpr,
convert int.mul_mod_right 2 (-i),
simp only [two_mul, sub_eq_add_neg]
end
local attribute [simp] -- Will be generalized to Euclidean domains.
theorem mod_self {a : ℤ} : a % a = 0 :=
by have := mul_mod_left 1 a; rwa one_mul at this
@[simp] theorem mod_mod_of_dvd (n : int) {m k : int} (h : m ∣ k) : n % k % m = n % m :=
begin
conv { to_rhs, rw ←mod_add_div n k },
rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left]
end
@[simp] theorem mod_mod (a b : ℤ) : a % b % b = a % b :=
by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]}
lemma sub_mod (a b n : ℤ) : (a - b) % n = ((a % n) - (b % n)) % n :=
begin
apply (mod_add_cancel_right b).mp,
rw [sub_add_cancel, ← add_mod_mod, sub_add_cancel, mod_mod]
end
/-! ### properties of `/` and `%` -/
@[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b / (a * c) = b / c :=
suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from
match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with
| ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _
| ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ :=
by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg];
apply congr_arg has_neg.neg; apply this
end,
λ m k b, match b, k with
| (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos)
| -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero]
| -[1+ n], k+1 := congr_arg neg_succ_of_nat $
show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin
apply nat.div_eq_of_lt_le,
{ refine le_trans _ (nat.le_add_right _ _),
rw [← nat.mul_div_mul _ _ m.succ_pos],
apply nat.div_mul_le_self },
{ change m.succ * n.succ ≤ _,
rw [mul_left_comm],
apply nat.mul_le_mul_left,
apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1,
apply nat.lt_succ_self }
end
end
@[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : 0 < b) :
a * b / (c * b) = a / c :=
by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H]
@[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b % (a * c) = a * (b % c) :=
by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc]
theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : 0 < b) : a < (a / b + 1) * b :=
by rw [add_mul, one_mul, mul_comm]; apply lt_add_of_sub_left_lt;
rw [← mod_def]; apply mod_lt_of_pos _ H
theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a :=
suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from
λ a b, match b, eq_coe_or_neg b with
| ._, ⟨n, or.inl rfl⟩ := this _ _
| ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this
end,
λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact
coe_nat_le_coe_nat_of_le (match a, n with
| (m : ℕ), n := nat.div_le_self _ _
| -[1+ m], 0 := nat.zero_le _
| -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _)
end)
theorem div_le_self {a : ℤ} (b : ℤ) (Ha : 0 ≤ a) : a / b ≤ a :=
by have := le_trans (le_abs_self _) (abs_div_le_abs a b);
rwa [abs_of_nonneg Ha] at this
theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a :=
by have := mod_add_div a b; rwa [H, zero_add] at this
theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a :=
by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H]
lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 :=
have h : n % 2 < 2 := abs_of_nonneg (show 0 ≤ (2 : ℤ), from dec_trivial) ▸ int.mod_lt _ dec_trivial,
have h₁ : 0 ≤ n % 2 := int.mod_nonneg _ dec_trivial,
match (n % 2), h, h₁ with
| (0 : ℕ) := λ _ _, or.inl rfl
| (1 : ℕ) := λ _ _, or.inr rfl
| (k + 2 : ℕ) := λ h _, absurd h dec_trivial
| -[1+ a] := λ _ h₁, absurd h₁ dec_trivial
end
/-! ### dvd -/
@[norm_cast] theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n :=
⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim
(λm0, by simp [m0] at ae; simp [ae, m0])
(λm0l, by {
cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a
(by simp [ae.symm]) (by simpa using m0l)) with k e,
subst a, exact ⟨k, int.coe_nat_inj ae⟩ }),
λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩
theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs :=
by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd]
theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n :=
by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd]
theorem dvd_antisymm {a b : ℤ} (H1 : 0 ≤ a) (H2 : 0 ≤ b) : a ∣ b → b ∣ a → a = b :=
begin
rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs],
rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'],
apply nat.dvd_antisymm
end
theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b :=
⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩
theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0
| a ._ ⟨c, rfl⟩ := mul_mod_right _ _
theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 :=
⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩
/-- If `a % b = c` then `b` divides `a - c`. -/
lemma dvd_sub_of_mod_eq {a b c : ℤ} (h : a % b = c) : b ∣ a - c :=
begin
have hx : a % b % b = c % b, { rw h },
rw [mod_mod, ←mod_sub_cancel_right c, sub_self, zero_mod] at hx,
exact dvd_of_mod_eq_zero hx
end
theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b :=
(nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e])
theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b :=
(nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e])
instance decidable_dvd : @decidable_rel ℤ (∣) :=
assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm
protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a :=
div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H)
protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b :=
by rw [mul_comm, int.div_mul_cancel H]
protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c)
| ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else
by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz]
theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a
| a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else
by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az];
apply dvd_mul_right
protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) :
a = b * c :=
by rw [← H2, int.mul_div_cancel' H1]
protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) :
a / b = c :=
by rw [H2, int.mul_div_cancel_left _ H1]
protected theorem eq_div_of_mul_eq_right {a b c : ℤ} (H1 : a ≠ 0) (H2 : a * b = c) :
b = c / a :=
eq.symm $ int.div_eq_of_eq_mul_right H1 H2.symm
protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) :
a / b = c ↔ a = b * c :=
⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩
protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) :
a / b = c ↔ a = c * b :=
by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H'
protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) :
a = c * b :=
by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2]
protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) :
a / b = c :=
int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2])
theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b)
| ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else
by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz]
lemma add_div_of_dvd {a b c : ℤ} :
c ∣ a → c ∣ b → (a + b) / c = a / c + b / c :=
begin
intros h1 h2,
by_cases h3 : c = 0,
{ rw [h3, zero_dvd_iff] at *,
rw [h1, h2, h3], refl },
{ apply mul_right_cancel' h3,
rw add_mul, repeat {rw [int.div_mul_cancel]};
try {apply dvd_add}; assumption }
end
theorem div_sign : ∀ a b, a / sign b = a * sign b
| a (n+1:ℕ) := by unfold sign; simp
| a 0 := by simp [sign]
| a -[1+ n] := by simp [sign]
@[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b
| a 0 := by simp
| 0 b := by simp
| (m+1:ℕ) (n+1:ℕ) := rfl
| (m+1:ℕ) -[1+ n] := rfl
| -[1+ m] (n+1:ℕ) := rfl
| -[1+ m] -[1+ n] := rfl
protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) :=
if az : a = 0 then by simp [az] else
(int.div_eq_of_eq_mul_left (mt abs_eq_zero.1 az)
(sign_mul_abs _).symm).symm
theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i
| (n+1:ℕ) := mul_one _
| 0 := mul_zero _
| -[1+ n] := mul_neg_one _
theorem le_of_dvd {a b : ℤ} (bpos : 0 < b) (H : a ∣ b) : a ≤ b :=
match a, b, eq_succ_of_zero_lt bpos, H with
| (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $
nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H
| -[1+ m], ._, ⟨n, rfl⟩, _ :=
le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _)
end
theorem eq_one_of_dvd_one {a : ℤ} (H : 0 ≤ a) (H' : a ∣ 1) : a = 1 :=
match a, eq_coe_of_zero_le H, H' with
| ._, ⟨n, rfl⟩, H' := congr_arg coe $
nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H'
end
theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : 0 ≤ a) (H' : a * b = 1) : a = 1 :=
eq_one_of_dvd_one H ⟨b, H'.symm⟩
theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : 0 ≤ b) (H' : a * b = 1) : b = 1 :=
eq_one_of_mul_eq_one_right H (by rw [mul_comm, H'])
lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z
| (int.of_nat _) haz := int.coe_nat_dvd.2 haz
| -[1+k] haz :=
begin
change ↑a ∣ -(k+1 : ℤ),
apply dvd_neg_of_dvd,
apply int.coe_nat_dvd.2,
exact haz
end
lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs
| (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz)
| -[1+k] haz :=
have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz,
int.coe_nat_dvd.1 haz'
lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) :
↑(p ^ m) ∣ k :=
begin
induction k,
{ apply int.coe_nat_dvd.2,
apply pow_dvd_of_le_of_pow_dvd hmn,
apply int.coe_nat_dvd.1 hdiv },
{ change -[1+k] with -(↑(k+1) : ℤ),
apply dvd_neg_of_dvd,
apply int.coe_nat_dvd.2,
apply pow_dvd_of_le_of_pow_dvd hmn,
apply int.coe_nat_dvd.1,
apply dvd_of_dvd_neg,
exact hdiv }
end
lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m :=
by rw ←pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk
/-- If `n > 0` then `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)`
for some `k`. -/
lemma exists_lt_and_lt_iff_not_dvd (m : ℤ) {n : ℤ} (hn : 0 < n) :
(∃ k, n * k < m ∧ m < n * (k + 1)) ↔ ¬ n ∣ m :=
begin
split,
{ rintro ⟨k, h1k, h2k⟩ ⟨l, rfl⟩, rw [mul_lt_mul_left hn] at h1k h2k,
rw [lt_add_one_iff, ← not_lt] at h2k, exact h2k h1k },
{ intro h, rw [dvd_iff_mod_eq_zero, ← ne.def] at h,
have := (mod_nonneg m hn.ne.symm).lt_of_ne h.symm,
simp only [← mod_add_div m n] {single_pass := tt},
refine ⟨m / n, lt_add_of_pos_left _ this, _⟩,
rw [add_comm _ (1 : ℤ), left_distrib, mul_one], exact add_lt_add_right (mod_lt_of_pos _ hn) _ }
end
/-! ### `/` and ordering -/
protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a :=
le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H
protected theorem div_le_of_le_mul {a b c : ℤ} (H : 0 < c) (H' : a ≤ b * c) : a / c ≤ b :=
le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H
protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : 0 < c) (H3 : a < b / c) : a * c < b :=
lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3)
protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : 0 < c) (H2 : a ≤ b / c) : a * c ≤ b :=
le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1))
protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : 0 < c) (H2 : a * c ≤ b) : a ≤ b / c :=
le_of_lt_add_one $ lt_of_mul_lt_mul_right
(lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1)
protected theorem le_div_iff_mul_le {a b c : ℤ} (H : 0 < c) : a ≤ b / c ↔ a * c ≤ b :=
⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩
protected theorem div_le_div {a b c : ℤ} (H : 0 < c) (H' : a ≤ b) : a / c ≤ b / c :=
int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H')
protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : 0 < c) (H' : a < b * c) : a / c < b :=
lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H')
protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : 0 < c) (H2 : a / c < b) : a < b * c :=
lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2)
protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : 0 < c) : a / c < b ↔ a < b * c :=
⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩
protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ a) (H3 : a / b ≤ c) :
a ≤ c * b :=
by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1
protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ c) (H3 : a * b < c) :
a < c / b :=
lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3)
protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : 0 < c) (H' : c ∣ b) :
a < b / c ↔ a * c < b :=
⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩
theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : 0 < a) (H2 : 0 ≤ b) (H3 : b ∣ a) : 0 < a / b :=
int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul)
theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H2 : d ∣ c) (H3 : b ≠ 0)
(H4 : d ≠ 0) (H5 : a * d = b * c) :
a / b = c / d :=
int.div_eq_of_eq_mul_right H3 $
by rw [← int.mul_div_assoc _ H2]; exact
(int.div_eq_of_eq_mul_left H4 H5.symm).symm
theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hbc : b ∣ c)
(h : b * a = c * d) : a = c / b * d :=
begin
cases hbc with k hk,
subst hk,
rw [int.mul_div_cancel_left _ hb],
rw mul_assoc at h,
apply mul_left_cancel' hb h
end
/-- If an integer with larger absolute value divides an integer, it is
zero. -/
lemma eq_zero_of_dvd_of_nat_abs_lt_nat_abs {a b : ℤ} (w : a ∣ b) (h : nat_abs b < nat_abs a) :
b = 0 :=
begin
rw [←nat_abs_dvd, ←dvd_nat_abs, coe_nat_dvd] at w,
rw ←nat_abs_eq_zero,
exact eq_zero_of_dvd_of_lt w h
end
lemma eq_zero_of_dvd_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) (h : b ∣ a) : a = 0 :=
eq_zero_of_dvd_of_nat_abs_lt_nat_abs h (nat_abs_lt_nat_abs_of_nonneg_of_lt w₁ w₂)
/-- If two integers are congruent to a sufficiently large modulus,
they are equal. -/
lemma eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs {a b c : ℤ} (h1 : a % b = c)
(h2 : nat_abs (a - c) < nat_abs b) :
a = c :=
eq_of_sub_eq_zero (eq_zero_of_dvd_of_nat_abs_lt_nat_abs (dvd_sub_of_mod_eq h1) h2)
theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ}
(h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] :=
begin
change sub_nat_nat _ _ = _,
have h' : n.succ - m = (n - m).succ,
apply succ_sub,
apply le_of_lt_succ h,
simp [*, sub_nat_nat]
end
theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ}
(h : n.succ ≤ m) : of_nat m + -[1+n] = of_nat (m - n.succ) :=
begin
change sub_nat_nat _ _ = _,
have h' : n.succ - m = 0,
apply sub_eq_zero_of_le h,
simp [*, sub_nat_nat]
end
@[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl
/-! ### to_nat -/
theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0
| (n : ℕ) := (max_eq_left (coe_zero_le n)).symm
| -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm
@[simp] lemma to_nat_zero : (0 : ℤ).to_nat = 0 := rfl
@[simp] lemma to_nat_one : (1 : ℤ).to_nat = 1 := rfl
@[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a :=
by rw [to_nat_eq_max, max_eq_left h]
@[simp] lemma to_nat_sub_of_le (a b : ℤ) (h : b ≤ a) : (to_nat (a + -b) : ℤ) = a + - b :=
int.to_nat_of_nonneg (sub_nonneg_of_le h)
@[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl
@[simp] lemma to_nat_coe_nat_add_one {n : ℕ} : ((n : ℤ) + 1).to_nat = n + 1 := rfl
theorem le_to_nat (a : ℤ) : a ≤ to_nat a :=
by rw [to_nat_eq_max]; apply le_max_left
@[simp] theorem to_nat_le {a : ℤ} {n : ℕ} : to_nat a ≤ n ↔ a ≤ n :=
by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff];
exact and_iff_left (coe_zero_le _)
@[simp] theorem lt_to_nat {n : ℕ} {a : ℤ} : n < to_nat a ↔ (n : ℤ) < a :=
le_iff_le_iff_lt_iff_lt.1 to_nat_le
theorem to_nat_le_to_nat {a b : ℤ} (h : a ≤ b) : to_nat a ≤ to_nat b :=
by rw to_nat_le; exact le_trans h (le_to_nat b)
theorem to_nat_lt_to_nat {a b : ℤ} (hb : 0 < b) : to_nat a < to_nat b ↔ a < b :=
⟨λ h, begin cases a, exact lt_to_nat.1 h, exact lt_trans (neg_succ_of_nat_lt_zero a) hb, end,
λ h, begin rw lt_to_nat, cases a, exact h, exact hb end⟩
theorem lt_of_to_nat_lt {a b : ℤ} (h : to_nat a < to_nat b) : a < b :=
(to_nat_lt_to_nat $ lt_to_nat.1 $ lt_of_le_of_lt (nat.zero_le _) h).1 h
lemma to_nat_add {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) :
(a + b).to_nat = a.to_nat + b.to_nat :=
begin
lift a to ℕ using ha,
lift b to ℕ using hb,
norm_cast,
end
lemma to_nat_add_one {a : ℤ} (h : 0 ≤ a) : (a + 1).to_nat = a.to_nat + 1 :=
to_nat_add h (zero_le_one)
/-- If `n : ℕ`, then `int.to_nat' n = some n`, if `n : ℤ` is negative, then `int.to_nat' n = none`.
-/
def to_nat' : ℤ → option ℕ
| (n : ℕ) := some n
| -[1+ n] := none
theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n
| (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm
| -[1+ m] n := by split; intro h; cases h
lemma to_nat_zero_of_neg : ∀ {z : ℤ}, z < 0 → z.to_nat = 0
| (-[1+n]) _ := rfl
| (int.of_nat n) h := (not_le_of_gt h $ int.of_nat_nonneg n).elim
/-! ### units -/
@[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 :=
units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹,
by rw [← nat_abs_mul, units.mul_inv]; refl,
by rw [← nat_abs_mul, units.inv_mul]; refl⟩
theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 :=
by simpa only [units.ext_iff, units_nat_abs] using nat_abs_eq u
lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u :=
(units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl)
@[simp] lemma units_mul_self (u : units ℤ) : u * u = 1 :=
(units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl)
-- `units.coe_mul` is a "wrong turn" for the simplifier, this undoes it and simplifies further
@[simp] lemma units_coe_mul_self (u : units ℤ) : (u * u : ℤ) = 1 :=
by rw [←units.coe_mul, units_mul_self, units.coe_one]
/-! ### bitwise ops -/
@[simp] lemma bodd_zero : bodd 0 = ff := rfl
@[simp] lemma bodd_one : bodd 1 = tt := rfl
lemma bodd_two : bodd 2 = ff := rfl
@[simp, norm_cast] lemma bodd_coe (n : ℕ) : int.bodd n = nat.bodd n := rfl
@[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd :=
by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros;
simp; cases i.bodd; simp
@[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd :=
by cases n; simp; refl
@[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n :=
by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe]
@[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) :=
by cases m with m m; cases n with n n; unfold has_add.add;
simp [int.add, -of_nat_eq_coe, bool.bxor_comm]
@[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n :=
by cases m with m m; cases n with n n;
simp [← int.mul_def, int.mul, -of_nat_eq_coe, bool.bxor_comm]
theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n
| (n : ℕ) :=
by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ),
by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2
| -[1+ n] := begin
refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2),
dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul],
{ change -[1+ 2 * nat.div2 n] = _, rw zero_add },
{ rw [zero_add, add_comm], refl }
end
theorem div2_val : ∀ n, div2 n = n / 2
| (n : ℕ) := congr_arg of_nat n.div2_val
| -[1+ n] := congr_arg neg_succ_of_nat n.div2_val
lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm
lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _)
lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 :=
by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val }
lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n :=
(bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _
/-- Defines a function from `ℤ` conditionally, if it is defined for odd and even integers separately
using `bit`. -/
def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n :=
by rw [← bit_decomp n]; apply h
@[simp] lemma bit_zero : bit ff 0 = 0 := rfl
@[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n :=
by rw [bit_val, nat.bit_val]; cases b; refl
@[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] :=
by rw [bit_val, nat.bit_val]; cases b; refl
@[simp] lemma bodd_bit (b n) : bodd (bit b n) = b :=
by rw bit_val; simp; cases b; cases bodd n; refl
@[simp] lemma bodd_bit0 (n : ℤ) : bodd (bit0 n) = ff := bodd_bit ff n
@[simp] lemma bodd_bit1 (n : ℤ) : bodd (bit1 n) = tt := bodd_bit tt n
@[simp] lemma div2_bit (b n) : div2 (bit b n) = n :=
begin
rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add],
cases b, all_goals {exact dec_trivial}
end
lemma bit0_ne_bit1 (m n : ℤ) : bit0 m ≠ bit1 n :=
mt (congr_arg bodd) $ by simp
lemma bit1_ne_bit0 (m n : ℤ) : bit1 m ≠ bit0 n :=
(bit0_ne_bit1 _ _).symm
lemma bit1_ne_zero (m : ℤ) : bit1 m ≠ 0 :=
by simpa only [bit0_zero] using bit1_ne_bit0 m 0
@[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b
| (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero
| -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero];
clear test_bit_zero; cases b; refl
@[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m
| (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ
| -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ]
private meta def bitwise_tac : tactic unit := `[
funext m,
funext n,
cases m with m m; cases n with n n; try {refl},
all_goals {
apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat,
try {dsimp [nat.land, nat.ldiff, nat.lor]},
try {rw [
show nat.bitwise (λ a b, a && bnot b) n m =
nat.bitwise (λ a b, b && bnot a) m n, from
congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]},
apply congr_arg (λ f, nat.bitwise f m n),
funext a,
funext b,
cases a; cases b; refl
},
all_goals {unfold nat.land nat.ldiff nat.lor}
]
theorem bitwise_or : bitwise bor = lor := by bitwise_tac
theorem bitwise_and : bitwise band = land := by bitwise_tac
theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac
theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac
@[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) :
bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) :=
begin
cases m with m m; cases n with n n;
repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ };
unfold bitwise nat_bitwise bnot;
[ induction h : f ff ff,
induction h : f ff tt,
induction h : f tt ff,
induction h : f tt tt ],
all_goals {
unfold cond, rw nat.bitwise_bit,
repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } },
all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl }
end
@[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) :=
by rw [← bitwise_or, bitwise_bit]
@[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) :=
by rw [← bitwise_and, bitwise_bit]
@[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) :=
by rw [← bitwise_diff, bitwise_bit]
@[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) :=
by rw [← bitwise_xor, bitwise_bit]
@[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n)
| (n : ℕ) := by simp [lnot]
| -[1+ n] := by simp [lnot]
@[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) :
test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) :=
begin
induction k with k IH generalizing m n;
apply bit_cases_on m; intros a m';
apply bit_cases_on n; intros b n';
rw bitwise_bit,
{ simp [test_bit_zero] },
{ simp [test_bit_succ, IH] }
end
@[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k :=
by rw [← bitwise_or, test_bit_bitwise]
@[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k :=
by rw [← bitwise_and, test_bit_bitwise]
@[simp]
lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) :=
by rw [← bitwise_diff, test_bit_bitwise]
@[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) :=
by rw [← bitwise_xor, test_bit_bitwise]
@[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k)
| (n : ℕ) k := by simp [lnot, test_bit]
| -[1+ n] k := by simp [lnot, test_bit]
lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k
| (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _)
| -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _)
| (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ
(λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k)
(λ i n, congr_arg coe $
by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right)
(λ i n, congr_arg coe $
by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl)
| -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ
(λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k])
(λ i n, congr_arg neg_succ_of_nat $
by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right)
(λ i n, congr_arg neg_succ_of_nat $
by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl)
lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k :=
shiftl_add _ _ _
@[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl
@[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg]
@[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl
@[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl
@[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl
@[simp]
lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl
lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k
| (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat,
← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add]
| -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ,
← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add]
lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n)
| (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _)
| -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _)
lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n)
| (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _)
| -[1+ m] n := begin
rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl,
exact coe_nat_lt_coe_nat_of_lt (pow_pos dec_trivial _)
end
lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) :=
congr_arg coe (nat.one_shiftl _)
@[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0
| (n : ℕ) := congr_arg coe (nat.zero_shiftl _)
| -[1+ n] := congr_arg coe (nat.zero_shiftr _)
@[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _
/-! ### Least upper bound property for integers -/
section classical
open_locale classical
theorem exists_least_of_bdd {P : ℤ → Prop}
(Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z)
(Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) :=
let ⟨b, Hb⟩ := Hbdd in
have EX : ∃ n : ℕ, P (b + n), from
let ⟨elt, Helt⟩ := Hinh in
match elt, le.dest (Hb _ Helt), Helt with
| ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩
end,
⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h,
match z, le.dest (Hb _ h), h with
| ._, ⟨n, rfl⟩, h := add_le_add_left
(int.coe_nat_le.2 $ nat.find_min' _ h) _
end⟩
theorem exists_greatest_of_bdd {P : ℤ → Prop}
(Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b)
(Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) :=
have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from
let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩,
have Hinh' : ∃ z : ℤ, P (-z), from
let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩,
let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in
⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩
end classical
end int
attribute [irreducible] int.nonneg
|
5c32c655ae66350e14aa6664b28e3c96737b66d3
|
57c233acf9386e610d99ed20ef139c5f97504ba3
|
/src/group_theory/sylow.lean
|
9f1ca8f9382e0a4cb459662ecbfd9c7888fdf9f2
|
[
"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
| 26,718
|
lean
|
/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Thomas Browning
-/
import data.set_like.fintype
import group_theory.group_action.conj_act
import group_theory.p_group
/-!
# Sylow theorems
The Sylow theorems are the following results for every finite group `G` and every prime number `p`.
* There exists a Sylow `p`-subgroup of `G`.
* All Sylow `p`-subgroups of `G` are conjugate to each other.
* Let `nₚ` be the number of Sylow `p`-subgroups of `G`, then `nₚ` divides the index of the Sylow
`p`-subgroup, `nₚ ≡ 1 [MOD p]`, and `nₚ` is equal to the index of the normalizer of the Sylow
`p`-subgroup in `G`.
## Main definitions
* `sylow p G` : The type of Sylow `p`-subgroups of `G`.
## Main statements
* `exists_subgroup_card_pow_prime`: A generalization of Sylow's first theorem:
For every prime power `pⁿ` dividing the cardinality of `G`,
there exists a subgroup of `G` of order `pⁿ`.
* `is_p_group.exists_le_sylow`: A generalization of Sylow's first theorem:
Every `p`-subgroup is contained in a Sylow `p`-subgroup.
* `sylow_conjugate`: A generalization of Sylow's second theorem:
If the number of Sylow `p`-subgroups is finite, then all Sylow `p`-subgroups are conjugate.
* `card_sylow_modeq_one`: A generalization of Sylow's third theorem:
If the number of Sylow `p`-subgroups is finite, then it is congruent to `1` modulo `p`.
-/
open fintype mul_action subgroup
section infinite_sylow
variables (p : ℕ) (G : Type*) [group G]
/-- A Sylow `p`-subgroup is a maximal `p`-subgroup. -/
structure sylow extends subgroup G :=
(is_p_group' : is_p_group p to_subgroup)
(is_maximal' : ∀ {Q : subgroup G}, is_p_group p Q → to_subgroup ≤ Q → Q = to_subgroup)
variables {p} {G}
namespace sylow
instance : has_coe (sylow p G) (subgroup G) := ⟨sylow.to_subgroup⟩
@[simp] lemma to_subgroup_eq_coe {P : sylow p G} : P.to_subgroup = ↑P := rfl
@[ext] lemma ext {P Q : sylow p G} (h : (P : subgroup G) = Q) : P = Q :=
by cases P; cases Q; congr'
lemma ext_iff {P Q : sylow p G} : P = Q ↔ (P : subgroup G) = Q :=
⟨congr_arg coe, ext⟩
instance : set_like (sylow p G) G :=
{ coe := coe,
coe_injective' := λ P Q h, ext (set_like.coe_injective h) }
end sylow
/-- A generalization of **Sylow's first theorem**.
Every `p`-subgroup is contained in a Sylow `p`-subgroup. -/
lemma is_p_group.exists_le_sylow {P : subgroup G} (hP : is_p_group p P) :
∃ Q : sylow p G, P ≤ Q :=
exists.elim (zorn.zorn_nonempty_partial_order₀ {Q : subgroup G | is_p_group p Q} (λ c hc1 hc2 Q hQ,
⟨ { carrier := ⋃ (R : c), R,
one_mem' := ⟨Q, ⟨⟨Q, hQ⟩, rfl⟩, Q.one_mem⟩,
inv_mem' := λ g ⟨_, ⟨R, rfl⟩, hg⟩, ⟨R, ⟨R, rfl⟩, R.1.inv_mem hg⟩,
mul_mem' := λ g h ⟨_, ⟨R, rfl⟩, hg⟩ ⟨_, ⟨S, rfl⟩, hh⟩, (hc2.total_of_refl R.2 S.2).elim
(λ T, ⟨S, ⟨S, rfl⟩, S.1.mul_mem (T hg) hh⟩) (λ T, ⟨R, ⟨R, rfl⟩, R.1.mul_mem hg (T hh)⟩) },
λ ⟨g, _, ⟨S, rfl⟩, hg⟩, by
{ refine exists_imp_exists (λ k hk, _) (hc1 S.2 ⟨g, hg⟩),
rwa [subtype.ext_iff, coe_pow] at hk ⊢ },
λ M hM g hg, ⟨M, ⟨⟨M, hM⟩, rfl⟩, hg⟩⟩) P hP) (λ Q ⟨hQ1, hQ2, hQ3⟩, ⟨⟨Q, hQ1, hQ3⟩, hQ2⟩)
instance sylow.nonempty : nonempty (sylow p G) :=
nonempty_of_exists is_p_group.of_bot.exists_le_sylow
noncomputable instance sylow.inhabited : inhabited (sylow p G) :=
classical.inhabited_of_nonempty sylow.nonempty
lemma sylow.exists_comap_eq_of_ker_is_p_group {H : Type*} [group H] (P : sylow p H)
{f : H →* G} (hf : is_p_group p f.ker) : ∃ Q : sylow p G, Q.1.comap f = P :=
exists_imp_exists (λ Q hQ, P.3 (Q.2.comap_of_ker_is_p_group f hf) (map_le_iff_le_comap.mp hQ))
(P.2.map f).exists_le_sylow
lemma sylow.exists_comap_eq_of_injective {H : Type*} [group H] (P : sylow p H)
{f : H →* G} (hf : function.injective f) : ∃ Q : sylow p G, Q.1.comap f = P :=
P.exists_comap_eq_of_ker_is_p_group (is_p_group.ker_is_p_group_of_injective hf)
lemma sylow.exists_comap_subtype_eq {H : subgroup G} (P : sylow p H) :
∃ Q : sylow p G, Q.1.comap H.subtype = P :=
P.exists_comap_eq_of_injective subtype.coe_injective
/-- If the kernel of `f : H →* G` is a `p`-group,
then `fintype (sylow p G)` implies `fintype (sylow p H)`. -/
noncomputable def sylow.fintype_of_ker_is_p_group {H : Type*} [group H]
{f : H →* G} (hf : is_p_group p f.ker) [fintype (sylow p G)] : fintype (sylow p H) :=
let h_exists := λ P : sylow p H, P.exists_comap_eq_of_ker_is_p_group hf,
g : sylow p H → sylow p G := λ P, classical.some (h_exists P),
hg : ∀ P : sylow p H, (g P).1.comap f = P := λ P, classical.some_spec (h_exists P) in
fintype.of_injective g (λ P Q h, sylow.ext (by simp only [←hg, h]))
/-- If `f : H →* G` is injective, then `fintype (sylow p G)` implies `fintype (sylow p H)`. -/
noncomputable def sylow.fintype_of_injective {H : Type*} [group H]
{f : H →* G} (hf : function.injective f) [fintype (sylow p G)] : fintype (sylow p H) :=
sylow.fintype_of_ker_is_p_group (is_p_group.ker_is_p_group_of_injective hf)
/-- If `H` is a subgroup of `G`, then `fintype (sylow p G)` implies `fintype (sylow p H)`. -/
noncomputable instance (H : subgroup G) [fintype (sylow p G)] : fintype (sylow p H) :=
sylow.fintype_of_injective (show function.injective H.subtype, from subtype.coe_injective)
open_locale pointwise
/-- `subgroup.pointwise_mul_action` preserves Sylow subgroups. -/
instance sylow.pointwise_mul_action {α : Type*} [group α] [mul_distrib_mul_action α G] :
mul_action α (sylow p G) :=
{ smul := λ g P, ⟨g • P, P.2.map _, λ Q hQ hS, inv_smul_eq_iff.mp (P.3 (hQ.map _)
(λ s hs, (congr_arg (∈ g⁻¹ • Q) (inv_smul_smul g s)).mp
(smul_mem_pointwise_smul (g • s) g⁻¹ Q (hS (smul_mem_pointwise_smul s g P hs)))))⟩,
one_smul := λ P, sylow.ext (one_smul α P),
mul_smul := λ g h P, sylow.ext (mul_smul g h P) }
lemma sylow.pointwise_smul_def {α : Type*} [group α] [mul_distrib_mul_action α G]
{g : α} {P : sylow p G} : ↑(g • P) = g • (P : subgroup G) := rfl
instance sylow.mul_action : mul_action G (sylow p G) :=
comp_hom _ mul_aut.conj
lemma sylow.smul_def {g : G} {P : sylow p G} : g • P = mul_aut.conj g • P := rfl
lemma sylow.coe_subgroup_smul {g : G} {P : sylow p G} :
↑(g • P) = mul_aut.conj g • (P : subgroup G) := rfl
lemma sylow.coe_smul {g : G} {P : sylow p G} :
↑(g • P) = mul_aut.conj g • (P : set G) := rfl
lemma sylow.smul_eq_iff_mem_normalizer {g : G} {P : sylow p G} :
g • P = P ↔ g ∈ (P : subgroup G).normalizer :=
begin
rw [eq_comm, set_like.ext_iff, ←inv_mem_iff, mem_normalizer_iff, inv_inv],
exact forall_congr (λ h, iff_congr iff.rfl ⟨λ ⟨a, b, c⟩, (congr_arg _ c).mp
((congr_arg (∈ P.1) (mul_aut.inv_apply_self G (mul_aut.conj g) a)).mpr b),
λ hh, ⟨(mul_aut.conj g)⁻¹ h, hh, mul_aut.apply_inv_self G (mul_aut.conj g) h⟩⟩),
end
lemma sylow.smul_eq_of_normal {g : G} {P : sylow p G} [h : (P : subgroup G).normal] :
g • P = P :=
by simp only [sylow.smul_eq_iff_mem_normalizer, normalizer_eq_top.mpr h, mem_top]
lemma subgroup.sylow_mem_fixed_points_iff (H : subgroup G) {P : sylow p G} :
P ∈ fixed_points H (sylow p G) ↔ H ≤ (P : subgroup G).normalizer :=
by simp_rw [set_like.le_def, ←sylow.smul_eq_iff_mem_normalizer]; exact subtype.forall
lemma is_p_group.inf_normalizer_sylow {P : subgroup G} (hP : is_p_group p P) (Q : sylow p G) :
P ⊓ (Q : subgroup G).normalizer = P ⊓ Q :=
le_antisymm (le_inf inf_le_left (sup_eq_right.mp (Q.3 (hP.to_inf_left.to_sup_of_normal_right'
Q.2 inf_le_right) le_sup_right))) (inf_le_inf_left P le_normalizer)
lemma is_p_group.sylow_mem_fixed_points_iff
{P : subgroup G} (hP : is_p_group p P) {Q : sylow p G} :
Q ∈ fixed_points P (sylow p G) ↔ P ≤ Q :=
by rw [P.sylow_mem_fixed_points_iff, ←inf_eq_left, hP.inf_normalizer_sylow, inf_eq_left]
/-- A generalization of **Sylow's second theorem**.
If the number of Sylow `p`-subgroups is finite, then all Sylow `p`-subgroups are conjugate. -/
instance [hp : fact p.prime] [fintype (sylow p G)] : is_pretransitive G (sylow p G) :=
⟨λ P Q, by
{ classical,
have H := λ {R : sylow p G} {S : orbit G P},
calc S ∈ fixed_points R (orbit G P)
↔ S.1 ∈ fixed_points R (sylow p G) : forall_congr (λ a, subtype.ext_iff)
... ↔ R.1 ≤ S : R.2.sylow_mem_fixed_points_iff
... ↔ S.1.1 = R : ⟨λ h, R.3 S.1.2 h, ge_of_eq⟩,
suffices : set.nonempty (fixed_points Q (orbit G P)),
{ exact exists.elim this (λ R hR, (congr_arg _ (sylow.ext (H.mp hR))).mp R.2) },
apply Q.2.nonempty_fixed_point_of_prime_not_dvd_card,
refine λ h, hp.out.not_dvd_one (nat.modeq_zero_iff_dvd.mp _),
calc 1 = card (fixed_points P (orbit G P)) : _
... ≡ card (orbit G P) [MOD p] : (P.2.card_modeq_card_fixed_points (orbit G P)).symm
... ≡ 0 [MOD p] : nat.modeq_zero_iff_dvd.mpr h,
rw ← set.card_singleton (⟨P, mem_orbit_self P⟩ : orbit G P),
refine card_congr' (congr_arg _ (eq.symm _)),
rw set.eq_singleton_iff_unique_mem,
exact ⟨H.mpr rfl, λ R h, subtype.ext (sylow.ext (H.mp h))⟩ }⟩
variables (p) (G)
/-- A generalization of **Sylow's third theorem**.
If the number of Sylow `p`-subgroups is finite, then it is congruent to `1` modulo `p`. -/
lemma card_sylow_modeq_one [fact p.prime] [fintype (sylow p G)] : card (sylow p G) ≡ 1 [MOD p] :=
begin
refine sylow.nonempty.elim (λ P : sylow p G, _),
have : fixed_points P.1 (sylow p G) = {P} :=
set.ext (λ Q : sylow p G, calc Q ∈ fixed_points P (sylow p G)
↔ P.1 ≤ Q : P.2.sylow_mem_fixed_points_iff
... ↔ Q.1 = P.1 : ⟨P.3 Q.2, ge_of_eq⟩
... ↔ Q ∈ {P} : sylow.ext_iff.symm.trans set.mem_singleton_iff.symm),
haveI : fintype (fixed_points P.1 (sylow p G)), { rw this, apply_instance },
have : card (fixed_points P.1 (sylow p G)) = 1, { simp [this] },
exact (P.2.card_modeq_card_fixed_points (sylow p G)).trans (by rw this),
end
variables {p} {G}
/-- Sylow subgroups are isomorphic -/
def sylow.equiv_smul (P : sylow p G) (g : G) : P ≃* (g • P : sylow p G) :=
equiv_smul (mul_aut.conj g) P.1
/-- Sylow subgroups are isomorphic -/
noncomputable def sylow.equiv [fact p.prime] [fintype (sylow p G)] (P Q : sylow p G) :
P ≃* Q :=
begin
rw ← classical.some_spec (exists_smul_eq G P Q),
exact P.equiv_smul (classical.some (exists_smul_eq G P Q)),
end
@[simp] lemma sylow.orbit_eq_top [fact p.prime] [fintype (sylow p G)] (P : sylow p G) :
orbit G P = ⊤ :=
top_le_iff.mp (λ Q hQ, exists_smul_eq G P Q)
lemma sylow.stabilizer_eq_normalizer (P : sylow p G) : stabilizer G P = P.1.normalizer :=
ext (λ g, sylow.smul_eq_iff_mem_normalizer)
/-- Sylow `p`-subgroups are in bijection with cosets of the normalizer of a Sylow `p`-subgroup -/
noncomputable def sylow.equiv_quotient_normalizer [fact p.prime] [fintype (sylow p G)]
(P : sylow p G) : sylow p G ≃ G ⧸ P.1.normalizer :=
calc sylow p G ≃ (⊤ : set (sylow p G)) : (equiv.set.univ (sylow p G)).symm
... ≃ orbit G P : by rw P.orbit_eq_top
... ≃ G ⧸ (stabilizer G P) : orbit_equiv_quotient_stabilizer G P
... ≃ G ⧸ P.1.normalizer : by rw P.stabilizer_eq_normalizer
noncomputable instance [fact p.prime] [fintype (sylow p G)] (P : sylow p G) :
fintype (G ⧸ P.1.normalizer) :=
of_equiv (sylow p G) P.equiv_quotient_normalizer
lemma card_sylow_eq_card_quotient_normalizer [fact p.prime] [fintype (sylow p G)] (P : sylow p G) :
card (sylow p G) = card (G ⧸ P.1.normalizer) :=
card_congr P.equiv_quotient_normalizer
lemma card_sylow_eq_index_normalizer [fact p.prime] [fintype (sylow p G)] (P : sylow p G) :
card (sylow p G) = P.1.normalizer.index :=
(card_sylow_eq_card_quotient_normalizer P).trans P.1.normalizer.index_eq_card.symm
lemma card_sylow_dvd_index [fact p.prime] [fintype (sylow p G)] (P : sylow p G) :
card (sylow p G) ∣ P.1.index :=
((congr_arg _ (card_sylow_eq_index_normalizer P)).mp dvd_rfl).trans (index_dvd_of_le le_normalizer)
/-- Frattini's Argument: If `N` is a normal subgroup of `G`, and if `P` is a Sylow `p`-subgroup
of `N`, then `N_G(P) ⊔ N = G`. -/
lemma sylow.normalizer_sup_eq_top {p : ℕ} [fact p.prime] {N : subgroup G} [N.normal]
[fintype (sylow p N)] (P : sylow p N) : ((↑P : subgroup N).map N.subtype).normalizer ⊔ N = ⊤ :=
begin
refine top_le_iff.mp (λ g hg, _),
obtain ⟨n, hn⟩ := exists_smul_eq N ((mul_aut.conj_normal g : mul_aut N) • P) P,
rw [←inv_mul_cancel_left ↑n g, sup_comm],
apply mul_mem_sup (N.inv_mem n.2),
rw [sylow.smul_def, ←mul_smul, ←mul_aut.conj_normal_coe, ←mul_aut.conj_normal.map_mul,
sylow.ext_iff, sylow.pointwise_smul_def, pointwise_smul_def] at hn,
refine λ x, (mem_map_iff_mem (show function.injective (mul_aut.conj (↑n * g)).to_monoid_hom,
from (mul_aut.conj (↑n * g)).injective)).symm.trans _,
rw [map_map, ←(congr_arg (map N.subtype) hn), map_map],
refl,
end
end infinite_sylow
open equiv equiv.perm finset function list quotient_group
open_locale big_operators
universes u v w
variables {G : Type u} {α : Type v} {β : Type w} [group G]
local attribute [instance, priority 10] subtype.fintype set_fintype classical.prop_decidable
lemma quotient_group.card_preimage_mk [fintype G] (s : subgroup G)
(t : set (G ⧸ s)) : fintype.card (quotient_group.mk ⁻¹' t) =
fintype.card s * fintype.card t :=
by rw [← fintype.card_prod, fintype.card_congr
(preimage_mk_equiv_subgroup_times_set _ _)]
namespace sylow
open subgroup submonoid mul_action
lemma mem_fixed_points_mul_left_cosets_iff_mem_normalizer {H : subgroup G}
[fintype ((H : set G) : Type u)] {x : G} :
(x : G ⧸ H) ∈ fixed_points H (G ⧸ H) ↔ x ∈ normalizer H :=
⟨λ hx, have ha : ∀ {y : G ⧸ H}, y ∈ orbit H (x : G ⧸ H) → y = x,
from λ _, ((mem_fixed_points' _).1 hx _),
(inv_mem_iff _).1 (@mem_normalizer_fintype _ _ _ _inst_2 _ (λ n (hn : n ∈ H),
have (n⁻¹ * x)⁻¹ * x ∈ H := quotient_group.eq.1 (ha (mem_orbit _ ⟨n⁻¹, H.inv_mem hn⟩)),
show _ ∈ H, by {rw [mul_inv_rev, inv_inv] at this, convert this, rw inv_inv}
)),
λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H),
(mem_fixed_points' _).2 $ λ y, quotient.induction_on' y $ λ y hy, quotient_group.eq.2
(let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in
have hb₂ : (b * x)⁻¹ * y ∈ H := quotient_group.eq.1 hb₂,
(inv_mem_iff H).1 $ (hx _).2 $ (mul_mem_cancel_left H (H.inv_mem hb₁)).1
$ by rw hx at hb₂;
simpa [mul_inv_rev, mul_assoc] using hb₂)⟩
def fixed_points_mul_left_cosets_equiv_quotient (H : subgroup G) [fintype (H : set G)] :
mul_action.fixed_points H (G ⧸ H) ≃
normalizer H ⧸ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) :=
@subtype_quotient_equiv_quotient_subtype G (normalizer H : set G) (id _) (id _) (fixed_points _ _)
(λ a, (@mem_fixed_points_mul_left_cosets_iff_mem_normalizer _ _ _ _inst_2 _).symm)
(by intros; refl)
/-- If `H` is a `p`-subgroup of `G`, then the index of `H` inside its normalizer is congruent
mod `p` to the index of `H`. -/
lemma card_quotient_normalizer_modeq_card_quotient [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime]
{H : subgroup G} (hH : fintype.card H = p ^ n) :
card (normalizer H ⧸ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H))
≡ card (G ⧸ H) [MOD p] :=
begin
rw [← fintype.card_congr (fixed_points_mul_left_cosets_equiv_quotient H)],
exact ((is_p_group.of_card hH).card_modeq_card_fixed_points _).symm
end
/-- If `H` is a subgroup of `G` of cardinality `p ^ n`, then the cardinality of the
normalizer of `H` is congruent mod `p ^ (n + 1)` to the cardinality of `G`. -/
lemma card_normalizer_modeq_card [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime]
{H : subgroup G} (hH : fintype.card H = p ^ n) :
card (normalizer H) ≡ card G [MOD p ^ (n + 1)] :=
have subgroup.comap ((normalizer H).subtype : normalizer H →* G) H ≃ H,
from set.bij_on.equiv (normalizer H).subtype
⟨λ _, id, λ _ _ _ _ h, subtype.val_injective h,
λ x hx, ⟨⟨x, le_normalizer hx⟩, hx, rfl⟩⟩,
begin
rw [card_eq_card_quotient_mul_card_subgroup H,
card_eq_card_quotient_mul_card_subgroup
(subgroup.comap ((normalizer H).subtype : normalizer H →* G) H),
fintype.card_congr this, hH, pow_succ],
exact (card_quotient_normalizer_modeq_card_quotient hH).mul_right' _
end
/-- If `H` is a `p`-subgroup but not a Sylow `p`-subgroup, then `p` divides the
index of `H` inside its normalizer. -/
lemma prime_dvd_card_quotient_normalizer [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime]
(hdvd : p ^ (n + 1) ∣ card G) {H : subgroup G} (hH : fintype.card H = p ^ n) :
p ∣ card (normalizer H ⧸ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) :=
let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in
have hcard : card (G ⧸ H) = s * p :=
(nat.mul_left_inj (show card H > 0, from fintype.card_pos_iff.2
⟨⟨1, H.one_mem⟩⟩)).1
(by rwa [← card_eq_card_quotient_mul_card_subgroup H, hH, hs,
pow_succ', mul_assoc, mul_comm p]),
have hm : s * p % p =
card (normalizer H ⧸ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) % p :=
hcard ▸ (card_quotient_normalizer_modeq_card_quotient hH).symm,
nat.dvd_of_mod_eq_zero
(by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm)
/-- If `H` is a `p`-subgroup but not a Sylow `p`-subgroup of cardinality `p ^ n`,
then `p ^ (n + 1)` divides the cardinality of the normalizer of `H`. -/
lemma prime_pow_dvd_card_normalizer [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime]
(hdvd : p ^ (n + 1) ∣ card G) {H : subgroup G} (hH : fintype.card H = p ^ n) :
p ^ (n + 1) ∣ card (normalizer H) :=
nat.modeq_zero_iff_dvd.1 ((card_normalizer_modeq_card hH).trans
hdvd.modeq_zero_nat)
/-- If `H` is a subgroup of `G` of cardinality `p ^ n`,
then `H` is contained in a subgroup of cardinality `p ^ (n + 1)`
if `p ^ (n + 1)` divides the cardinality of `G` -/
theorem exists_subgroup_card_pow_succ [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime]
(hdvd : p ^ (n + 1) ∣ card G) {H : subgroup G} (hH : fintype.card H = p ^ n) :
∃ K : subgroup G, fintype.card K = p ^ (n + 1) ∧ H ≤ K :=
let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in
have hcard : card (G ⧸ H) = s * p :=
(nat.mul_left_inj (show card H > 0, from fintype.card_pos_iff.2
⟨⟨1, H.one_mem⟩⟩)).1
(by rwa [← card_eq_card_quotient_mul_card_subgroup H, hH, hs,
pow_succ', mul_assoc, mul_comm p]),
have hm : s * p % p =
card (normalizer H ⧸ (subgroup.comap (normalizer H).subtype H)) % p :=
card_congr (fixed_points_mul_left_cosets_equiv_quotient H) ▸ hcard ▸
(is_p_group.of_card hH).card_modeq_card_fixed_points _,
have hm' : p ∣ card (normalizer H ⧸ (subgroup.comap (normalizer H).subtype H)) :=
nat.dvd_of_mod_eq_zero
(by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm),
let ⟨x, hx⟩ := @exists_prime_order_of_dvd_card _ (quotient_group.quotient.group _) _ _ hp hm' in
have hequiv : H ≃ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) :=
⟨λ a, ⟨⟨a.1, le_normalizer a.2⟩, a.2⟩, λ a, ⟨a.1.1, a.2⟩,
λ ⟨_, _⟩, rfl, λ ⟨⟨_, _⟩, _⟩, rfl⟩,
⟨subgroup.map ((normalizer H).subtype) (subgroup.comap
(quotient_group.mk' (comap H.normalizer.subtype H)) (zpowers x)),
begin
show card ↥(map H.normalizer.subtype
(comap (mk' (comap H.normalizer.subtype H)) (subgroup.zpowers x))) = p ^ (n + 1),
suffices : card ↥(subtype.val '' ((subgroup.comap (mk' (comap H.normalizer.subtype H))
(zpowers x)) : set (↥(H.normalizer)))) = p^(n+1),
{ convert this using 2 },
rw [set.card_image_of_injective
(subgroup.comap (mk' (comap H.normalizer.subtype H)) (zpowers x) : set (H.normalizer))
subtype.val_injective,
pow_succ', ← hH, fintype.card_congr hequiv, ← hx, order_eq_card_zpowers,
← fintype.card_prod],
exact @fintype.card_congr _ _ (id _) (id _) (preimage_mk_equiv_subgroup_times_set _ _)
end,
begin
assume y hy,
simp only [exists_prop, subgroup.coe_subtype, mk'_apply, subgroup.mem_map, subgroup.mem_comap],
refine ⟨⟨y, le_normalizer hy⟩, ⟨0, _⟩, rfl⟩,
rw [zpow_zero, eq_comm, quotient_group.eq_one_iff],
simpa using hy
end⟩
/-- If `H` is a subgroup of `G` of cardinality `p ^ n`,
then `H` is contained in a subgroup of cardinality `p ^ m`
if `n ≤ m` and `p ^ m` divides the cardinality of `G` -/
theorem exists_subgroup_card_pow_prime_le [fintype G] (p : ℕ) : ∀ {n m : ℕ} [hp : fact p.prime]
(hdvd : p ^ m ∣ card G) (H : subgroup G) (hH : card H = p ^ n) (hnm : n ≤ m),
∃ K : subgroup G, card K = p ^ m ∧ H ≤ K
| n m := λ hp hdvd H hH hnm,
(lt_or_eq_of_le hnm).elim
(λ hnm : n < m,
have h0m : 0 < m, from (lt_of_le_of_lt n.zero_le hnm),
have wf : m - 1 < m, from nat.sub_lt h0m zero_lt_one,
have hnm1 : n ≤ m - 1, from le_tsub_of_add_le_right hnm,
let ⟨K, hK⟩ := @exists_subgroup_card_pow_prime_le n (m - 1) hp
(nat.pow_dvd_of_le_of_pow_dvd tsub_le_self hdvd) H hH hnm1 in
have hdvd' : p ^ ((m - 1) + 1) ∣ card G, by rwa [tsub_add_cancel_of_le h0m.nat_succ_le],
let ⟨K', hK'⟩ := @exists_subgroup_card_pow_succ _ _ _ _ _ hp hdvd' K hK.1 in
⟨K', by rw [hK'.1, tsub_add_cancel_of_le h0m.nat_succ_le], le_trans hK.2 hK'.2⟩)
(λ hnm : n = m, ⟨H, by simp [hH, hnm]⟩)
/-- A generalisation of **Sylow's first theorem**. If `p ^ n` divides
the cardinality of `G`, then there is a subgroup of cardinality `p ^ n` -/
theorem exists_subgroup_card_pow_prime [fintype G] (p : ℕ) {n : ℕ} [fact p.prime]
(hdvd : p ^ n ∣ card G) : ∃ K : subgroup G, fintype.card K = p ^ n :=
let ⟨K, hK⟩ := exists_subgroup_card_pow_prime_le p hdvd ⊥ (by simp) n.zero_le in
⟨K, hK.1⟩
lemma pow_dvd_card_of_pow_dvd_card [fintype G] {p n : ℕ} [fact p.prime] (P : sylow p G)
(hdvd : p ^ n ∣ card G) : p ^ n ∣ card P :=
begin
obtain ⟨Q, hQ⟩ := exists_subgroup_card_pow_prime p hdvd,
obtain ⟨R, hR⟩ := (is_p_group.of_card hQ).exists_le_sylow,
obtain ⟨g, rfl⟩ := exists_smul_eq G R P,
calc p ^ n = card Q : hQ.symm
... ∣ card R : card_dvd_of_le hR
... = card (g • R) : card_congr (R.equiv_smul g).to_equiv
end
lemma dvd_card_of_dvd_card [fintype G] {p : ℕ} [fact p.prime] (P : sylow p G)
(hdvd : p ∣ card G) : p ∣ card P :=
begin
rw ← pow_one p at hdvd,
have key := P.pow_dvd_card_of_pow_dvd_card hdvd,
rwa pow_one at key,
end
lemma ne_bot_of_dvd_card [fintype G] {p : ℕ} [hp : fact p.prime] (P : sylow p G)
(hdvd : p ∣ card G) : (P : subgroup G) ≠ ⊥ :=
begin
refine λ h, hp.out.not_dvd_one _,
have key : p ∣ card (P : subgroup G) := P.dvd_card_of_dvd_card hdvd,
rwa [h, card_bot] at key,
end
lemma subsingleton_of_normal {p : ℕ} [fact p.prime] [fintype (sylow p G)] (P : sylow p G)
(h : (P : subgroup G).normal) : subsingleton (sylow p G) :=
begin
apply subsingleton.intro,
intros Q R,
obtain ⟨x, h1⟩ := exists_smul_eq G P Q,
obtain ⟨x, h2⟩ := exists_smul_eq G P R,
rw sylow.smul_eq_of_normal at h1 h2,
rw [← h1, ← h2],
end
section pointwise
open_locale pointwise
lemma characteristic_of_normal {p : ℕ} [fact p.prime] [fintype (sylow p G)] (P : sylow p G)
(h : (P : subgroup G).normal) :
(P : subgroup G).characteristic :=
begin
haveI := sylow.subsingleton_of_normal P h,
rw characteristic_iff_map_eq,
intros Φ,
show (Φ • P).to_subgroup = P.to_subgroup,
congr,
end
end pointwise
/-- The preimage of a Sylow subgroup under a homomorphism with p-group-kernel is a Sylow subgroup -/
def comap_of_ker_is_p_group {p : ℕ} (P : sylow p G)
{K : Type*} [group K] (ϕ : K →* G) (hϕ : is_p_group p ϕ.ker) (h : P.1 ≤ ϕ.range) :
sylow p K :=
{ P.1.comap ϕ with
is_p_group' := P.2.comap_of_ker_is_p_group ϕ hϕ,
is_maximal' := λ Q hQ hle, by
{ rw ← P.3 (hQ.map ϕ) (le_trans (ge_of_eq (map_comap_eq_self h)) (map_mono hle)),
exact (comap_map_eq_self ((P.1.ker_le_comap ϕ).trans hle)).symm }, }
@[simp]
lemma coe_comap_of_ker_is_p_group {p : ℕ} {P : sylow p G}
{K : Type*} [group K] (ϕ : K →* G) (hϕ : is_p_group p ϕ.ker) (h : P.1 ≤ ϕ.range) :
↑(P.comap_of_ker_is_p_group ϕ hϕ h) = subgroup.comap ϕ ↑P := rfl
/-- The preimage of a Sylow subgroup under an injective homomorphism is a Sylow subgroup -/
def comap_of_injective {p : ℕ} (P : sylow p G)
{K : Type*} [group K] (ϕ : K →* G) (hϕ : function.injective ϕ) (h : P.1 ≤ ϕ.range) :
sylow p K :=
P.comap_of_ker_is_p_group ϕ (is_p_group.ker_is_p_group_of_injective hϕ) h
@[simp]
lemma coe_comap_of_injective {p : ℕ} {P : sylow p G}
{K : Type*} [group K] (ϕ : K →* G) (hϕ : function.injective ϕ) (h : P.1 ≤ ϕ.range) :
↑(P.comap_of_injective ϕ hϕ h) = subgroup.comap ϕ ↑P := rfl
/-- A sylow subgroup in G is also a sylow subgroup in a subgroup of G. -/
def subtype {p : ℕ} (P : sylow p G) (N : subgroup G) (h : ↑P ≤ N) : sylow p N :=
P.comap_of_injective N.subtype subtype.coe_injective (by simp [h])
@[simp]
lemma coe_subtype {p : ℕ} {P : sylow p G} {N : subgroup G} {h : P.1 ≤ N} :
↑(P.subtype N h) = subgroup.comap N.subtype ↑P := rfl
lemma normal_of_normalizer_normal {p : ℕ} [fact p.prime] [fintype (sylow p G)]
(P : sylow p G) (hn : (↑P : subgroup G).normalizer.normal) :
(↑P : subgroup G).normal :=
by rw [←normalizer_eq_top, ←normalizer_sup_eq_top (P.subtype _ le_normalizer), coe_subtype,
map_comap_eq_self (le_normalizer.trans (ge_of_eq (subtype_range _))), sup_idem]
@[simp] lemma normalizer_normalizer {p : ℕ} [fact p.prime] [fintype (sylow p G)]
(P : sylow p G) :
(↑P : subgroup G).normalizer.normalizer = (↑P : subgroup G).normalizer :=
begin
have := normal_of_normalizer_normal (P.subtype _ (le_normalizer.trans le_normalizer)),
simp_rw [←normalizer_eq_top, coe_subtype, ←comap_subtype_normalizer_eq le_normalizer,
←comap_subtype_normalizer_eq le_rfl, comap_subtype_self_eq_top] at this,
rw [←subtype_range (P : subgroup G).normalizer.normalizer, monoid_hom.range_eq_map, ←this rfl],
exact map_comap_eq_self (le_normalizer.trans (ge_of_eq (subtype_range _))),
end
lemma normal_of_normalizer_condition (hnc : normalizer_condition G)
{p : ℕ} [fact p.prime] [fintype (sylow p G)] (P : sylow p G) :
(↑P : subgroup G).normal :=
normalizer_eq_top.mp $ normalizer_condition_iff_only_full_group_self_normalizing.mp hnc _ $
normalizer_normalizer _
end sylow
|
0cca5f424bde22cb2e709cc5f521c318f018614c
|
57fdc8de88f5ea3bfde4325e6ecd13f93a274ab5
|
/tactic/alias.lean
|
d0e28e7e5022679ac2d16908e176d752d3430689
|
[
"Apache-2.0"
] |
permissive
|
louisanu/mathlib
|
11f56f2d40dc792bc05ee2f78ea37d73e98ecbfe
|
2bd5e2159d20a8f20d04fc4d382e65eea775ed39
|
refs/heads/master
| 1,617,706,993,439
| 1,523,163,654,000
| 1,523,163,654,000
| 124,519,997
| 0
| 0
|
Apache-2.0
| 1,520,588,283,000
| 1,520,588,283,000
| null |
UTF-8
|
Lean
| false
| false
| 4,418
|
lean
|
/-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
This file defines an alias command, which can be used to create copies
of a theorem or definition with different names.
Syntax:
/ -- doc string - /
alias my_theorem ← alias1 alias2 ...
This produces defs or theorems of the form:
/ -- doc string - /
@[alias] theorem alias1 : <type of my_theorem> := my_theorem
/ -- doc string - /
@[alias] theorem alias2 : <type of my_theorem> := my_theorem
Iff alias syntax:
alias A_iff_B ↔ B_of_A A_of_B
alias A_iff_B ↔ ..
This gets an existing biconditional theorem A_iff_B and produces
the one-way implications B_of_A and A_of_B (with no change in
implicit arguments). A blank _ can be used to avoid generating one direction.
The .. notation attempts to generate the 'of'-names automatically when the
input theorem has the form A_iff_B or A_iff_B_left etc.
-/
import data.buffer.parser
open lean.parser tactic interactive parser
namespace tactic.alias
@[user_attribute] meta def alias_attr : user_attribute :=
{ name := `alias, descr := "This definition is an alias of another." }
meta def alias_direct (d : declaration) (doc : string) (al : name) : tactic unit :=
do updateex_env $ λ env,
env.add (match d.to_definition with
| declaration.defn n ls t _ _ _ :=
declaration.defn al ls t (expr.const n (level.param <$> ls))
reducibility_hints.abbrev tt
| declaration.thm n ls t _ :=
declaration.thm al ls t $ task.pure $ expr.const n (level.param <$> ls)
| _ := undefined
end),
alias_attr.set al () tt,
add_doc_string al doc
meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → tactic 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 := pure $ @expr.const tt iffmp [] a b (f 0)
| _ f := fail "Target theorem must have the form `Π x y z, a ↔ b`"
meta def alias_iff (d : declaration) (doc : string) (al : name) (iffmp : name) : tactic unit :=
(if al = `_ then skip else get_decl al >> skip) <|> do
let ls := d.univ_params,
let t := d.type,
v ← mk_iff_mp_app iffmp t (λ_, expr.const d.to_name (level.param <$> ls)),
t' ← infer_type v,
updateex_env $ λ env, env.add (declaration.thm al ls t' $ task.pure v),
alias_attr.set al () tt,
add_doc_string al doc
meta def make_left_right : name → tactic (name × name)
| (name.mk_string s p) := do
let buf : char_buffer := s.to_char_buffer,
sum.inr parts ← pure $ run (sep_by1 (ch '_') (many_char (sat (≠ '_')))) s.to_char_buffer,
(left, _::right) ← pure $ parts.span (≠ "iff"),
let pfx (a b : string) := a.to_list.is_prefix_of b.to_list,
(suffix', right') ← pure $ right.reverse.span (λ s, pfx "left" s ∨ pfx "right" s),
let right := right'.reverse,
let suffix := suffix'.reverse,
pure (p <.> "_".intercalate (right ++ "of" :: left ++ suffix),
p <.> "_".intercalate (left ++ "of" :: right ++ suffix))
| _ := failed
@[user_command] meta def alias_cmd (meta_info : decl_meta_info)
(_ : parse $ tk "alias") : lean.parser unit :=
do old ← ident,
d ← (do old ← resolve_constant old, get_decl old) <|>
fail ("declaration " ++ to_string old ++ " not found"),
let doc := λ al : name, meta_info.doc_string.get_or_else $
"**Alias** of `" ++ to_string old ++ "`.",
do {
tk "←" <|> tk "<-",
aliases ← many ident,
↑(aliases.mmap' $ λ al, alias_direct d (doc al) al) } <|>
do {
tk "↔" <|> tk "<->",
(left, right) ←
mcond ((tk "." *> tk "." >> pure tt) <|> pure ff)
(make_left_right old <|> fail "invalid name for automatic name generation")
(prod.mk <$> types.ident_ <*> types.ident_),
alias_iff d (doc left) left `iff.mp,
alias_iff d (doc right) right `iff.mpr }
meta def get_lambda_body : expr → expr
| (expr.lam _ _ _ b) := get_lambda_body b
| a := a
meta def get_alias_target (n : name) : tactic (option name) :=
do attr ← try_core (has_attribute `alias n),
option.cases_on attr (pure none) $ λ_, do
d ← get_decl n,
let (head, args) := (get_lambda_body d.value).get_app_fn_args,
let head := if head.is_constant_of `iff.mp ∨ head.is_constant_of `iff.mpr then
expr.get_app_fn (head.ith_arg 2)
else head,
guardb $ head.is_constant,
pure $ head.const_name
end tactic.alias
|
226cdf4bb32e54e331d11495b297c15d9193091c
|
4dbc106f944ae08d9082a937156fe53f8241336c
|
/src/data/hashmap.lean
|
ab4f855b17db1af0452470fac19422b48b5dc993
|
[] |
no_license
|
spl/lean-finmap
|
feff7ee53811b172531f84b20c02e50c787fe6fc
|
936d9caeb27631e3c6cf20e972de4837c9fe98fa
|
refs/heads/master
| 1,584,501,090,642
| 1,537,511,660,000
| 1,537,515,626,000
| 134,227,269
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 11,837
|
lean
|
import data.array.basic data.list.dict data.pnat
universes u v
/-- A hash map with an `n`-sized array of association list buckets, a hash
function, and proofs that the buckets have no duplicate keys and that every
bucket is correctly hashed. -/
structure hashmap {α : Type u} (β : α → Type v) :=
/- Number of buckets -/
(n : ℕ)
/- Hash function from key to bucket index -/
(hash : α → fin n)
/- Array of association list buckets -/
(buckets : array n (list (sigma β)))
/- Each bucket has no duplicate keys. -/
(nodupkeys : ∀ (i : fin n), (buckets.read i).nodupkeys)
/- Each bucket member has a hash equal to the bucket index. -/
(hash_index : ∀ {i : fin n} {s : sigma β}, s ∈ buckets.read i → hash s.1 = i)
namespace hashmap
open list
/- default number of buckets -/
/-- Default number of buckets (8) -/
def default_n : ℕ :=
8
/-- Default positive number of buckets (default_n) -/
def default_pn : ℕ+ :=
⟨default_n, dec_trivial⟩
/- constructing empty hashmaps -/
/-- Construct an empty hashmap -/
def mk_empty {α} (β : α → Type v) (n : ℕ := default_n) (f : α → fin n) : hashmap β :=
⟨n, f, mk_array n [], λ i, nodupkeys_nil, λ _ _ h, by cases h⟩
/-- Create a hash function from a function `f : α → ℕ` using the result modulo
the number of buckets -/
def hash_mod {α} (n : ℕ+ := default_pn) (f : α → ℕ) (a : α) : fin n.val :=
⟨f a % n.val, nat.mod_lt _ n.property⟩
/-- Construct an empty nat-modulo hashmap -/
def mk_empty_mod {α} (β : α → Type v) (n : ℕ+ := default_pn) (f : α → ℕ) : hashmap β :=
mk_empty β n (hash_mod n f)
section αβ
variables {α : Type u} {β : α → Type v}
/- extensionality -/
theorem ext_core {m₁ m₂ : hashmap β} :
m₁.n = m₂.n →
m₁.hash == m₂.hash →
m₁.buckets == m₂.buckets →
m₁ = m₂ :=
begin
cases m₁,
cases m₂,
dsimp,
intros hn hh hb,
congr,
repeat { assumption },
{ apply proof_irrel_heq, substs hn hb },
{ apply proof_irrel_heq, substs hn hh hb }
end
theorem ext {m₁ m₂ : hashmap β}
(hn : m₁.n = m₂.n)
(hh : ∀ (a : α), (eq.rec_on hn (m₁.hash a) : fin m₂.n) = m₂.hash a)
(hb : ∀ (i : fin m₁.n), m₁.buckets.read i = m₂.buckets.read (eq.rec_on hn i)) :
m₁ = m₂ :=
ext_core hn
(function.hfunext rfl (λ a₁ a₂ p, heq_of_eq_rec_left hn (by rw eq_of_heq p; apply hh)))
(by cases m₁; cases m₂; dsimp at hn; subst hn; exact heq_of_eq (array.ext hb))
/- nodupkeys -/
theorem nodupkeys_of_mem_buckets {l : list (sigma β)} {m : hashmap β} (h : l ∈ m.buckets) :
l.nodupkeys :=
let ⟨i, e⟩ := h in e ▸ m.nodupkeys i
/- empty -/
/-- A hashmap is empty if all buckets are empty -/
def empty (m : hashmap β) : Prop :=
∀ (i : fin m.n), m.buckets.read i = []
section empty
variables {m : hashmap β}
theorem empty_mk_empty (β) (n : ℕ) (f : α → fin n) : empty (mk_empty β n f) :=
λ _, rfl
theorem empty_mk_empty_mod (β) (n : ℕ+) (f : α → ℕ) : empty (mk_empty_mod β n f) :=
λ _, rfl
@[simp] theorem empty_zero (h : m.n = 0) : empty m :=
λ i, by cases (h.rec_on i : fin 0).is_lt
end empty
/- to_lists -/
/-- Bucket list of a hashmap -/
def to_lists (m : hashmap β) : list (list (sigma β)) :=
m.buckets.to_list
section to_lists
variables {m : hashmap β} {i : ℕ} {l : list (sigma β)}
@[simp] theorem mem_to_lists : l ∈ m.to_lists ↔ l ∈ m.buckets :=
array.mem_to_list
theorem hash_idx_of_to_lists_enum (he : (i, l) ∈ m.to_lists.enum)
{s : sigma β} (hl : s ∈ l) : (m.hash s.1).1 = i :=
have e₁ : ∃ p, m.buckets.read ⟨i, p⟩ = l := array.mem_to_list_enum.1 he,
have e₂ : ∃ p, m.hash s.1 = ⟨i, p⟩ := e₁.imp (λ _ h, m.hash_index $ h.symm ▸ hl),
let ⟨_, h⟩ := e₂ in by rw h
theorem disjoint_to_lists_map_keys (m : hashmap β) :
pairwise disjoint (m.to_lists.map keys) :=
begin
rw [←enum_map_snd m.to_lists, pairwise_map, pairwise_map],
refine pairwise.imp_of_mem _ ((pairwise_map _).mp (nodup_enum_map_fst _)),
rw prod.forall,
intros n₁ l₁,
rw prod.forall,
intros n₂ l₂,
intros me₁ me₂ e a mka₁ mka₂,
apply e,
cases exists_mem_of_mem_keys mka₁ with b₁ mab₁,
cases exists_mem_of_mem_keys mka₂ with b₂ mab₂,
rw [←hash_idx_of_to_lists_enum me₁ mab₁, ←hash_idx_of_to_lists_enum me₂ mab₂]
end
end to_lists
/- to_list -/
/-- Association list of a hashmap -/
def to_list (m : hashmap β) : list (sigma β) :=
m.to_lists.join
section to_list
variables {m : hashmap β} {i : ℕ} {l : list (sigma β)} {s : sigma β}
section val
variables {n : ℕ} {h : α → fin n} {bs : array n (list (sigma β))}
{ndk : ∀ i, (bs.read i).nodupkeys}
{hi : ∀ i (s : sigma β), s ∈ bs.read i → h s.1 = i}
@[simp] theorem to_list_val : (mk n h bs ndk hi).to_list = bs.to_list.join :=
rfl
theorem empty_to_list : empty m ↔ m.to_list = [] :=
array.to_list_join_nil.symm
end val
theorem nodupkeys_to_list (m : hashmap β) : m.to_list.nodupkeys :=
nodupkeys_join.mpr $ and.intro
(λ l ml, by simp [to_lists] at ml; cases ml with i e; induction e; exact m.nodupkeys i)
m.disjoint_to_lists_map_keys
end to_list
/- foldl -/
/-- Left-fold of a hashmap -/
def foldl {γ : Type*} (m : hashmap β) (f : γ → sigma β → γ) (d : γ) : γ :=
m.buckets.foldl d (λ b r, b.foldl f r)
/- keys -/
/-- List of keys in a hashmap -/
def keys (m : hashmap β) : list α :=
m.to_list.keys
section keys
variables {m : hashmap β}
section val
variables {n : ℕ} {h : α → fin n} {bs : array n (list (sigma β))}
{ndk : ∀ i, (bs.read i).nodupkeys}
{hi : ∀ i (s : sigma β), s ∈ bs.read i → h s.1 = i}
@[simp] theorem keys_val :
(mk n h bs ndk hi).keys = bs.to_list.join.keys :=
rfl
end val
theorem nodup_keys (m : hashmap β) : m.keys.nodup :=
nodupkeys_iff.mpr m.nodupkeys_to_list
end keys
/- has_repr -/
instance [has_repr α] [∀ a, has_repr (β a)] : has_repr (hashmap β) :=
⟨λ m, "{" ++ string.intercalate ", " (m.to_list.map repr) ++ "}"⟩
section decidable_eq_α
variables [decidable_eq α]
/- lookup -/
/-- Look up a key in a hashmap to find the value, if it exists -/
def lookup (a : α) (m : hashmap β) : option (β a) :=
klookup a $ m.buckets.read $ m.hash a
section lookup
variables {a : α} {s : sigma β} {m : hashmap β}
section val
variables {n : ℕ} {h : α → fin n} {bs : array n (list (sigma β))}
{ndk : ∀ i, (bs.read i).nodupkeys}
{hi : ∀ i (s : sigma β), s ∈ bs.read i → h s.1 = i}
@[simp] theorem lookup_val :
lookup a (mk n h bs ndk hi) = klookup a (bs.read (h a)) :=
rfl
end val
@[simp] theorem lookup_empty (a : α) (h : empty m) : lookup a m = none :=
by simp [lookup, h (m.hash a)]
theorem lookup_iff_mem_buckets : s.2 ∈ m.lookup s.1 ↔ ∃ l, l ∈ m.buckets ∧ s ∈ l :=
calc s.2 ∈ m.lookup s.1 ↔ s ∈ m.buckets.read (m.hash s.1) :
by cases m with _ h _ ndk; simp [ndk (h s.1)]
... ↔ m.buckets.read (m.hash s.1) ∈ m.buckets ∧ s ∈ m.buckets.read (m.hash s.1) :
⟨λ h, ⟨array.read_mem _ _, h⟩, λ ⟨_, h⟩, h⟩
... ↔ ∃ l, l ∈ m.buckets ∧ s ∈ l :
⟨λ ⟨p, q⟩, ⟨_, p, q⟩, λ ⟨_, ⟨i, p⟩, q⟩,
by rw ←p at q; rw m.hash_index q; exact ⟨array.read_mem m.buckets i, q⟩⟩
end lookup
/- mem -/
instance : has_mem (sigma β) (hashmap β) :=
⟨λ s m, s.2 ∈ m.lookup s.1⟩
section mem
variables {s : sigma β} {m : hashmap β}
section val
variables {n : ℕ} {h : α → fin n} {bs : array n (list (sigma β))}
{ndk : ∀ i, (bs.read i).nodupkeys}
{hi : ∀ i (s : sigma β), s ∈ bs.read i → h s.1 = i}
@[simp] theorem mem_val : s ∈ mk n h bs ndk hi ↔ s ∈ bs.read (h s.1) :=
mem_klookup_of_nodupkeys (ndk (h s.1))
end val
theorem mem_def : s ∈ m ↔ s.2 ∈ m.lookup s.1 :=
iff.rfl
@[simp] theorem mem_to_list : s ∈ m.to_list ↔ s ∈ m :=
calc s ∈ m.to_list ↔ ∃ l, l ∈ m.to_lists ∧ s ∈ l : mem_join
... ↔ ∃ l, l ∈ m.buckets ∧ s ∈ l : by simp only [mem_to_lists]
... ↔ s ∈ m : lookup_iff_mem_buckets.symm
end mem
/- has_key -/
/-- Test for the presence of a key in a hashmap -/
def has_key (m : hashmap β) (a : α) : bool :=
(m.lookup a).is_some
section has_key
variables {a : α} {m : hashmap β}
section val
variables {n : ℕ} {h : α → fin n} {bs : array n (list (sigma β))}
{ndk : ∀ i, (bs.read i).nodupkeys}
{hi : ∀ i (s : sigma β), s ∈ bs.read i → h s.1 = i}
@[simp] theorem has_key_val :
(mk n h bs ndk hi).has_key a = (klookup a (bs.read (h a))).is_some :=
rfl
end val
theorem has_key_def : m.has_key a = (m.lookup a).is_some :=
rfl
@[simp] theorem mem_keys_iff_has_key : a ∈ m.keys ↔ m.has_key a :=
calc a ∈ m.keys ↔ ∃ (b : β a), sigma.mk a b ∈ m.to_list : mem_keys
... ↔ ∃ (b : β a), b ∈ m.lookup a : exists_congr $ λ b, mem_to_list
... ↔ m.has_key a : klookup_is_some.symm
end has_key
/- erase -/
/-- Erase a hashmap entry with the given key -/
def erase (m : hashmap β) (a : α) : hashmap β :=
{ buckets := m.buckets.modify (m.hash a) (kerase a),
nodupkeys := λ i, by by_cases e : m.hash a = i; simp [e, m.nodupkeys i],
hash_index := λ i s h, m.hash_index $
by by_cases e : m.hash a = i; simp [e] at h; [exact mem_of_mem_kerase h, exact h],
..m }
section erase
variables {a : α} {s : sigma β} {m : hashmap β}
section val
variables {n : ℕ} {h : α → fin n} {bs : array n (list (sigma β))}
{ndk : ∀ i, (bs.read i).nodupkeys}
{hi : ∀ i (s : sigma β), s ∈ bs.read i → h s.1 = i}
@[simp] theorem mem_erase_val :
s ∈ (mk n h bs ndk hi).erase a ↔ s.1 ≠ a ∧ s ∈ bs.read (h s.1) :=
begin
unfold erase,
by_cases e : h s.1 = h a,
{ simp [e, ndk (h a)] },
{ simp [ne.symm e, mt (congr_arg _) e] }
end
end val
theorem lookup_erase (m : hashmap β) : (m.erase a).lookup a = none :=
by simp [erase, lookup, m.nodupkeys (m.hash a)]
@[simp] theorem mem_erase : s ∈ m.erase a ↔ s.1 ≠ a ∧ s ∈ m :=
by cases m; simp
end erase
/- insert -/
/-- Insert a new entry in a hashmap -/
protected def insert (s : sigma β) (m : hashmap β) : hashmap β :=
{ buckets := m.buckets.modify (m.hash s.1) (kinsert s),
nodupkeys := λ i, by by_cases e : m.hash s.1 = i; simp [e, m.nodupkeys i],
hash_index := λ i s' h, begin
by_cases e : m.hash s.1 = i; simp [e] at h,
{ cases h with h h,
{ induction h, exact e },
{ exact m.hash_index (mem_of_mem_kerase h) } },
{ exact m.hash_index h }
end,
..m }
instance : has_insert (sigma β) (hashmap β) :=
⟨hashmap.insert⟩
section insert
variables {s t : sigma β} {m : hashmap β}
section val
variables {n : ℕ} {h : α → fin n} {bs : array n (list (sigma β))}
{ndk : ∀ i, (bs.read i).nodupkeys}
{hi : ∀ i (s : sigma β), s ∈ bs.read i → h s.1 = i}
@[simp] theorem mem_insert_val :
s ∈ insert t (mk n h bs ndk hi) ↔ s = t ∨ s.1 ≠ t.1 ∧ s ∈ bs.read (h s.1) :=
begin
unfold insert has_insert.insert hashmap.insert,
by_cases e : h s.1 = h t.1,
{ simp [e, ndk (h t.1)] },
{ have e' : s.1 ≠ t.1 := mt (congr_arg _) e, simp [ne.symm e, e', mt sigma.eq_fst e'] }
end
end val
@[simp] theorem mem_insert : s ∈ insert t m ↔ s = t ∨ s.1 ≠ t.1 ∧ s ∈ m :=
by cases m; simp
end insert
/-- Insert a list of entries in a hashmap -/
def insert_list (l : list (sigma β)) (m : hashmap β) : hashmap β :=
l.foldl (flip insert) m
/-- Construct a hashmap from an association list -/
def of_list (n : ℕ := default_n) (f : α → fin n) (l : list (sigma β)) : hashmap β :=
insert_list l $ mk_empty _ n f
/-- Construct a nat-modulo hashmap from an association list -/
def of_list_mod (n : ℕ+ := default_pn) (f : α → ℕ) (l : list (sigma β)) : hashmap β :=
insert_list l $ mk_empty_mod _ n f
end decidable_eq_α
end αβ
end hashmap
|
bf7c08c40ffc183c8117c3f3b24762149ea22a12
|
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
|
/src/set_theory/pgame.lean
|
e37e5d59a15d0fc154c99551c4063f720edcdbc4
|
[
"Apache-2.0"
] |
permissive
|
dexmagic/mathlib
|
ff48eefc56e2412429b31d4fddd41a976eb287ce
|
7a5d15a955a92a90e1d398b2281916b9c41270b2
|
refs/heads/master
| 1,693,481,322,046
| 1,633,360,193,000
| 1,633,360,193,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 43,063
|
lean
|
/-
Copyright (c) 2019 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Mario Carneiro, Isabel Longbottom, Scott Morrison
-/
import logic.embedding
import data.nat.cast
import data.fin
/-!
# Combinatorial (pre-)games.
The basic theory of combinatorial games, following Conway's book `On Numbers and Games`. We
construct "pregames", define an ordering and arithmetic operations on them, then show that the
operations descend to "games", defined via the equivalence relation `p ≈ q ↔ p ≤ q ∧ q ≤ p`.
The surreal numbers will be built as a quotient of a subtype of pregames.
A pregame (`pgame` below) is axiomatised via an inductive type, whose sole constructor takes two
types (thought of as indexing the the possible moves for the players Left and Right), and a pair of
functions out of these types to `pgame` (thought of as describing the resulting game after making a
move).
Combinatorial games themselves, as a quotient of pregames, are constructed in `game.lean`.
## Conway induction
By construction, the induction principle for pregames is exactly "Conway induction". That is, to
prove some predicate `pgame → Prop` holds for all pregames, it suffices to prove that for every
pregame `g`, if the predicate holds for every game resulting from making a move, then it also holds
for `g`.
While it is often convenient to work "by induction" on pregames, in some situations this becomes
awkward, so we also define accessor functions `left_moves`, `right_moves`, `move_left` and
`move_right`. There is a relation `subsequent p q`, saying that `p` can be reached by playing some
non-empty sequence of moves starting from `q`, an instance `well_founded subsequent`, and a local
tactic `pgame_wf_tac` which is helpful for discharging proof obligations in inductive proofs relying
on this relation.
## Order properties
Pregames have both a `≤` and a `<` relation, which are related in quite a subtle way. In particular,
it is worth noting that in Lean's (perhaps unfortunate?) definition of a `preorder`, we have
`lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a)`, but this is _not_ satisfied by the usual
`≤` and `<` relations on pregames. (It is satisfied once we restrict to the surreal numbers.) In
particular, `<` is not transitive; there is an example below showing `0 < star ∧ star < 0`.
We do have
```
theorem not_le {x y : pgame} : ¬ x ≤ y ↔ y < x := ...
theorem not_lt {x y : pgame} : ¬ x < y ↔ y ≤ x := ...
```
The statement `0 ≤ x` means that Left has a good response to any move by Right; in particular, the
theorem `zero_le` below states
```
0 ≤ x ↔ ∀ j : x.right_moves, ∃ i : (x.move_right j).left_moves, 0 ≤ (x.move_right j).move_left i
```
On the other hand the statement `0 < x` means that Left has a good move right now; in particular the
theorem `zero_lt` below states
```
0 < x ↔ ∃ i : left_moves x, ∀ j : right_moves (x.move_left i), 0 < (x.move_left i).move_right j
```
The theorems `le_def`, `lt_def`, give a recursive characterisation of each relation, in terms of
themselves two moves later. The theorems `le_def_lt` and `lt_def_lt` give recursive
characterisations of each relation in terms of the other relation one move later.
We define an equivalence relation `equiv p q ↔ p ≤ q ∧ q ≤ p`. Later, games will be defined as the
quotient by this relation.
## Algebraic structures
We next turn to defining the operations necessary to make games into a commutative additive group.
Addition is defined for $x = \{xL | xR\}$ and $y = \{yL | yR\}$ by $x + y = \{xL + y, x + yL | xR +
y, x + yR\}$. Negation is defined by $\{xL | xR\} = \{-xR | -xL\}$.
The order structures interact in the expected way with addition, so we have
```
theorem le_iff_sub_nonneg {x y : pgame} : x ≤ y ↔ 0 ≤ y - x := sorry
theorem lt_iff_sub_pos {x y : pgame} : x < y ↔ 0 < y - x := sorry
```
We show that these operations respect the equivalence relation, and hence descend to games. At the
level of games, these operations satisfy all the laws of a commutative group. To prove the necessary
equivalence relations at the level of pregames, we introduce the notion of a `relabelling` of a
game, and show, for example, that there is a relabelling between `x + (y + z)` and `(x + y) + z`.
## Future work
* The theory of dominated and reversible positions, and unique normal form for short games.
* Analysis of basic domineering positions.
* Hex.
* Temperature.
* The development of surreal numbers, based on this development of combinatorial games, is still
quite incomplete.
## References
The material here is all drawn from
* [Conway, *On numbers and games*][conway2001]
An interested reader may like to formalise some of the material from
* [Andreas Blass, *A game semantics for linear logic*][MR1167694]
* [André Joyal, *Remarques sur la théorie des jeux à deux personnes*][joyal1997]
-/
universes u
/-- The type of pre-games, before we have quotiented
by extensionality. In ZFC, a combinatorial game is constructed from
two sets of combinatorial games that have been constructed at an earlier
stage. To do this in type theory, we say that a pre-game is built
inductively from two families of pre-games indexed over any type
in Type u. The resulting type `pgame.{u}` lives in `Type (u+1)`,
reflecting that it is a proper class in ZFC. -/
inductive pgame : Type (u+1)
| mk : ∀ α β : Type u, (α → pgame) → (β → pgame) → pgame
namespace pgame
/--
Construct a pre-game from list of pre-games describing the available moves for Left and Right.
-/
-- TODO provide some API describing the interaction with
-- `left_moves`, `right_moves`, `move_left` and `move_right` below.
-- TODO define this at the level of games, as well, and perhaps also for finsets of games.
def of_lists (L R : list pgame.{0}) : pgame.{0} :=
pgame.mk (fin L.length) (fin R.length) (λ i, L.nth_le i i.is_lt) (λ j, R.nth_le j.val j.is_lt)
/-- The indexing type for allowable moves by Left. -/
def left_moves : pgame → Type u
| (mk l _ _ _) := l
/-- The indexing type for allowable moves by Right. -/
def right_moves : pgame → Type u
| (mk _ r _ _) := r
/-- The new game after Left makes an allowed move. -/
def move_left : Π (g : pgame), left_moves g → pgame
| (mk l _ L _) i := L i
/-- The new game after Right makes an allowed move. -/
def move_right : Π (g : pgame), right_moves g → pgame
| (mk _ r _ R) j := R j
@[simp] lemma left_moves_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).left_moves = xl := rfl
@[simp] lemma move_left_mk {xl xr xL xR i} : (⟨xl, xr, xL, xR⟩ : pgame).move_left i = xL i := rfl
@[simp] lemma right_moves_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).right_moves = xr := rfl
@[simp] lemma move_right_mk {xl xr xL xR j} : (⟨xl, xr, xL, xR⟩ : pgame).move_right j = xR j := rfl
/-- `subsequent p q` says that `p` can be obtained by playing
some nonempty sequence of moves from `q`. -/
inductive subsequent : pgame → pgame → Prop
| left : Π (x : pgame) (i : x.left_moves), subsequent (x.move_left i) x
| right : Π (x : pgame) (j : x.right_moves), subsequent (x.move_right j) x
| trans : Π (x y z : pgame), subsequent x y → subsequent y z → subsequent x z
theorem wf_subsequent : well_founded subsequent :=
⟨λ x, begin
induction x with l r L R IHl IHr,
refine ⟨_, λ y h, _⟩,
generalize_hyp e : mk l r L R = x at h,
induction h with _ i _ j a b _ h1 h2 IH1 IH2; subst e,
{ apply IHl },
{ apply IHr },
{ exact acc.inv (IH2 rfl) h1 }
end⟩
instance : has_well_founded pgame :=
{ r := subsequent,
wf := wf_subsequent }
/-- A move by Left produces a subsequent game. (For use in pgame_wf_tac.) -/
lemma subsequent.left_move {xl xr} {xL : xl → pgame} {xR : xr → pgame} {i : xl} :
subsequent (xL i) (mk xl xr xL xR) :=
subsequent.left (mk xl xr xL xR) i
/-- A move by Right produces a subsequent game. (For use in pgame_wf_tac.) -/
lemma subsequent.right_move {xl xr} {xL : xl → pgame} {xR : xr → pgame} {j : xr} :
subsequent (xR j) (mk xl xr xL xR) :=
subsequent.right (mk xl xr xL xR) j
/-- A local tactic for proving well-foundedness of recursive definitions involving pregames. -/
meta def pgame_wf_tac :=
`[solve_by_elim
[psigma.lex.left, psigma.lex.right,
subsequent.left_move, subsequent.right_move,
subsequent.left, subsequent.right, subsequent.trans]
{ max_depth := 6 }]
/-- The pre-game `zero` is defined by `0 = { | }`. -/
instance : has_zero pgame := ⟨⟨pempty, pempty, pempty.elim, pempty.elim⟩⟩
@[simp] lemma zero_left_moves : (0 : pgame).left_moves = pempty := rfl
@[simp] lemma zero_right_moves : (0 : pgame).right_moves = pempty := rfl
instance : inhabited pgame := ⟨0⟩
/-- The pre-game `one` is defined by `1 = { 0 | }`. -/
instance : has_one pgame := ⟨⟨punit, pempty, λ _, 0, pempty.elim⟩⟩
@[simp] lemma one_left_moves : (1 : pgame).left_moves = punit := rfl
@[simp] lemma one_move_left : (1 : pgame).move_left punit.star = 0 := rfl
@[simp] lemma one_right_moves : (1 : pgame).right_moves = pempty := rfl
/-- Define simultaneously by mutual induction the `<=` and `<`
relation on pre-games. The ZFC definition says that `x = {xL | xR}`
is less or equal to `y = {yL | yR}` if `∀ x₁ ∈ xL, x₁ < y`
and `∀ y₂ ∈ yR, x < y₂`, where `x < y` is the same as `¬ y <= x`.
This is a tricky induction because it only decreases one side at
a time, and it also swaps the arguments in the definition of `<`.
The solution is to define `x < y` and `x <= y` simultaneously. -/
def le_lt : Π (x y : pgame), Prop × Prop
| (mk xl xr xL xR) (mk yl yr yL yR) :=
-- the orderings of the clauses here are carefully chosen so that
-- and.left/or.inl refer to moves by Left, and
-- and.right/or.inr refer to moves by Right.
((∀ i : xl, (le_lt (xL i) ⟨yl, yr, yL, yR⟩).2) ∧ (∀ j : yr, (le_lt ⟨xl, xr, xL, xR⟩ (yR j)).2),
(∃ i : yl, (le_lt ⟨xl, xr, xL, xR⟩ (yL i)).1) ∨ (∃ j : xr, (le_lt (xR j) ⟨yl, yr, yL, yR⟩).1))
using_well_founded { dec_tac := pgame_wf_tac }
instance : has_le pgame := ⟨λ x y, (le_lt x y).1⟩
instance : has_lt pgame := ⟨λ x y, (le_lt x y).2⟩
/-- Definition of `x ≤ y` on pre-games built using the constructor. -/
@[simp] theorem mk_le_mk {xl xr xL xR yl yr yL yR} :
(⟨xl, xr, xL, xR⟩ : pgame) ≤ ⟨yl, yr, yL, yR⟩ ↔
(∀ i, xL i < ⟨yl, yr, yL, yR⟩) ∧
(∀ j, (⟨xl, xr, xL, xR⟩ : pgame) < yR j) :=
show (le_lt _ _).1 ↔ _, by { rw le_lt, refl }
/-- Definition of `x ≤ y` on pre-games, in terms of `<` -/
theorem le_def_lt {x y : pgame} : x ≤ y ↔
(∀ i : x.left_moves, x.move_left i < y) ∧
(∀ j : y.right_moves, x < y.move_right j) :=
by { cases x, cases y, rw mk_le_mk, refl }
/-- Definition of `x < y` on pre-games built using the constructor. -/
@[simp] theorem mk_lt_mk {xl xr xL xR yl yr yL yR} :
(⟨xl, xr, xL, xR⟩ : pgame) < ⟨yl, yr, yL, yR⟩ ↔
(∃ i, (⟨xl, xr, xL, xR⟩ : pgame) ≤ yL i) ∨
(∃ j, xR j ≤ ⟨yl, yr, yL, yR⟩) :=
show (le_lt _ _).2 ↔ _, by { rw le_lt, refl }
/-- Definition of `x < y` on pre-games, in terms of `≤` -/
theorem lt_def_le {x y : pgame} : x < y ↔
(∃ i : y.left_moves, x ≤ y.move_left i) ∨
(∃ j : x.right_moves, x.move_right j ≤ y) :=
by { cases x, cases y, rw mk_lt_mk, refl }
/-- The definition of `x ≤ y` on pre-games, in terms of `≤` two moves later. -/
theorem le_def {x y : pgame} : x ≤ y ↔
(∀ i : x.left_moves,
(∃ i' : y.left_moves, x.move_left i ≤ y.move_left i') ∨
(∃ j : (x.move_left i).right_moves, (x.move_left i).move_right j ≤ y)) ∧
(∀ j : y.right_moves,
(∃ i : (y.move_right j).left_moves, x ≤ (y.move_right j).move_left i) ∨
(∃ j' : x.right_moves, x.move_right j' ≤ y.move_right j)) :=
begin
rw [le_def_lt],
conv { to_lhs, simp only [lt_def_le] },
end
/-- The definition of `x < y` on pre-games, in terms of `<` two moves later. -/
theorem lt_def {x y : pgame} : x < y ↔
(∃ i : y.left_moves,
(∀ i' : x.left_moves, x.move_left i' < y.move_left i) ∧
(∀ j : (y.move_left i).right_moves, x < (y.move_left i).move_right j)) ∨
(∃ j : x.right_moves,
(∀ i : (x.move_right j).left_moves, (x.move_right j).move_left i < y) ∧
(∀ j' : y.right_moves, x.move_right j < y.move_right j')) :=
begin
rw [lt_def_le],
conv { to_lhs, simp only [le_def_lt] },
end
/-- The definition of `x ≤ 0` on pre-games, in terms of `≤ 0` two moves later. -/
theorem le_zero {x : pgame} : x ≤ 0 ↔
∀ i : x.left_moves, ∃ j : (x.move_left i).right_moves, (x.move_left i).move_right j ≤ 0 :=
begin
rw le_def,
dsimp,
simp [forall_pempty, exists_pempty]
end
/-- The definition of `0 ≤ x` on pre-games, in terms of `0 ≤` two moves later. -/
theorem zero_le {x : pgame} : 0 ≤ x ↔
∀ j : x.right_moves, ∃ i : (x.move_right j).left_moves, 0 ≤ (x.move_right j).move_left i :=
begin
rw le_def,
dsimp,
simp [forall_pempty, exists_pempty]
end
/-- The definition of `x < 0` on pre-games, in terms of `< 0` two moves later. -/
theorem lt_zero {x : pgame} : x < 0 ↔
∃ j : x.right_moves, ∀ i : (x.move_right j).left_moves, (x.move_right j).move_left i < 0 :=
begin
rw lt_def,
dsimp,
simp [forall_pempty, exists_pempty]
end
/-- The definition of `0 < x` on pre-games, in terms of `< x` two moves later. -/
theorem zero_lt {x : pgame} : 0 < x ↔
∃ i : x.left_moves, ∀ j : (x.move_left i).right_moves, 0 < (x.move_left i).move_right j :=
begin
rw lt_def,
dsimp,
simp [forall_pempty, exists_pempty]
end
/-- Given a right-player-wins game, provide a response to any move by left. -/
noncomputable def right_response {x : pgame} (h : x ≤ 0) (i : x.left_moves) :
(x.move_left i).right_moves :=
classical.some $ (le_zero.1 h) i
/-- Show that the response for right provided by `right_response`
preserves the right-player-wins condition. -/
lemma right_response_spec {x : pgame} (h : x ≤ 0) (i : x.left_moves) :
(x.move_left i).move_right (right_response h i) ≤ 0 :=
classical.some_spec $ (le_zero.1 h) i
/-- Given a left-player-wins game, provide a response to any move by right. -/
noncomputable def left_response {x : pgame} (h : 0 ≤ x) (j : x.right_moves) :
(x.move_right j).left_moves :=
classical.some $ (zero_le.1 h) j
/-- Show that the response for left provided by `left_response`
preserves the left-player-wins condition. -/
lemma left_response_spec {x : pgame} (h : 0 ≤ x) (j : x.right_moves) :
0 ≤ (x.move_right j).move_left (left_response h j) :=
classical.some_spec $ (zero_le.1 h) j
theorem lt_of_le_mk {xl xr xL xR y i} :
(⟨xl, xr, xL, xR⟩ : pgame) ≤ y → xL i < y :=
by { cases y, rw mk_le_mk, tauto }
theorem lt_of_mk_le {x : pgame} {yl yr yL yR i} :
x ≤ ⟨yl, yr, yL, yR⟩ → x < yR i :=
by { cases x, rw mk_le_mk, tauto }
theorem mk_lt_of_le {xl xr xL xR y i} :
(by exact xR i ≤ y) → (⟨xl, xr, xL, xR⟩ : pgame) < y :=
by { cases y, rw mk_lt_mk, tauto }
theorem lt_mk_of_le {x : pgame} {yl yr yL yR i} :
(by exact x ≤ yL i) → x < ⟨yl, yr, yL, yR⟩ :=
by { cases x, rw mk_lt_mk, exact λ h, or.inl ⟨_, h⟩ }
theorem not_le_lt {x y : pgame} :
(¬ x ≤ y ↔ y < x) ∧ (¬ x < y ↔ y ≤ x) :=
begin
induction x with xl xr xL xR IHxl IHxr generalizing y,
induction y with yl yr yL yR IHyl IHyr,
classical,
simp only [mk_le_mk, mk_lt_mk,
not_and_distrib, not_or_distrib, not_forall, not_exists,
and_comm, or_comm, IHxl, IHxr, IHyl, IHyr, iff_self, and_self]
end
theorem not_le {x y : pgame} : ¬ x ≤ y ↔ y < x := not_le_lt.1
theorem not_lt {x y : pgame} : ¬ x < y ↔ y ≤ x := not_le_lt.2
@[refl] protected theorem le_refl : ∀ x : pgame, x ≤ x
| ⟨l, r, L, R⟩ := by rw mk_le_mk; exact
⟨λ i, lt_mk_of_le (le_refl _), λ i, mk_lt_of_le (le_refl _)⟩
protected theorem lt_irrefl (x : pgame) : ¬ x < x :=
not_lt.2 (pgame.le_refl _)
protected theorem ne_of_lt : ∀ {x y : pgame}, x < y → x ≠ y
| x _ h rfl := pgame.lt_irrefl x h
theorem le_trans_aux
{xl xr} {xL : xl → pgame} {xR : xr → pgame}
{yl yr} {yL : yl → pgame} {yR : yr → pgame}
{zl zr} {zL : zl → pgame} {zR : zr → pgame}
(h₁ : ∀ i, mk yl yr yL yR ≤ mk zl zr zL zR → mk zl zr zL zR ≤ xL i → mk yl yr yL yR ≤ xL i)
(h₂ : ∀ i, zR i ≤ mk xl xr xL xR → mk xl xr xL xR ≤ mk yl yr yL yR → zR i ≤ mk yl yr yL yR) :
mk xl xr xL xR ≤ mk yl yr yL yR →
mk yl yr yL yR ≤ mk zl zr zL zR →
mk xl xr xL xR ≤ mk zl zr zL zR :=
by simp only [mk_le_mk] at *; exact
λ ⟨xLy, xyR⟩ ⟨yLz, yzR⟩, ⟨
λ i, not_le.1 (λ h, not_lt.2 (h₁ _ ⟨yLz, yzR⟩ h) (xLy _)),
λ i, not_le.1 (λ h, not_lt.2 (h₂ _ h ⟨xLy, xyR⟩) (yzR _))⟩
@[trans] theorem le_trans {x y z : pgame} : x ≤ y → y ≤ z → x ≤ z :=
suffices ∀ {x y z : pgame},
(x ≤ y → y ≤ z → x ≤ z) ∧ (y ≤ z → z ≤ x → y ≤ x) ∧ (z ≤ x → x ≤ y → z ≤ y),
from this.1, begin
clear x y z, intros,
induction x with xl xr xL xR IHxl IHxr generalizing y z,
induction y with yl yr yL yR IHyl IHyr generalizing z,
induction z with zl zr zL zR IHzl IHzr,
exact ⟨
le_trans_aux (λ i, (IHxl _).2.1) (λ i, (IHzr _).2.2),
le_trans_aux (λ i, (IHyl _).2.2) (λ i, (IHxr _).1),
le_trans_aux (λ i, (IHzl _).1) (λ i, (IHyr _).2.1)⟩,
end
@[trans] theorem lt_of_le_of_lt {x y z : pgame} (hxy : x ≤ y) (hyz : y < z) : x < z :=
begin
rw ←not_le at ⊢ hyz,
exact mt (λ H, le_trans H hxy) hyz
end
@[trans] theorem lt_of_lt_of_le {x y z : pgame} (hxy : x < y) (hyz : y ≤ z) : x < z :=
begin
rw ←not_le at ⊢ hxy,
exact mt (λ H, le_trans hyz H) hxy
end
/-- Define the equivalence relation on pre-games. Two pre-games
`x`, `y` are equivalent if `x ≤ y` and `y ≤ x`. -/
def equiv (x y : pgame) : Prop := x ≤ y ∧ y ≤ x
local infix ` ≈ ` := pgame.equiv
@[refl, simp] theorem equiv_refl (x) : x ≈ x := ⟨pgame.le_refl _, pgame.le_refl _⟩
@[symm] theorem equiv_symm {x y} : x ≈ y → y ≈ x | ⟨xy, yx⟩ := ⟨yx, xy⟩
@[trans] theorem equiv_trans {x y z} : x ≈ y → y ≈ z → x ≈ z
| ⟨xy, yx⟩ ⟨yz, zy⟩ := ⟨le_trans xy yz, le_trans zy yx⟩
@[trans]
theorem lt_of_lt_of_equiv {x y z} (h₁ : x < y) (h₂ : y ≈ z) : x < z := lt_of_lt_of_le h₁ h₂.1
@[trans]
theorem le_of_le_of_equiv {x y z} (h₁ : x ≤ y) (h₂ : y ≈ z) : x ≤ z := le_trans h₁ h₂.1
@[trans]
theorem lt_of_equiv_of_lt {x y z} (h₁ : x ≈ y) (h₂ : y < z) : x < z := lt_of_le_of_lt h₁.1 h₂
@[trans]
theorem le_of_equiv_of_le {x y z} (h₁ : x ≈ y) (h₂ : y ≤ z) : x ≤ z := le_trans h₁.1 h₂
theorem le_congr {x₁ y₁ x₂ y₂} : x₁ ≈ x₂ → y₁ ≈ y₂ → (x₁ ≤ y₁ ↔ x₂ ≤ y₂)
| ⟨x12, x21⟩ ⟨y12, y21⟩ := ⟨λ h, le_trans x21 (le_trans h y12), λ h, le_trans x12 (le_trans h y21)⟩
theorem lt_congr {x₁ y₁ x₂ y₂} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ < y₁ ↔ x₂ < y₂ :=
not_le.symm.trans $ (not_congr (le_congr hy hx)).trans not_le
theorem equiv_congr_left {y₁ y₂} : y₁ ≈ y₂ ↔ ∀ x₁, x₁ ≈ y₁ ↔ x₁ ≈ y₂ :=
⟨λ h x₁, ⟨λ h', equiv_trans h' h, λ h', equiv_trans h' (equiv_symm h)⟩,
λ h, (h y₁).1 $ equiv_refl _⟩
theorem equiv_congr_right {x₁ x₂} : x₁ ≈ x₂ ↔ ∀ y₁, x₁ ≈ y₁ ↔ x₂ ≈ y₁ :=
⟨λ h y₁, ⟨λ h', equiv_trans (equiv_symm h) h', λ h', equiv_trans h h'⟩,
λ h, (h x₂).2 $ equiv_refl _⟩
theorem equiv_of_mk_equiv {x y : pgame}
(L : x.left_moves ≃ y.left_moves) (R : x.right_moves ≃ y.right_moves)
(hl : ∀ (i : x.left_moves), x.move_left i ≈ y.move_left (L i))
(hr : ∀ (j : y.right_moves), x.move_right (R.symm j) ≈ y.move_right j) :
x ≈ y :=
begin
fsplit; rw le_def,
{ exact ⟨λ i, or.inl ⟨L i, (hl i).1⟩, λ j, or.inr ⟨R.symm j, (hr j).1⟩⟩ },
{ fsplit,
{ intro i,
left,
specialize hl (L.symm i),
simp only [move_left_mk, equiv.apply_symm_apply] at hl,
use ⟨L.symm i, hl.2⟩ },
{ intro j,
right,
specialize hr (R j),
simp only [move_right_mk, equiv.symm_apply_apply] at hr,
use ⟨R j, hr.2⟩ } }
end
/-- `restricted x y` says that Left always has no more moves in `x` than in `y`,
and Right always has no more moves in `y` than in `x` -/
inductive restricted : pgame.{u} → pgame.{u} → Type (u+1)
| mk : Π {x y : pgame} (L : x.left_moves → y.left_moves) (R : y.right_moves → x.right_moves),
(∀ (i : x.left_moves), restricted (x.move_left i) (y.move_left (L i))) →
(∀ (j : y.right_moves), restricted (x.move_right (R j)) (y.move_right j)) → restricted x y
/-- The identity restriction. -/
@[refl] def restricted.refl : Π (x : pgame), restricted x x
| (mk xl xr xL xR) :=
restricted.mk
id id
(λ i, restricted.refl _) (λ j, restricted.refl _)
using_well_founded { dec_tac := pgame_wf_tac }
-- TODO trans for restricted
theorem restricted.le : Π {x y : pgame} (r : restricted x y), x ≤ y
| (mk xl xr xL xR) (mk yl yr yL yR)
(restricted.mk L_embedding R_embedding L_restriction R_restriction) :=
begin
rw le_def,
exact
⟨λ i, or.inl ⟨L_embedding i, (L_restriction i).le⟩,
λ i, or.inr ⟨R_embedding i, (R_restriction i).le⟩⟩
end
/--
`relabelling x y` says that `x` and `y` are really the same game, just dressed up differently.
Specifically, there is a bijection between the moves for Left in `x` and in `y`, and similarly
for Right, and under these bijections we inductively have `relabelling`s for the consequent games.
-/
inductive relabelling : pgame.{u} → pgame.{u} → Type (u+1)
| mk : Π {x y : pgame} (L : x.left_moves ≃ y.left_moves) (R : x.right_moves ≃ y.right_moves),
(∀ (i : x.left_moves), relabelling (x.move_left i) (y.move_left (L i))) →
(∀ (j : y.right_moves), relabelling (x.move_right (R.symm j)) (y.move_right j)) →
relabelling x y
/-- If `x` is a relabelling of `y`, then Left and Right have the same moves in either game,
so `x` is a restriction of `y`. -/
def relabelling.restricted: Π {x y : pgame} (r : relabelling x y), restricted x y
| (mk xl xr xL xR) (mk yl yr yL yR) (relabelling.mk L_equiv R_equiv L_relabelling R_relabelling) :=
restricted.mk L_equiv.to_embedding R_equiv.symm.to_embedding
(λ i, (L_relabelling i).restricted)
(λ j, (R_relabelling j).restricted)
-- It's not the case that `restricted x y → restricted y x → relabelling x y`,
-- but if we insisted that the maps in a restriction were injective, then one
-- could use Schröder-Bernstein for do this.
/-- The identity relabelling. -/
@[refl] def relabelling.refl : Π (x : pgame), relabelling x x
| (mk xl xr xL xR) :=
relabelling.mk (equiv.refl _) (equiv.refl _)
(λ i, relabelling.refl _) (λ j, relabelling.refl _)
using_well_founded { dec_tac := pgame_wf_tac }
/-- Reverse a relabelling. -/
@[symm] def relabelling.symm : Π {x y : pgame}, relabelling x y → relabelling y x
| (mk xl xr xL xR) (mk yl yr yL yR) (relabelling.mk L_equiv R_equiv L_relabelling R_relabelling) :=
begin
refine relabelling.mk L_equiv.symm R_equiv.symm _ _,
{ intro i, simpa using (L_relabelling (L_equiv.symm i)).symm },
{ intro j, simpa using (R_relabelling (R_equiv j)).symm }
end
/-- Transitivity of relabelling -/
@[trans] def relabelling.trans :
Π {x y z : pgame}, relabelling x y → relabelling y z → relabelling x z
| (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR)
(relabelling.mk L_equiv₁ R_equiv₁ L_relabelling₁ R_relabelling₁)
(relabelling.mk L_equiv₂ R_equiv₂ L_relabelling₂ R_relabelling₂) :=
begin
refine relabelling.mk (L_equiv₁.trans L_equiv₂) (R_equiv₁.trans R_equiv₂) _ _,
{ intro i, simpa using (L_relabelling₁ _).trans (L_relabelling₂ _) },
{ intro j, simpa using (R_relabelling₁ _).trans (R_relabelling₂ _) },
end
theorem relabelling.le {x y : pgame} (r : relabelling x y) : x ≤ y :=
r.restricted.le
/-- A relabelling lets us prove equivalence of games. -/
theorem relabelling.equiv {x y : pgame} (r : relabelling x y) : x ≈ y :=
⟨r.le, r.symm.le⟩
instance {x y : pgame} : has_coe (relabelling x y) (x ≈ y) := ⟨relabelling.equiv⟩
/-- Replace the types indexing the next moves for Left and Right by equivalent types. -/
def relabel {x : pgame} {xl' xr'} (el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') :=
pgame.mk xl' xr' (λ i, x.move_left (el.symm i)) (λ j, x.move_right (er.symm j))
@[simp] lemma relabel_move_left' {x : pgame} {xl' xr'}
(el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') (i : xl') :
move_left (relabel el er) i = x.move_left (el.symm i) :=
rfl
@[simp] lemma relabel_move_left {x : pgame} {xl' xr'}
(el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') (i : x.left_moves) :
move_left (relabel el er) (el i) = x.move_left i :=
by simp
@[simp] lemma relabel_move_right' {x : pgame} {xl' xr'}
(el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') (j : xr') :
move_right (relabel el er) j = x.move_right (er.symm j) :=
rfl
@[simp] lemma relabel_move_right {x : pgame} {xl' xr'}
(el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') (j : x.right_moves) :
move_right (relabel el er) (er j) = x.move_right j :=
by simp
/-- The game obtained by relabelling the next moves is a relabelling of the original game. -/
def relabel_relabelling {x : pgame} {xl' xr'} (el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') :
relabelling x (relabel el er) :=
relabelling.mk el er (λ i, by simp) (λ j, by simp)
/-- The negation of `{L | R}` is `{-R | -L}`. -/
def neg : pgame → pgame
| ⟨l, r, L, R⟩ := ⟨r, l, λ i, neg (R i), λ i, neg (L i)⟩
instance : has_neg pgame := ⟨neg⟩
@[simp] lemma neg_def {xl xr xL xR} : -(mk xl xr xL xR) = mk xr xl (λ j, -(xR j)) (λ i, -(xL i)) :=
rfl
@[simp] theorem neg_neg : Π {x : pgame}, -(-x) = x
| (mk xl xr xL xR) :=
begin
dsimp [has_neg.neg, neg],
congr; funext i; apply neg_neg
end
@[simp] theorem neg_zero : -(0 : pgame) = 0 :=
begin
dsimp [has_zero.zero, has_neg.neg, neg],
congr; funext i; cases i
end
/-- An explicit equivalence between the moves for Left in `-x` and the moves for Right in `x`. -/
-- This equivalence is useful to avoid having to use `cases` unnecessarily.
def left_moves_neg (x : pgame) : (-x).left_moves ≃ x.right_moves :=
by { cases x, refl }
/-- An explicit equivalence between the moves for Right in `-x` and the moves for Left in `x`. -/
def right_moves_neg (x : pgame) : (-x).right_moves ≃ x.left_moves :=
by { cases x, refl }
@[simp] lemma move_right_left_moves_neg {x : pgame} (i : left_moves (-x)) :
move_right x ((left_moves_neg x) i) = -(move_left (-x) i) :=
begin
induction x,
exact neg_neg.symm
end
@[simp] lemma move_left_left_moves_neg_symm {x : pgame} (i : right_moves x) :
move_left (-x) ((left_moves_neg x).symm i) = -(move_right x i) :=
by { cases x, refl }
@[simp] lemma move_left_right_moves_neg {x : pgame} (i : right_moves (-x)) :
move_left x ((right_moves_neg x) i) = -(move_right (-x) i) :=
begin
induction x,
exact neg_neg.symm
end
@[simp] lemma move_right_right_moves_neg_symm {x : pgame} (i : left_moves x) :
move_right (-x) ((right_moves_neg x).symm i) = -(move_left x i) :=
by { cases x, refl }
/-- If `x` has the same moves as `y`, then `-x` has the sames moves as `-y`. -/
def relabelling.neg_congr : ∀ {x y : pgame}, x.relabelling y → (-x).relabelling (-y)
| (mk xl xr xL xR) (mk yl yr yL yR) ⟨L_equiv, R_equiv, L_relabelling, R_relabelling⟩ :=
⟨R_equiv, L_equiv,
λ i, relabelling.neg_congr (by simpa using R_relabelling (R_equiv i)),
λ i, relabelling.neg_congr (by simpa using L_relabelling (L_equiv.symm i))⟩
theorem le_iff_neg_ge : Π {x y : pgame}, x ≤ y ↔ -y ≤ -x
| (mk xl xr xL xR) (mk yl yr yL yR) :=
begin
rw [le_def],
rw [le_def],
dsimp [neg],
split,
{ intro h,
split,
{ intro i, have t := h.right i, cases t,
{ right, cases t,
use (@right_moves_neg (yR i)).symm t_w, convert le_iff_neg_ge.1 t_h, simp },
{ left, cases t,
use t_w, exact le_iff_neg_ge.1 t_h, } },
{ intro j, have t := h.left j, cases t,
{ right, cases t,
use t_w, exact le_iff_neg_ge.1 t_h, },
{ left, cases t,
use (@left_moves_neg (xL j)).symm t_w, convert le_iff_neg_ge.1 t_h, simp, } } },
{ intro h,
split,
{ intro i, have t := h.right i, cases t,
{ right, cases t,
use (@left_moves_neg (xL i)) t_w, convert le_iff_neg_ge.2 _, convert t_h, simp, },
{ left, cases t,
use t_w, exact le_iff_neg_ge.2 t_h, } },
{ intro j, have t := h.left j, cases t,
{ right, cases t,
use t_w, exact le_iff_neg_ge.2 t_h, },
{ left, cases t,
use (@right_moves_neg (yR j)) t_w, convert le_iff_neg_ge.2 _, convert t_h, simp } } },
end
using_well_founded { dec_tac := pgame_wf_tac }
theorem neg_congr {x y : pgame} (h : x ≈ y) : -x ≈ -y :=
⟨le_iff_neg_ge.1 h.2, le_iff_neg_ge.1 h.1⟩
theorem lt_iff_neg_gt : Π {x y : pgame}, x < y ↔ -y < -x :=
begin
classical,
intros,
rw [←not_le, ←not_le, not_iff_not],
apply le_iff_neg_ge
end
theorem zero_le_iff_neg_le_zero {x : pgame} : 0 ≤ x ↔ -x ≤ 0 :=
begin
convert le_iff_neg_ge,
rw neg_zero
end
theorem le_zero_iff_zero_le_neg {x : pgame} : x ≤ 0 ↔ 0 ≤ -x :=
begin
convert le_iff_neg_ge,
rw neg_zero
end
/-- The sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/
def add (x y : pgame) : pgame :=
begin
induction x with xl xr xL xR IHxl IHxr generalizing y,
induction y with yl yr yL yR IHyl IHyr,
have y := mk yl yr yL yR,
refine ⟨xl ⊕ yl, xr ⊕ yr, sum.rec _ _, sum.rec _ _⟩,
{ exact λ i, IHxl i y },
{ exact λ i, IHyl i },
{ exact λ i, IHxr i y },
{ exact λ i, IHyr i }
end
instance : has_add pgame := ⟨add⟩
/-- `x + 0` has exactly the same moves as `x`. -/
def add_zero_relabelling : Π (x : pgame.{u}), relabelling (x + 0) x
| (mk xl xr xL xR) :=
begin
refine ⟨equiv.sum_empty xl pempty, equiv.sum_empty xr pempty, _, _⟩,
{ rintro (⟨i⟩|⟨⟨⟩⟩),
apply add_zero_relabelling, },
{ rintro j,
apply add_zero_relabelling, }
end
/-- `x + 0` is equivalent to `x`. -/
lemma add_zero_equiv (x : pgame.{u}) : x + 0 ≈ x :=
(add_zero_relabelling x).equiv
/-- `0 + x` has exactly the same moves as `x`. -/
def zero_add_relabelling : Π (x : pgame.{u}), relabelling (0 + x) x
| (mk xl xr xL xR) :=
begin
refine ⟨equiv.empty_sum pempty xl, equiv.empty_sum pempty xr, _, _⟩,
{ rintro (⟨⟨⟩⟩|⟨i⟩),
apply zero_add_relabelling, },
{ rintro j,
apply zero_add_relabelling, }
end
/-- `0 + x` is equivalent to `x`. -/
lemma zero_add_equiv (x : pgame.{u}) : 0 + x ≈ x :=
(zero_add_relabelling x).equiv
/-- An explicit equivalence between the moves for Left in `x + y` and the type-theory sum
of the moves for Left in `x` and in `y`. -/
def left_moves_add (x y : pgame) : (x + y).left_moves ≃ x.left_moves ⊕ y.left_moves :=
by { cases x, cases y, refl, }
/-- An explicit equivalence between the moves for Right in `x + y` and the type-theory sum
of the moves for Right in `x` and in `y`. -/
def right_moves_add (x y : pgame) : (x + y).right_moves ≃ x.right_moves ⊕ y.right_moves :=
by { cases x, cases y, refl, }
@[simp] lemma mk_add_move_left_inl {xl xr yl yr} {xL xR yL yR} {i} :
(mk xl xr xL xR + mk yl yr yL yR).move_left (sum.inl i) =
(mk xl xr xL xR).move_left i + (mk yl yr yL yR) :=
rfl
@[simp] lemma add_move_left_inl {x y : pgame} {i} :
(x + y).move_left ((@left_moves_add x y).symm (sum.inl i)) = x.move_left i + y :=
by { cases x, cases y, refl, }
@[simp] lemma mk_add_move_right_inl {xl xr yl yr} {xL xR yL yR} {i} :
(mk xl xr xL xR + mk yl yr yL yR).move_right (sum.inl i) =
(mk xl xr xL xR).move_right i + (mk yl yr yL yR) :=
rfl
@[simp] lemma add_move_right_inl {x y : pgame} {i} :
(x + y).move_right ((@right_moves_add x y).symm (sum.inl i)) = x.move_right i + y :=
by { cases x, cases y, refl, }
@[simp] lemma mk_add_move_left_inr {xl xr yl yr} {xL xR yL yR} {i} :
(mk xl xr xL xR + mk yl yr yL yR).move_left (sum.inr i) =
(mk xl xr xL xR) + (mk yl yr yL yR).move_left i :=
rfl
@[simp] lemma add_move_left_inr {x y : pgame} {i : y.left_moves} :
(x + y).move_left ((@left_moves_add x y).symm (sum.inr i)) = x + y.move_left i :=
by { cases x, cases y, refl, }
@[simp] lemma mk_add_move_right_inr {xl xr yl yr} {xL xR yL yR} {i} :
(mk xl xr xL xR + mk yl yr yL yR).move_right (sum.inr i) =
(mk xl xr xL xR) + (mk yl yr yL yR).move_right i :=
rfl
@[simp] lemma add_move_right_inr {x y : pgame} {i} :
(x + y).move_right ((@right_moves_add x y).symm (sum.inr i)) = x + y.move_right i :=
by { cases x, cases y, refl, }
/-- If `w` has the same moves as `x` and `y` has the same moves as `z`,
then `w + y` has the same moves as `x + z`. -/
def relabelling.add_congr : ∀ {w x y z : pgame.{u}},
w.relabelling x → y.relabelling z → (w + y).relabelling (x + z)
| (mk wl wr wL wR) (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR)
⟨L_equiv₁, R_equiv₁, L_relabelling₁, R_relabelling₁⟩
⟨L_equiv₂, R_equiv₂, L_relabelling₂, R_relabelling₂⟩ :=
begin
refine ⟨equiv.sum_congr L_equiv₁ L_equiv₂, equiv.sum_congr R_equiv₁ R_equiv₂, _, _⟩,
{ rintro (i|j),
{ exact relabelling.add_congr
(L_relabelling₁ i)
(⟨L_equiv₂, R_equiv₂, L_relabelling₂, R_relabelling₂⟩) },
{ exact relabelling.add_congr
(⟨L_equiv₁, R_equiv₁, L_relabelling₁, R_relabelling₁⟩)
(L_relabelling₂ j) }},
{ rintro (i|j),
{ exact relabelling.add_congr
(R_relabelling₁ i)
(⟨L_equiv₂, R_equiv₂, L_relabelling₂, R_relabelling₂⟩) },
{ exact relabelling.add_congr
(⟨L_equiv₁, R_equiv₁, L_relabelling₁, R_relabelling₁⟩)
(R_relabelling₂ j) }}
end
using_well_founded { dec_tac := pgame_wf_tac }
instance : has_sub pgame := ⟨λ x y, x + -y⟩
/-- If `w` has the same moves as `x` and `y` has the same moves as `z`,
then `w - y` has the same moves as `x - z`. -/
def relabelling.sub_congr {w x y z : pgame}
(h₁ : w.relabelling x) (h₂ : y.relabelling z) : (w - y).relabelling (x - z) :=
h₁.add_congr h₂.neg_congr
/-- `-(x+y)` has exactly the same moves as `-x + -y`. -/
def neg_add_relabelling : Π (x y : pgame), relabelling (-(x + y)) (-x + -y)
| (mk xl xr xL xR) (mk yl yr yL yR) :=
⟨equiv.refl _, equiv.refl _,
λ j, sum.cases_on j
(λ j, neg_add_relabelling (xR j) (mk yl yr yL yR))
(λ j, neg_add_relabelling (mk xl xr xL xR) (yR j)),
λ i, sum.cases_on i
(λ i, neg_add_relabelling (xL i) (mk yl yr yL yR))
(λ i, neg_add_relabelling (mk xl xr xL xR) (yL i))⟩
using_well_founded { dec_tac := pgame_wf_tac }
theorem neg_add_le {x y : pgame} : -(x + y) ≤ -x + -y :=
(neg_add_relabelling x y).le
/-- `x+y` has exactly the same moves as `y+x`. -/
def add_comm_relabelling : Π (x y : pgame.{u}), relabelling (x + y) (y + x)
| (mk xl xr xL xR) (mk yl yr yL yR) :=
begin
refine ⟨equiv.sum_comm _ _, equiv.sum_comm _ _, _, _⟩;
rintros (_|_);
{ simp [left_moves_add, right_moves_add], apply add_comm_relabelling }
end
using_well_founded { dec_tac := pgame_wf_tac }
theorem add_comm_le {x y : pgame} : x + y ≤ y + x :=
(add_comm_relabelling x y).le
theorem add_comm_equiv {x y : pgame} : x + y ≈ y + x :=
(add_comm_relabelling x y).equiv
/-- `(x + y) + z` has exactly the same moves as `x + (y + z)`. -/
def add_assoc_relabelling : Π (x y z : pgame.{u}), relabelling ((x + y) + z) (x + (y + z))
| (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) :=
begin
refine ⟨equiv.sum_assoc _ _ _, equiv.sum_assoc _ _ _, _, _⟩,
{ rintro (⟨i|i⟩|i),
{ apply add_assoc_relabelling, },
{ change relabelling
(mk xl xr xL xR + yL i + mk zl zr zL zR) (mk xl xr xL xR + (yL i + mk zl zr zL zR)),
apply add_assoc_relabelling, },
{ change relabelling
(mk xl xr xL xR + mk yl yr yL yR + zL i) (mk xl xr xL xR + (mk yl yr yL yR + zL i)),
apply add_assoc_relabelling, } },
{ rintro (j|⟨j|j⟩),
{ apply add_assoc_relabelling, },
{ change relabelling
(mk xl xr xL xR + yR j + mk zl zr zL zR) (mk xl xr xL xR + (yR j + mk zl zr zL zR)),
apply add_assoc_relabelling, },
{ change relabelling
(mk xl xr xL xR + mk yl yr yL yR + zR j) (mk xl xr xL xR + (mk yl yr yL yR + zR j)),
apply add_assoc_relabelling, } },
end
using_well_founded { dec_tac := pgame_wf_tac }
theorem add_assoc_equiv {x y z : pgame} : (x + y) + z ≈ x + (y + z) :=
(add_assoc_relabelling x y z).equiv
theorem add_le_add_right : Π {x y z : pgame} (h : x ≤ y), x + z ≤ y + z
| (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) :=
begin
intros h,
rw le_def,
split,
{ -- if Left plays first
intros i,
change xl ⊕ zl at i,
cases i,
{ -- either they play in x
rw le_def at h,
cases h,
have t := h_left i,
rcases t with ⟨i', ih⟩ | ⟨j, jh⟩,
{ left,
refine ⟨(left_moves_add _ _).inv_fun (sum.inl i'), _⟩,
exact add_le_add_right ih, },
{ right,
refine ⟨(right_moves_add _ _).inv_fun (sum.inl j), _⟩,
convert add_le_add_right jh,
apply add_move_right_inl } },
{ -- or play in z
left,
refine ⟨(left_moves_add _ _).inv_fun (sum.inr i), _⟩,
exact add_le_add_right h, }, },
{ -- if Right plays first
intros j,
change yr ⊕ zr at j,
cases j,
{ -- either they play in y
rw le_def at h,
cases h,
have t := h_right j,
rcases t with ⟨i, ih⟩ | ⟨j', jh⟩,
{ left,
refine ⟨(left_moves_add _ _).inv_fun (sum.inl i), _⟩,
convert add_le_add_right ih,
apply add_move_left_inl },
{ right,
refine ⟨(right_moves_add _ _).inv_fun (sum.inl j'), _⟩,
exact add_le_add_right jh } },
{ -- or play in z
right,
refine ⟨(right_moves_add _ _).inv_fun (sum.inr j), _⟩,
exact add_le_add_right h } }
end
using_well_founded { dec_tac := pgame_wf_tac }
theorem add_le_add_left {x y z : pgame} (h : y ≤ z) : x + y ≤ x + z :=
calc x + y ≤ y + x : add_comm_le
... ≤ z + x : add_le_add_right h
... ≤ x + z : add_comm_le
theorem add_congr {w x y z : pgame} (h₁ : w ≈ x) (h₂ : y ≈ z) : w + y ≈ x + z :=
⟨calc w + y ≤ w + z : add_le_add_left h₂.1
... ≤ x + z : add_le_add_right h₁.1,
calc x + z ≤ x + y : add_le_add_left h₂.2
... ≤ w + y : add_le_add_right h₁.2⟩
theorem sub_congr {w x y z : pgame} (h₁ : w ≈ x) (h₂ : y ≈ z) : w - y ≈ x - z :=
add_congr h₁ (neg_congr h₂)
theorem add_left_neg_le_zero : Π {x : pgame}, (-x) + x ≤ 0
| ⟨xl, xr, xL, xR⟩ :=
begin
rw [le_def],
split,
{ intro i,
change xr ⊕ xl at i,
cases i,
{ -- If Left played in -x, Right responds with the same move in x.
right,
refine ⟨(right_moves_add _ _).inv_fun (sum.inr i), _⟩,
convert @add_left_neg_le_zero (xR i),
exact add_move_right_inr },
{ -- If Left in x, Right responds with the same move in -x.
right,
dsimp,
refine ⟨(right_moves_add _ _).inv_fun (sum.inl i), _⟩,
convert @add_left_neg_le_zero (xL i),
exact add_move_right_inl }, },
{ rintro ⟨⟩, }
end
using_well_founded { dec_tac := pgame_wf_tac }
theorem zero_le_add_left_neg : Π {x : pgame}, 0 ≤ (-x) + x :=
begin
intro x,
rw [le_iff_neg_ge, neg_zero],
exact le_trans neg_add_le add_left_neg_le_zero
end
theorem add_left_neg_equiv {x : pgame} : (-x) + x ≈ 0 :=
⟨add_left_neg_le_zero, zero_le_add_left_neg⟩
theorem add_right_neg_le_zero {x : pgame} : x + (-x) ≤ 0 :=
calc x + (-x) ≤ (-x) + x : add_comm_le
... ≤ 0 : add_left_neg_le_zero
theorem zero_le_add_right_neg {x : pgame} : 0 ≤ x + (-x) :=
calc 0 ≤ (-x) + x : zero_le_add_left_neg
... ≤ x + (-x) : add_comm_le
theorem add_right_neg_equiv {x : pgame} : x + (-x) ≈ 0 :=
⟨add_right_neg_le_zero, zero_le_add_right_neg⟩
theorem add_lt_add_right {x y z : pgame} (h : x < y) : x + z < y + z :=
suffices y + z ≤ x + z → y ≤ x, by { rw ←not_le at ⊢ h, exact mt this h },
assume w,
calc y ≤ y + 0 : (add_zero_relabelling _).symm.le
... ≤ y + (z + -z) : add_le_add_left zero_le_add_right_neg
... ≤ (y + z) + (-z) : (add_assoc_relabelling _ _ _).symm.le
... ≤ (x + z) + (-z) : add_le_add_right w
... ≤ x + (z + -z) : (add_assoc_relabelling _ _ _).le
... ≤ x + 0 : add_le_add_left add_right_neg_le_zero
... ≤ x : (add_zero_relabelling _).le
theorem add_lt_add_left {x y z : pgame} (h : y < z) : x + y < x + z :=
calc x + y ≤ y + x : add_comm_le
... < z + x : add_lt_add_right h
... ≤ x + z : add_comm_le
theorem le_iff_sub_nonneg {x y : pgame} : x ≤ y ↔ 0 ≤ y - x :=
⟨λ h, le_trans zero_le_add_right_neg (add_le_add_right h),
λ h,
calc x ≤ 0 + x : (zero_add_relabelling x).symm.le
... ≤ (y - x) + x : add_le_add_right h
... ≤ y + (-x + x) : (add_assoc_relabelling _ _ _).le
... ≤ y + 0 : add_le_add_left (add_left_neg_le_zero)
... ≤ y : (add_zero_relabelling y).le⟩
theorem lt_iff_sub_pos {x y : pgame} : x < y ↔ 0 < y - x :=
⟨λ h, lt_of_le_of_lt zero_le_add_right_neg (add_lt_add_right h),
λ h,
calc x ≤ 0 + x : (zero_add_relabelling x).symm.le
... < (y - x) + x : add_lt_add_right h
... ≤ y + (-x + x) : (add_assoc_relabelling _ _ _).le
... ≤ y + 0 : add_le_add_left (add_left_neg_le_zero)
... ≤ y : (add_zero_relabelling y).le⟩
/-- The pre-game `star`, which is fuzzy/confused with zero. -/
def star : pgame := pgame.of_lists [0] [0]
theorem star_lt_zero : star < 0 :=
by rw lt_def; exact
or.inr ⟨⟨0, zero_lt_one⟩, (by split; rintros ⟨⟩)⟩
theorem zero_lt_star : 0 < star :=
by rw lt_def; exact
or.inl ⟨⟨0, zero_lt_one⟩, (by split; rintros ⟨⟩)⟩
/-- The pre-game `ω`. (In fact all ordinals have game and surreal representatives.) -/
def omega : pgame := ⟨ulift ℕ, pempty, λ n, ↑n.1, pempty.elim⟩
theorem zero_lt_one : (0 : pgame) < 1 :=
begin
rw lt_def,
left,
use ⟨punit.star, by split; rintro ⟨ ⟩⟩,
end
/-- The pre-game `half` is defined as `{0 | 1}`. -/
def half : pgame := ⟨punit, punit, 0, 1⟩
@[simp] lemma half_move_left : half.move_left punit.star = 0 := rfl
@[simp] lemma half_move_right : half.move_right punit.star = 1 := rfl
theorem zero_lt_half : 0 < half :=
begin
rw lt_def,
left,
use punit.star,
split; rintro ⟨ ⟩,
end
theorem half_lt_one : half < 1 :=
begin
rw lt_def,
right,
use punit.star,
split; rintro ⟨ ⟩,
exact zero_lt_one,
end
end pgame
|
35d780b6122519e987d2c0b15d30277651babafb
|
1a61aba1b67cddccce19532a9596efe44be4285f
|
/library/data/nat/find.lean
|
69961e68ec9c2d975b685f05c38a569bd17ef55f
|
[
"Apache-2.0"
] |
permissive
|
eigengrau/lean
|
07986a0f2548688c13ba36231f6cdbee82abf4c6
|
f8a773be1112015e2d232661ce616d23f12874d0
|
refs/heads/master
| 1,610,939,198,566
| 1,441,352,386,000
| 1,441,352,494,000
| 41,903,576
| 0
| 0
| null | 1,441,352,210,000
| 1,441,352,210,000
| null |
UTF-8
|
Lean
| false
| false
| 3,596
|
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
Choice function for decidable predicates on natural numbers.
This module provides the following two declarations:
choose {p : nat → Prop} [d : decidable_pred p] : (∃ x, p x) → nat
choose_spec {p : nat → Prop} [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex)
-/
import data.nat.basic data.nat.order
open nat subtype decidable well_founded
namespace nat
section find_x
parameter {p : nat → Prop}
private definition lbp (x : nat) : Prop := ∀ y, y < x → ¬ p y
private lemma lbp_zero : lbp 0 :=
λ y h, absurd h (not_lt_zero y)
private lemma lbp_succ {x : nat} : lbp x → ¬ p x → lbp (succ x) :=
λ lx npx y yltsx,
or.elim (eq_or_lt_of_le (le_of_succ_le_succ yltsx))
(suppose y = x, by substvars; assumption)
(suppose y < x, lx y this)
private definition gtb (a b : nat) : Prop :=
a > b ∧ lbp a
local infix `≺`:50 := gtb
private lemma acc_of_px {x : nat} : p x → acc gtb x :=
assume h,
acc.intro x (λ (y : nat) (l : y ≺ x),
obtain (h₁ : y > x) (h₂ : ∀ a, a < y → ¬ p a), from l,
absurd h (h₂ x h₁))
private lemma acc_of_acc_succ {x : nat} : acc gtb (succ x) → acc gtb x :=
assume h,
acc.intro x (λ (y : nat) (l : y ≺ x),
by_cases
(suppose y = succ x, by substvars; assumption)
(suppose y ≠ succ x,
have x < y, from and.elim_left l,
have succ x < y, from lt_of_le_and_ne this (ne.symm `y ≠ succ x`),
acc.inv h (and.intro this (and.elim_right l))))
private lemma acc_of_px_of_gt {x y : nat} : p x → y > x → acc gtb y :=
assume px ygtx,
acc.intro y (λ (z : nat) (l : z ≺ y),
obtain (zgty : z > y) (h : ∀ a, a < z → ¬ p a), from l,
absurd px (h x (lt.trans ygtx zgty)))
private lemma acc_of_acc_of_lt : ∀ {x y : nat}, acc gtb x → y < x → acc gtb y
| 0 y a0 ylt0 := absurd ylt0 !not_lt_zero
| (succ x) y asx yltsx :=
assert acc gtb x, from acc_of_acc_succ asx,
by_cases
(suppose y = x, by substvars; assumption)
(suppose y ≠ x, acc_of_acc_of_lt `acc gtb x` (lt_of_le_and_ne (le_of_lt_succ yltsx) this))
parameter (ex : ∃ a, p a)
parameter [dp : decidable_pred p]
include dp
private lemma acc_of_ex (x : nat) : acc gtb x :=
obtain (w : nat) (pw : p w), from ex,
lt.by_cases
(suppose x < w, acc_of_acc_of_lt (acc_of_px pw) this)
(suppose x = w, by subst x; exact (acc_of_px pw))
(suppose x > w, acc_of_px_of_gt pw this)
private lemma wf_gtb : well_founded gtb :=
well_founded.intro acc_of_ex
private definition find.F (x : nat) : (Π x₁, x₁ ≺ x → lbp x₁ → {a : nat | p a}) → lbp x → {a : nat | p a} :=
match x with
| 0 := λ f l0, by_cases
(λ p0 : p 0, tag 0 p0)
(suppose ¬ p 0,
have lbp 1, from lbp_succ l0 this,
have 1 ≺ 0, from and.intro (lt.base 0) `lbp 1`,
f 1 `1 ≺ 0` `lbp 1`)
| (succ n) := λ f lsn, by_cases
(suppose p (succ n), tag (succ n) this)
(suppose ¬ p (succ n),
have lss : lbp (succ (succ n)), from lbp_succ lsn this,
have succ (succ n) ≺ succ n, from and.intro (lt.base (succ n)) lss,
f (succ (succ n)) this lss)
end
private definition find_x : {x : nat | p x} :=
@fix _ _ _ wf_gtb find.F 0 lbp_zero
end find_x
protected definition find {p : nat → Prop} [d : decidable_pred p] : (∃ x, p x) → nat :=
assume h, elt_of (find_x h)
protected theorem find_spec {p : nat → Prop} [d : decidable_pred p] (ex : ∃ x, p x) : p (nat.find ex) :=
has_property (find_x ex)
end nat
|
9f28d4b686f84ef8339723293d06e7a832e7df85
|
d406927ab5617694ec9ea7001f101b7c9e3d9702
|
/src/analysis/complex/basic.lean
|
2282d4c0ef867b25b54a4eba470d2b7b344558b3
|
[
"Apache-2.0"
] |
permissive
|
alreadydone/mathlib
|
dc0be621c6c8208c581f5170a8216c5ba6721927
|
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
|
refs/heads/master
| 1,685,523,275,196
| 1,670,184,141,000
| 1,670,184,141,000
| 287,574,545
| 0
| 0
|
Apache-2.0
| 1,670,290,714,000
| 1,597,421,623,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 15,470
|
lean
|
/-
Copyright (c) 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 data.complex.determinant
import data.complex.is_R_or_C
/-!
# Normed space structure on `ℂ`.
This file gathers basic facts on complex numbers of an analytic nature.
## Main results
This file registers `ℂ` as a normed field, expresses basic properties of the norm, and gives
tools on the real vector space structure of `ℂ`. Notably, in the namespace `complex`,
it defines functions:
* `re_clm`
* `im_clm`
* `of_real_clm`
* `conj_cle`
They are bundled versions of the real part, the imaginary part, the embedding of `ℝ` in `ℂ`, and
the complex conjugate as continuous `ℝ`-linear maps. The last two are also bundled as linear
isometries in `of_real_li` and `conj_lie`.
We also register the fact that `ℂ` is an `is_R_or_C` field.
-/
noncomputable theory
namespace complex
open_locale complex_conjugate topological_space
instance : has_norm ℂ := ⟨abs⟩
@[simp] lemma norm_eq_abs (z : ℂ) : ‖z‖ = abs z := rfl
instance : normed_add_comm_group ℂ :=
add_group_norm.to_normed_add_comm_group
{ map_zero' := map_zero abs,
neg' := abs.map_neg,
eq_zero_of_map_eq_zero' := λ _, abs.eq_zero.1,
..abs }
instance : normed_field ℂ :=
{ norm := abs,
dist_eq := λ _ _, rfl,
norm_mul' := map_mul abs,
.. complex.field, .. complex.normed_add_comm_group }
instance : densely_normed_field ℂ :=
{ lt_norm_lt := λ r₁ r₂ h₀ hr, let ⟨x, h⟩ := normed_field.exists_lt_norm_lt ℝ h₀ hr in
have this : ‖(‖x‖ : ℂ)‖ = ‖(‖x‖)‖, by simp only [norm_eq_abs, abs_of_real, real.norm_eq_abs],
⟨‖x‖, by rwa [this, norm_norm]⟩ }
instance {R : Type*} [normed_field R] [normed_algebra R ℝ] : normed_algebra R ℂ :=
{ norm_smul_le := λ r x, begin
rw [norm_eq_abs, norm_eq_abs, ←algebra_map_smul ℝ r x, algebra.smul_def, map_mul,
←norm_algebra_map' ℝ r, coe_algebra_map, abs_of_real],
refl,
end,
to_algebra := complex.algebra }
variables {E : Type*} [normed_add_comm_group E] [normed_space ℂ E]
/-- The module structure from `module.complex_to_real` is a normed space. -/
@[priority 900] -- see Note [lower instance priority]
instance _root_.normed_space.complex_to_real : normed_space ℝ E :=
normed_space.restrict_scalars ℝ ℂ E
lemma dist_eq (z w : ℂ) : dist z w = abs (z - w) := rfl
lemma dist_eq_re_im (z w : ℂ) : dist z w = real.sqrt ((z.re - w.re) ^ 2 + (z.im - w.im) ^ 2) :=
by { rw [sq, sq], refl }
@[simp] lemma dist_mk (x₁ y₁ x₂ y₂ : ℝ) :
dist (mk x₁ y₁) (mk x₂ y₂) = real.sqrt ((x₁ - x₂) ^ 2 + (y₁ - y₂) ^ 2) :=
dist_eq_re_im _ _
lemma dist_of_re_eq {z w : ℂ} (h : z.re = w.re) : dist z w = dist z.im w.im :=
by rw [dist_eq_re_im, h, sub_self, zero_pow two_pos, zero_add, real.sqrt_sq_eq_abs, real.dist_eq]
lemma nndist_of_re_eq {z w : ℂ} (h : z.re = w.re) : nndist z w = nndist z.im w.im :=
nnreal.eq $ dist_of_re_eq h
lemma edist_of_re_eq {z w : ℂ} (h : z.re = w.re) : edist z w = edist z.im w.im :=
by rw [edist_nndist, edist_nndist, nndist_of_re_eq h]
lemma dist_of_im_eq {z w : ℂ} (h : z.im = w.im) : dist z w = dist z.re w.re :=
by rw [dist_eq_re_im, h, sub_self, zero_pow two_pos, add_zero, real.sqrt_sq_eq_abs, real.dist_eq]
lemma nndist_of_im_eq {z w : ℂ} (h : z.im = w.im) : nndist z w = nndist z.re w.re :=
nnreal.eq $ dist_of_im_eq h
lemma edist_of_im_eq {z w : ℂ} (h : z.im = w.im) : edist z w = edist z.re w.re :=
by rw [edist_nndist, edist_nndist, nndist_of_im_eq h]
lemma dist_conj_self (z : ℂ) : dist (conj z) z = 2 * |z.im| :=
by rw [dist_of_re_eq (conj_re z), conj_im, dist_comm, real.dist_eq, sub_neg_eq_add, ← two_mul,
_root_.abs_mul, abs_of_pos (zero_lt_two' ℝ)]
lemma nndist_conj_self (z : ℂ) : nndist (conj z) z = 2 * real.nnabs z.im :=
nnreal.eq $ by rw [← dist_nndist, nnreal.coe_mul, nnreal.coe_two, real.coe_nnabs, dist_conj_self]
lemma dist_self_conj (z : ℂ) : dist z (conj z) = 2 * |z.im| :=
by rw [dist_comm, dist_conj_self]
lemma nndist_self_conj (z : ℂ) : nndist z (conj z) = 2 * real.nnabs z.im :=
by rw [nndist_comm, nndist_conj_self]
@[simp] lemma comap_abs_nhds_zero : filter.comap abs (𝓝 0) = 𝓝 0 := comap_norm_nhds_zero
lemma norm_real (r : ℝ) : ‖(r : ℂ)‖ = ‖r‖ := abs_of_real _
@[simp] lemma norm_rat (r : ℚ) : ‖(r : ℂ)‖ = |(r : ℝ)| :=
by { rw ← of_real_rat_cast, exact norm_real _ }
@[simp] lemma norm_nat (n : ℕ) : ‖(n : ℂ)‖ = n := abs_of_nat _
@[simp] lemma norm_int {n : ℤ} : ‖(n : ℂ)‖ = |n| :=
by simp [← rat.cast_coe_int] {single_pass := tt}
lemma norm_int_of_nonneg {n : ℤ} (hn : 0 ≤ n) : ‖(n : ℂ)‖ = n :=
by simp [hn]
@[continuity] lemma continuous_abs : continuous abs := continuous_norm
@[continuity] lemma continuous_norm_sq : continuous norm_sq :=
by simpa [← norm_sq_eq_abs] using continuous_abs.pow 2
@[simp, norm_cast] lemma nnnorm_real (r : ℝ) : ‖(r : ℂ)‖₊ = ‖r‖₊ :=
subtype.ext $ norm_real r
@[simp, norm_cast] lemma nnnorm_nat (n : ℕ) : ‖(n : ℂ)‖₊ = n :=
subtype.ext $ by simp
@[simp, norm_cast] lemma nnnorm_int (n : ℤ) : ‖(n : ℂ)‖₊ = ‖n‖₊ :=
subtype.ext $ by simp only [coe_nnnorm, norm_int, int.norm_eq_abs]
lemma nnnorm_eq_one_of_pow_eq_one {ζ : ℂ} {n : ℕ} (h : ζ ^ n = 1) (hn : n ≠ 0) :
‖ζ‖₊ = 1 :=
begin
refine (@pow_left_inj nnreal _ _ _ _ zero_le' zero_le' hn.bot_lt).mp _,
rw [←nnnorm_pow, h, nnnorm_one, one_pow],
end
lemma norm_eq_one_of_pow_eq_one {ζ : ℂ} {n : ℕ} (h : ζ ^ n = 1) (hn : n ≠ 0) :
‖ζ‖ = 1 :=
congr_arg coe (nnnorm_eq_one_of_pow_eq_one h hn)
/-- The `abs` function on `ℂ` is proper. -/
lemma tendsto_abs_cocompact_at_top : filter.tendsto abs (filter.cocompact ℂ) filter.at_top :=
tendsto_norm_cocompact_at_top
/-- The `norm_sq` function on `ℂ` is proper. -/
lemma tendsto_norm_sq_cocompact_at_top :
filter.tendsto norm_sq (filter.cocompact ℂ) filter.at_top :=
by simpa [mul_self_abs] using
tendsto_abs_cocompact_at_top.at_top_mul_at_top tendsto_abs_cocompact_at_top
open continuous_linear_map
/-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/
def re_clm : ℂ →L[ℝ] ℝ := re_lm.mk_continuous 1 (λ x, by simp [abs_re_le_abs])
@[continuity] lemma continuous_re : continuous re := re_clm.continuous
@[simp] lemma re_clm_coe : (coe (re_clm) : ℂ →ₗ[ℝ] ℝ) = re_lm := rfl
@[simp] lemma re_clm_apply (z : ℂ) : (re_clm : ℂ → ℝ) z = z.re := rfl
@[simp] lemma re_clm_norm : ‖re_clm‖ = 1 :=
le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _) $
calc 1 = ‖re_clm 1‖ : by simp
... ≤ ‖re_clm‖ : unit_le_op_norm _ _ (by simp)
@[simp] lemma re_clm_nnnorm : ‖re_clm‖₊ = 1 := subtype.ext re_clm_norm
/-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/
def im_clm : ℂ →L[ℝ] ℝ := im_lm.mk_continuous 1 (λ x, by simp [abs_im_le_abs])
@[continuity] lemma continuous_im : continuous im := im_clm.continuous
@[simp] lemma im_clm_coe : (coe (im_clm) : ℂ →ₗ[ℝ] ℝ) = im_lm := rfl
@[simp] lemma im_clm_apply (z : ℂ) : (im_clm : ℂ → ℝ) z = z.im := rfl
@[simp] lemma im_clm_norm : ‖im_clm‖ = 1 :=
le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _) $
calc 1 = ‖im_clm I‖ : by simp
... ≤ ‖im_clm‖ : unit_le_op_norm _ _ (by simp)
@[simp] lemma im_clm_nnnorm : ‖im_clm‖₊ = 1 := subtype.ext im_clm_norm
lemma restrict_scalars_one_smul_right' (x : E) :
continuous_linear_map.restrict_scalars ℝ ((1 : ℂ →L[ℂ] ℂ).smul_right x : ℂ →L[ℂ] E) =
re_clm.smul_right x + I • im_clm.smul_right x :=
by { ext ⟨a, b⟩, simp [mk_eq_add_mul_I, add_smul, mul_smul, smul_comm I] }
lemma restrict_scalars_one_smul_right (x : ℂ) :
continuous_linear_map.restrict_scalars ℝ ((1 : ℂ →L[ℂ] ℂ).smul_right x : ℂ →L[ℂ] ℂ) = x • 1 :=
by { ext1 z, dsimp, apply mul_comm }
/-- The complex-conjugation function from `ℂ` to itself is an isometric linear equivalence. -/
def conj_lie : ℂ ≃ₗᵢ[ℝ] ℂ := ⟨conj_ae.to_linear_equiv, abs_conj⟩
@[simp] lemma conj_lie_apply (z : ℂ) : conj_lie z = conj z := rfl
@[simp] lemma conj_lie_symm : conj_lie.symm = conj_lie := rfl
lemma isometry_conj : isometry (conj : ℂ → ℂ) := conj_lie.isometry
@[simp] lemma dist_conj_conj (z w : ℂ) : dist (conj z) (conj w) = dist z w :=
isometry_conj.dist_eq z w
@[simp] lemma nndist_conj_conj (z w : ℂ) : nndist (conj z) (conj w) = nndist z w :=
isometry_conj.nndist_eq z w
lemma dist_conj_comm (z w : ℂ) : dist (conj z) w = dist z (conj w) :=
by rw [← dist_conj_conj, conj_conj]
lemma nndist_conj_comm (z w : ℂ) : nndist (conj z) w = nndist z (conj w) :=
subtype.ext $ dist_conj_comm _ _
/-- The determinant of `conj_lie`, as a linear map. -/
@[simp] lemma det_conj_lie : (conj_lie.to_linear_equiv : ℂ →ₗ[ℝ] ℂ).det = -1 :=
det_conj_ae
/-- The determinant of `conj_lie`, as a linear equiv. -/
@[simp] lemma linear_equiv_det_conj_lie : conj_lie.to_linear_equiv.det = -1 :=
linear_equiv_det_conj_ae
instance : has_continuous_star ℂ := ⟨conj_lie.continuous⟩
@[continuity] lemma continuous_conj : continuous (conj : ℂ → ℂ) := continuous_star
/-- The only continuous ring homomorphisms from `ℂ` to `ℂ` are the identity and the complex
conjugation. -/
lemma ring_hom_eq_id_or_conj_of_continuous {f : ℂ →+* ℂ} (hf : continuous f) :
f = ring_hom.id ℂ ∨ f = conj :=
begin
refine (real_alg_hom_eq_id_or_conj $ alg_hom.mk' f $ map_real_smul f hf).imp (λ h, _) (λ h, _),
all_goals { convert congr_arg alg_hom.to_ring_hom h, ext1, refl, },
end
/-- Continuous linear equiv version of the conj function, from `ℂ` to `ℂ`. -/
def conj_cle : ℂ ≃L[ℝ] ℂ := conj_lie
@[simp] lemma conj_cle_coe : conj_cle.to_linear_equiv = conj_ae.to_linear_equiv := rfl
@[simp] lemma conj_cle_apply (z : ℂ) : conj_cle z = conj z := rfl
@[simp] lemma conj_cle_norm : ‖(conj_cle : ℂ →L[ℝ] ℂ)‖ = 1 :=
conj_lie.to_linear_isometry.norm_to_continuous_linear_map
@[simp] lemma conj_cle_nnorm : ‖(conj_cle : ℂ →L[ℝ] ℂ)‖₊ = 1 := subtype.ext conj_cle_norm
/-- Linear isometry version of the canonical embedding of `ℝ` in `ℂ`. -/
def of_real_li : ℝ →ₗᵢ[ℝ] ℂ := ⟨of_real_am.to_linear_map, norm_real⟩
lemma isometry_of_real : isometry (coe : ℝ → ℂ) := of_real_li.isometry
@[continuity] lemma continuous_of_real : continuous (coe : ℝ → ℂ) := of_real_li.continuous
/-- The only continuous ring homomorphism from `ℝ` to `ℂ` is the identity. -/
lemma ring_hom_eq_of_real_of_continuous {f : ℝ →+* ℂ} (h : continuous f) :
f = complex.of_real :=
begin
convert congr_arg alg_hom.to_ring_hom
(subsingleton.elim (alg_hom.mk' f $ map_real_smul f h) $ algebra.of_id ℝ ℂ),
ext1, refl,
end
/-- Continuous linear map version of the canonical embedding of `ℝ` in `ℂ`. -/
def of_real_clm : ℝ →L[ℝ] ℂ := of_real_li.to_continuous_linear_map
@[simp] lemma of_real_clm_coe : (of_real_clm : ℝ →ₗ[ℝ] ℂ) = of_real_am.to_linear_map := rfl
@[simp] lemma of_real_clm_apply (x : ℝ) : of_real_clm x = x := rfl
@[simp] lemma of_real_clm_norm : ‖of_real_clm‖ = 1 := of_real_li.norm_to_continuous_linear_map
@[simp] lemma of_real_clm_nnnorm : ‖of_real_clm‖₊ = 1 := subtype.ext $ of_real_clm_norm
noncomputable instance : is_R_or_C ℂ :=
{ re := ⟨complex.re, complex.zero_re, complex.add_re⟩,
im := ⟨complex.im, complex.zero_im, complex.add_im⟩,
I := complex.I,
I_re_ax := by simp only [add_monoid_hom.coe_mk, complex.I_re],
I_mul_I_ax := by simp only [complex.I_mul_I, eq_self_iff_true, or_true],
re_add_im_ax := λ z, by simp only [add_monoid_hom.coe_mk, complex.re_add_im,
complex.coe_algebra_map, complex.of_real_eq_coe],
of_real_re_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_re,
complex.coe_algebra_map, complex.of_real_eq_coe],
of_real_im_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_im,
complex.coe_algebra_map, complex.of_real_eq_coe],
mul_re_ax := λ z w, by simp only [complex.mul_re, add_monoid_hom.coe_mk],
mul_im_ax := λ z w, by simp only [add_monoid_hom.coe_mk, complex.mul_im],
conj_re_ax := λ z, rfl,
conj_im_ax := λ z, rfl,
conj_I_ax := by simp only [complex.conj_I, ring_hom.coe_mk],
norm_sq_eq_def_ax := λ z, by simp only [←complex.norm_sq_eq_abs, ←complex.norm_sq_apply,
add_monoid_hom.coe_mk, complex.norm_eq_abs],
mul_im_I_ax := λ z, by simp only [mul_one, add_monoid_hom.coe_mk, complex.I_im],
inv_def_ax := λ z, by simp only [complex.inv_def, complex.norm_sq_eq_abs, complex.coe_algebra_map,
complex.of_real_eq_coe, complex.norm_eq_abs],
div_I_ax := complex.div_I }
lemma _root_.is_R_or_C.re_eq_complex_re : ⇑(is_R_or_C.re : ℂ →+ ℝ) = complex.re := rfl
lemma _root_.is_R_or_C.im_eq_complex_im : ⇑(is_R_or_C.im : ℂ →+ ℝ) = complex.im := rfl
section complex_order
open_locale complex_order
lemma eq_coe_norm_of_nonneg {z : ℂ} (hz : 0 ≤ z) : z = ↑‖z‖ :=
by rw [eq_re_of_real_le hz, is_R_or_C.norm_of_real, real.norm_of_nonneg (complex.le_def.2 hz).1]
end complex_order
section
variables {α β γ : Type*}
[add_comm_monoid α] [topological_space α] [add_comm_monoid γ] [topological_space γ]
/-- The natural `add_equiv` from `ℂ` to `ℝ × ℝ`. -/
@[simps apply symm_apply_re symm_apply_im { simp_rhs := tt }]
def equiv_real_prod_add_hom : ℂ ≃+ ℝ × ℝ :=
{ map_add' := by simp, .. equiv_real_prod }
/-- The natural `linear_equiv` from `ℂ` to `ℝ × ℝ`. -/
@[simps apply symm_apply_re symm_apply_im { simp_rhs := tt }]
def equiv_real_prod_add_hom_lm : ℂ ≃ₗ[ℝ] ℝ × ℝ :=
{ map_smul' := by simp [equiv_real_prod_add_hom], .. equiv_real_prod_add_hom }
/-- The natural `continuous_linear_equiv` from `ℂ` to `ℝ × ℝ`. -/
@[simps apply symm_apply_re symm_apply_im { simp_rhs := tt }]
def equiv_real_prodₗ : ℂ ≃L[ℝ] ℝ × ℝ :=
equiv_real_prod_add_hom_lm.to_continuous_linear_equiv
end
lemma has_sum_iff {α} (f : α → ℂ) (c : ℂ) :
has_sum f c ↔ has_sum (λ x, (f x).re) c.re ∧ has_sum (λ x, (f x).im) c.im :=
begin
-- For some reason, `continuous_linear_map.has_sum` is orders of magnitude faster than
-- `has_sum.mapL` here:
refine ⟨λ h, ⟨re_clm.has_sum h, im_clm.has_sum h⟩, _⟩,
rintro ⟨h₁, h₂⟩,
convert (h₁.prod_mk h₂).mapL equiv_real_prodₗ.symm.to_continuous_linear_map,
{ ext x; refl },
{ cases c, refl }
end
end complex
namespace is_R_or_C
local notation `reC` := @is_R_or_C.re ℂ _
local notation `imC` := @is_R_or_C.im ℂ _
local notation `IC` := @is_R_or_C.I ℂ _
local notation `absC` := @is_R_or_C.abs ℂ _
local notation `norm_sqC` := @is_R_or_C.norm_sq ℂ _
@[simp] lemma re_to_complex {x : ℂ} : reC x = x.re := rfl
@[simp] lemma im_to_complex {x : ℂ} : imC x = x.im := rfl
@[simp] lemma I_to_complex : IC = complex.I := rfl
@[simp] lemma norm_sq_to_complex {x : ℂ} : norm_sqC x = complex.norm_sq x :=
by simp [is_R_or_C.norm_sq, complex.norm_sq]
@[simp] lemma abs_to_complex {x : ℂ} : absC x = complex.abs x :=
by simp [is_R_or_C.abs, complex.abs]
end is_R_or_C
|
02511e948b783899d7264b48b8bbea757bb98cd3
|
4fa161becb8ce7378a709f5992a594764699e268
|
/src/analysis/normed_space/hahn_banach.lean
|
7c55577adbe4ac6c98e76618540c380579fb2bd8
|
[
"Apache-2.0"
] |
permissive
|
laughinggas/mathlib
|
e4aa4565ae34e46e834434284cb26bd9d67bc373
|
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
|
refs/heads/master
| 1,669,496,232,688
| 1,592,831,995,000
| 1,592,831,995,000
| 274,155,979
| 0
| 0
|
Apache-2.0
| 1,592,835,190,000
| 1,592,835,189,000
| null |
UTF-8
|
Lean
| false
| false
| 3,495
|
lean
|
/-
Copyright (c) 2020 Yury Kudryashov All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Heather Macbeth
-/
import analysis.normed_space.operator_norm
import analysis.convex.cone
/-!
# Hahn-Banach theorem
In this file we prove a version of Hahn-Banach theorem for continuous linear
functions on normed spaces.
We also prove a standard corollary, needed for the isometric inclusion in the double dual.
## TODO
Prove more corollaries
-/
section basic
variables {E : Type*} [normed_group E] [normed_space ℝ E]
/-- Hahn-Banach theorem for continuous linear functions. -/
theorem exists_extension_norm_eq (p : subspace ℝ E) (f : p →L[ℝ] ℝ) :
∃ g : E →L[ℝ] ℝ, (∀ x : p, g x = f x) ∧ ∥g∥ = ∥f∥ :=
begin
rcases exists_extension_of_le_sublinear ⟨p, f⟩ (λ x, ∥f∥ * ∥x∥)
(λ c hc x, by simp only [norm_smul c x, real.norm_eq_abs, abs_of_pos hc, mul_left_comm])
(λ x y, _) (λ x, le_trans (le_abs_self _) (f.le_op_norm _))
with ⟨g, g_eq, g_le⟩,
set g' := g.mk_continuous (∥f∥)
(λ x, abs_le.2 ⟨neg_le.1 $ g.map_neg x ▸ norm_neg x ▸ g_le (-x), g_le x⟩),
{ refine ⟨g', g_eq, _⟩,
{ apply le_antisymm (g.mk_continuous_norm_le (norm_nonneg f) _),
refine f.op_norm_le_bound (norm_nonneg _) (λ x, _),
dsimp at g_eq,
rw ← g_eq,
apply g'.le_op_norm } },
{ simp only [← mul_add],
exact mul_le_mul_of_nonneg_left (norm_add_le x y) (norm_nonneg f) }
end
end basic
section dual_vector
variables {E : Type*} [normed_group E] [normed_space ℝ E]
open continuous_linear_equiv
open_locale classical
lemma coord_self' (x : E) (h : x ≠ 0) : (∥x∥ • (coord ℝ x h))
⟨x, submodule.mem_span_singleton_self x⟩ = ∥x∥ :=
calc (∥x∥ • (coord ℝ x h)) ⟨x, submodule.mem_span_singleton_self x⟩
= ∥x∥ • (linear_equiv.coord ℝ E x h) ⟨x, submodule.mem_span_singleton_self x⟩ : rfl
... = ∥x∥ • 1 : by rw linear_equiv.coord_self ℝ E x h
... = ∥x∥ : mul_one _
lemma coord_norm' (x : E) (h : x ≠ 0) : ∥∥x∥ • coord ℝ x h∥ = 1 :=
by rw [norm_smul, norm_norm, coord_norm, mul_inv_cancel (mt norm_eq_zero.mp h)]
/-- Corollary of Hahn-Banach. Given a nonzero element `x` of a normed space, there exists an
element of the dual space, of norm 1, whose value on `x` is `∥x∥`. -/
theorem exists_dual_vector (x : E) (h : x ≠ 0) : ∃ g : E →L[ℝ] ℝ, ∥g∥ = 1 ∧ g x = ∥x∥ :=
begin
cases exists_extension_norm_eq (submodule.span ℝ {x}) (∥x∥ • coord ℝ x h) with g hg,
use g, split,
{ rw [hg.2, coord_norm'] },
{ calc g x = g (⟨x, submodule.mem_span_singleton_self x⟩ : submodule.span ℝ {x}) : by simp
... = (∥x∥ • coord ℝ x h) (⟨x, submodule.mem_span_singleton_self x⟩ : submodule.span ℝ {x}) : by rw ← hg.1
... = ∥x∥ : by rw coord_self' }
end
/-- Variant of the above theorem, eliminating the hypothesis that `x` be nonzero, and choosing
the dual element arbitrarily when `x = 0`. -/
theorem exists_dual_vector' (h : 0 < vector_space.dim ℝ E) (x : E) : ∃ g : E →L[ℝ] ℝ,
∥g∥ = 1 ∧ g x = ∥x∥ :=
begin
by_cases hx : x = 0,
{ cases dim_pos_iff_exists_ne_zero.mp h with y hy,
cases exists_dual_vector y hy with g hg,
use g, refine ⟨hg.left, _⟩, simp [hx] },
{ exact exists_dual_vector x hx }
end
-- TODO: These corollaries are also true over ℂ.
end dual_vector
|
1c0c8a9c4943df3f15e96e7f4f9823563213162e
|
cf39355caa609c0f33405126beee2739aa3cb77e
|
/tests/lean/1290.lean
|
325c8deea639e41697f1f27937d6794922948edc
|
[
"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
| 457
|
lean
|
structure Category :=
(Obj : Type)
(Hom : Obj -> Obj -> Type)
structure Isomorphism ( C: Category ) { A B : C^.Obj } :=
(morphism : C^.Hom A B)
instance Isomorphism_coercion_to_morphism { C : Category } { A B C^.Obj } : has_coe (Isomorphism C A B) (C^.Hom A B) :=
(coe: Isomorphism.morphism)
instance Isomorphism_coercion_to_morphism_fixed { C : Category } { A B : C^.Obj } : has_coe (Isomorphism C) (C^.Hom A B) :=
{coe := Isomorphism.morphism}
|
3f5235fab04c35500a2aaff80f713303747fa594
|
9dc8cecdf3c4634764a18254e94d43da07142918
|
/src/data/list/defs.lean
|
76c77a323cee4e5822574870466bea900ecb72b0
|
[
"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
| 41,521
|
lean
|
/-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import data.option.defs
import logic.basic
import tactic.cache
import data.rbmap.basic
import data.rbtree.default_lt
/-!
## Definitions on lists
This file contains various definitions on lists. It does not contain
proofs about these definitions, those are contained in other files in `data/list`
-/
namespace list
open function nat
universes u v w x
variables {α β γ δ ε ζ : Type*}
instance [decidable_eq α] : has_sdiff (list α) :=
⟨ list.diff ⟩
/-- Split a list at an index.
split_at 2 [a, b, c] = ([a, b], [c]) -/
def split_at : ℕ → list α → list α × list α
| 0 a := ([], a)
| (succ n) [] := ([], [])
| (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r)
/-- An auxiliary function for `split_on_p`. -/
def split_on_p_aux {α : Type u} (P : α → Prop) [decidable_pred P] :
list α → (list α → list α) → list (list α)
| [] f := [f []]
| (h :: t) f :=
if P h then f [] :: split_on_p_aux t id
else split_on_p_aux t (λ l, f (h :: l))
/-- Split a list at every element satisfying a predicate. -/
def split_on_p {α : Type u} (P : α → Prop) [decidable_pred P] (l : list α) : list (list α) :=
split_on_p_aux P l id
/-- Split a list at every occurrence of an element.
[1,1,2,3,2,4,4].split_on 2 = [[1,1],[3],[4,4]] -/
def split_on {α : Type u} [decidable_eq α] (a : α) (as : list α) : list (list α) :=
as.split_on_p (=a)
/-- Concatenate an element at the end of a list.
concat [a, b] c = [a, b, c] -/
@[simp] def concat : list α → α → list α
| [] a := [a]
| (b::l) a := b :: concat l a
/-- `head' xs` returns the first element of `xs` if `xs` is non-empty;
it returns `none` otherwise -/
@[simp] def head' : list α → option α
| [] := none
| (a :: l) := some a
/-- Convert a list into an array (whose length is the length of `l`). -/
def to_array (l : list α) : array l.length α :=
{data := λ v, l.nth_le v.1 v.2}
/-- "default" `nth` function: returns `d` instead of `none` in the case
that the index is out of bounds. -/
def nthd (d : α) : Π (l : list α) (n : ℕ), α
| [] _ := d
| (x::xs) 0 := x
| (x::xs) (n + 1) := nthd xs n
/-- "inhabited" `nth` function: returns `default` instead of `none` in the case
that the index is out of bounds. -/
def inth [h : inhabited α] (l : list α) (n : nat) : α := nthd default l n
/-- Apply a function to the nth tail of `l`. Returns the input without
using `f` if the index is larger than the length of the list.
modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c] -/
@[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α
| 0 l := f l
| (n+1) [] := []
| (n+1) (a::l) := a :: modify_nth_tail n l
/-- Apply `f` to the head of the list, if it exists. -/
@[simp] def modify_head (f : α → α) : list α → list α
| [] := []
| (a::l) := f a :: l
/-- Apply `f` to the nth element of the list, if it exists. -/
def modify_nth (f : α → α) : ℕ → list α → list α :=
modify_nth_tail (modify_head f)
/-- Apply `f` to the last element of `l`, if it exists. -/
@[simp] def modify_last (f : α → α) : list α → list α
| [] := []
| [x] := [f x]
| (x :: xs) := x :: modify_last xs
/-- `insert_nth n a l` inserts `a` into the list `l` after the first `n` elements of `l`
`insert_nth 2 1 [1, 2, 3, 4] = [1, 2, 1, 3, 4]`-/
def insert_nth (n : ℕ) (a : α) : list α → list α := modify_nth_tail (list.cons a) n
section take'
variable [inhabited α]
/-- Take `n` elements from a list `l`. If `l` has less than `n` elements, append `n - length l`
elements `default`. -/
def take' : ∀ n, list α → list α
| 0 l := []
| (n+1) l := l.head :: take' n l.tail
end take'
/-- Get the longest initial segment of the list whose members all satisfy `p`.
take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2] -/
def take_while (p : α → Prop) [decidable_pred p] : list α → list α
| [] := []
| (a::l) := if p a then a :: take_while l else []
/-- Fold a function `f` over the list from the left, returning the list
of partial results.
scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6] -/
def scanl (f : α → β → α) : α → list β → list α
| a [] := [a]
| a (b::l) := a :: scanl (f a b) l
/-- Auxiliary definition used to define `scanr`. If `scanr_aux f b l = (b', l')`
then `scanr f b l = b' :: l'` -/
def scanr_aux (f : α → β → β) (b : β) : list α → β × list β
| [] := (b, [])
| (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l')
/-- Fold a function `f` over the list from the right, returning the list
of partial results.
scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0] -/
def scanr (f : α → β → β) (b : β) (l : list α) : list β :=
let (b', l') := scanr_aux f b l in b' :: l'
/-- Product of a list.
prod [a, b, c] = ((1 * a) * b) * c -/
def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1
/-- Sum of a list.
sum [a, b, c] = ((0 + a) + b) + c -/
-- Later this will be tagged with `to_additive`, but this can't be done yet because of import
-- dependencies.
def sum [has_add α] [has_zero α] : list α → α := foldl (+) 0
/-- The alternating sum of a list. -/
def alternating_sum {G : Type*} [has_zero G] [has_add G] [has_neg G] : list G → G
| [] := 0
| (g :: []) := g
| (g :: h :: t) := g + -h + alternating_sum t
/-- The alternating product of a list. -/
def alternating_prod {G : Type*} [has_one G] [has_mul G] [has_inv G] : list G → G
| [] := 1
| (g :: []) := g
| (g :: h :: t) := g * h⁻¹ * alternating_prod t
/-- Given a function `f : α → β ⊕ γ`, `partition_map f l` maps the list by `f`
whilst partitioning the result it into a pair of lists, `list β × list γ`,
partitioning the `sum.inl _` into the left list, and the `sum.inr _` into the right list.
`partition_map (id : ℕ ⊕ ℕ → ℕ ⊕ ℕ) [inl 0, inr 1, inl 2] = ([0,2], [1])` -/
def partition_map (f : α → β ⊕ γ) : list α → list β × list γ
| [] := ([],[])
| (x::xs) :=
match f x with
| (sum.inr r) := prod.map id (cons r) $ partition_map xs
| (sum.inl l) := prod.map (cons l) id $ partition_map xs
end
/-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such
element exists. -/
def find (p : α → Prop) [decidable_pred p] : list α → option α
| [] := none
| (a::l) := if p a then some a else find l
/-- `mfind tac l` returns the first element of `l` on which `tac` succeeds, and
fails otherwise. -/
def mfind {α} {m : Type u → Type v} [monad m] [alternative m] (tac : α → m punit) : list α → m α :=
list.mfirst $ λ a, tac a $> a
/-- `mbfind' p l` returns the first element `a` of `l` for which `p a` returns
true. `mbfind'` short-circuits, so `p` is not necessarily run on every `a` in
`l`. This is a monadic version of `list.find`. -/
def mbfind' {m : Type u → Type v} [monad m] {α : Type u} (p : α → m (ulift bool)) :
list α → m (option α)
| [] := pure none
| (x :: xs) := do
⟨px⟩ ← p x,
if px then pure (some x) else mbfind' xs
section
variables {m : Type → Type v} [monad m]
/-- A variant of `mbfind'` with more restrictive universe levels. -/
def mbfind {α} (p : α → m bool) (xs : list α) : m (option α) :=
xs.mbfind' (functor.map ulift.up ∘ p)
/-- `many p as` returns true iff `p` returns true for any element of `l`.
`many` short-circuits, so if `p` returns true for any element of `l`, later
elements are not checked. This is a monadic version of `list.any`. -/
-- Implementing this via `mbfind` would give us less universe polymorphism.
def many {α : Type u} (p : α → m bool) : list α → m bool
| [] := pure false
| (x :: xs) := do px ← p x, if px then pure tt else many xs
/-- `mall p as` returns true iff `p` returns true for all elements of `l`.
`mall` short-circuits, so if `p` returns false for any element of `l`, later
elements are not checked. This is a monadic version of `list.all`. -/
def mall {α : Type u} (p : α → m bool) (as : list α) : m bool :=
bnot <$> many (λ a, bnot <$> p a) as
/-- `mbor xs` runs the actions in `xs`, returning true if any of them returns
true. `mbor` short-circuits, so if an action returns true, later actions are
not run. This is a monadic version of `list.bor`. -/
def mbor : list (m bool) → m bool :=
many id
/-- `mband xs` runs the actions in `xs`, returning true if all of them return
true. `mband` short-circuits, so if an action returns false, later actions are
not run. This is a monadic version of `list.band`. -/
def mband : list (m bool) → m bool :=
mall id
end
/-- Auxiliary definition for `foldl_with_index`. -/
def foldl_with_index_aux (f : ℕ → α → β → α) : ℕ → α → list β → α
| _ a [] := a
| i a (b :: l) := foldl_with_index_aux (i + 1) (f i a b) l
/-- Fold a list from left to right as with `foldl`, but the combining function
also receives each element's index. -/
def foldl_with_index (f : ℕ → α → β → α) (a : α) (l : list β) : α :=
foldl_with_index_aux f 0 a l
/-- Auxiliary definition for `foldr_with_index`. -/
def foldr_with_index_aux (f : ℕ → α → β → β) : ℕ → β → list α → β
| _ b [] := b
| i b (a :: l) := f i a (foldr_with_index_aux (i + 1) b l)
/-- Fold a list from right to left as with `foldr`, but the combining function
also receives each element's index. -/
def foldr_with_index (f : ℕ → α → β → β) (b : β) (l : list α) : β :=
foldr_with_index_aux f 0 b l
/-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/
def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat :=
foldr_with_index (λ i a is, if p a then i :: is else is) [] l
/-- Returns the elements of `l` that satisfy `p` together with their indexes in
`l`. The returned list is ordered by index. -/
def indexes_values (p : α → Prop) [decidable_pred p] (l : list α) : list (ℕ × α) :=
foldr_with_index (λ i a l, if p a then (i , a) :: l else l) [] l
/-- `indexes_of a l` is the list of all indexes of `a` in `l`. For example:
```
indexes_of a [a, b, a, a] = [0, 2, 3]
```
-/
def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a)
section mfold_with_index
variables {m : Type v → Type w} [monad m]
/-- Monadic variant of `foldl_with_index`. -/
def mfoldl_with_index {α β} (f : ℕ → β → α → m β) (b : β) (as : list α) : m β :=
as.foldl_with_index (λ i ma b, do a ← ma, f i a b) (pure b)
/-- Monadic variant of `foldr_with_index`. -/
def mfoldr_with_index {α β} (f : ℕ → α → β → m β) (b : β) (as : list α) : m β :=
as.foldr_with_index (λ i a mb, do b ← mb, f i a b) (pure b)
end mfold_with_index
section mmap_with_index
variables {m : Type v → Type w} [applicative m]
/-- Auxiliary definition for `mmap_with_index`. -/
def mmap_with_index_aux {α β} (f : ℕ → α → m β) : ℕ → list α → m (list β)
| _ [] := pure []
| i (a :: as) := list.cons <$> f i a <*> mmap_with_index_aux (i + 1) as
/-- Applicative variant of `map_with_index`. -/
def mmap_with_index {α β} (f : ℕ → α → m β) (as : list α) : m (list β) :=
mmap_with_index_aux f 0 as
/-- Auxiliary definition for `mmap_with_index'`. -/
def mmap_with_index'_aux {α} (f : ℕ → α → m punit) : ℕ → list α → m punit
| _ [] := pure ⟨⟩
| i (a :: as) := f i a *> mmap_with_index'_aux (i + 1) as
/-- A variant of `mmap_with_index` specialised to applicative actions which
return `unit`. -/
def mmap_with_index' {α} (f : ℕ → α → m punit) (as : list α) : m punit :=
mmap_with_index'_aux f 0 as
end mmap_with_index
/-- `lookmap` is a combination of `lookup` and `filter_map`.
`lookmap f l` will apply `f : α → option α` to each element of the list,
replacing `a → b` at the first value `a` in the list such that `f a = some b`. -/
def lookmap (f : α → option α) : list α → list α
| [] := []
| (a::l) :=
match f a with
| some b := b :: l
| none := a :: lookmap l
end
/-- `countp p l` is the number of elements of `l` that satisfy `p`. -/
def countp (p : α → Prop) [decidable_pred p] : list α → nat
| [] := 0
| (x::xs) := if p x then succ (countp xs) else countp xs
/-- `count a l` is the number of occurrences of `a` in `l`. -/
def count [decidable_eq α] (a : α) : list α → nat := countp (eq a)
/-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`,
that is, `l₂` has the form `l₁ ++ t` for some `t`. -/
def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂
/-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`,
that is, `l₂` has the form `t ++ l₁` for some `t`. -/
def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂
/-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous
substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/
def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂
infix ` <+: `:50 := is_prefix
infix ` <:+ `:50 := is_suffix
infix ` <:+: `:50 := is_infix
/-- `inits l` is the list of initial segments of `l`.
inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]] -/
@[simp] def inits : list α → list (list α)
| [] := [[]]
| (a::l) := [] :: map (λt, a::t) (inits l)
/-- `tails l` is the list of terminal segments of `l`.
tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []] -/
@[simp] def tails : list α → list (list α)
| [] := [[]]
| (a::l) := (a::l) :: tails l
def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β)
| [] f r := f [] :: r
| (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r)
/-- `sublists' l` is the list of all (non-contiguous) sublists of `l`.
It differs from `sublists` only in the order of appearance of the sublists;
`sublists'` uses the first element of the list as the MSB,
`sublists` uses the first element of the list as the LSB.
sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] -/
def sublists' (l : list α) : list (list α) :=
sublists'_aux l id []
def sublists_aux : list α → (list α → list β → list β) → list β
| [] f := []
| (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r)))
/-- `sublists l` is the list of all (non-contiguous) sublists of `l`; cf. `sublists'`
for a different ordering.
sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] -/
def sublists (l : list α) : list (list α) :=
[] :: sublists_aux l cons
def sublists_aux₁ : list α → (list α → list β) → list β
| [] f := []
| (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys))
section forall₂
variables {r : α → β → Prop} {p : γ → δ → Prop}
/-- `forall₂ R l₁ l₂` means that `l₁` and `l₂` have the same length,
and whenever `a` is the nth element of `l₁`, and `b` is the nth element of `l₂`,
then `R a b` is satisfied. -/
inductive forall₂ (R : α → β → Prop) : list α → list β → Prop
| nil : forall₂ [] []
| cons {a b l₁ l₂} : R a b → forall₂ l₁ l₂ → forall₂ (a::l₁) (b::l₂)
attribute [simp] forall₂.nil
end forall₂
/-- `l.all₂ p` 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 all₂ (p : α → Prop) : list α → Prop
| [] := true
| (x :: []) := p x
| (x :: l) := p x ∧ all₂ l
/-- Auxiliary definition used to define `transpose`.
`transpose_aux l L` takes each element of `l` and appends it to the start of
each element of `L`.
`transpose_aux [a, b, c] [l₁, l₂, l₃] = [a::l₁, b::l₂, c::l₃]` -/
def transpose_aux : list α → list (list α) → list (list α)
| [] ls := ls
| (a::i) [] := [a] :: transpose_aux i []
| (a::i) (l::ls) := (a::l) :: transpose_aux i ls
/-- transpose of a list of lists, treated as a matrix.
transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]] -/
def transpose : list (list α) → list (list α)
| [] := []
| (l::ls) := transpose_aux l (transpose ls)
/-- List of all sections through a list of lists. A section
of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from
`L₁`, whose second element comes from `L₂`, and so on. -/
def sections : list (list α) → list (list α)
| [] := [[]]
| (l::L) := bind (sections L) $ λ s, map (λ a, a::s) l
section permutations
/-- An auxiliary function for defining `permutations`. `permutations_aux2 t ts r ys f` is equal to
`(ys ++ ts, (insert_left ys t ts).map f ++ r)`, where `insert_left ys t ts` (not explicitly
defined) is the list of lists of the form `insert_nth n t (ys ++ ts)` for `0 ≤ n < length ys`.
permutations_aux2 10 [4, 5, 6] [] [1, 2, 3] id =
([1, 2, 3, 4, 5, 6],
[[10, 1, 2, 3, 4, 5, 6],
[1, 10, 2, 3, 4, 5, 6],
[1, 2, 10, 3, 4, 5, 6]]) -/
def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β
| [] f := (ts, r)
| (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in
(y :: us, f (t :: y :: us) :: zs)
private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l)
local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas
/-- A recursor for pairs of lists. To have `C l₁ l₂` for all `l₁`, `l₂`, it suffices to have it for
`l₂ = []` and to be able to pour the elements of `l₁` into `l₂`. -/
@[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v}
(H0 : ∀ is, C [] is)
(H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂
| [] is := H0 is
| (t::ts) is :=
have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from
show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is,
length (t :: ts)),
by rw nat.succ_add; exact prod.lex.right _ (lt_succ_self _),
have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ (nat.lt_add_of_pos_left (succ_pos _)),
H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is [])
using_well_founded
{ dec_tac := tactic.assumption,
rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] }
/-- An auxiliary function for defining `permutations`. `permutations_aux ts is` is the set of all
permutations of `is ++ ts` that do not fix `ts`. -/
def permutations_aux : list α → list α → list (list α) :=
@@permutations_aux.rec (λ _ _, list (list α)) (λ is, [])
(λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2))
/-- List of all permutations of `l`.
permutations [1, 2, 3] =
[[1, 2, 3], [2, 1, 3], [3, 2, 1],
[2, 3, 1], [3, 1, 2], [1, 3, 2]] -/
def permutations (l : list α) : list (list α) :=
l :: permutations_aux l []
/-- `permutations'_aux t ts` inserts `t` into every position in `ts`, including the last.
This function is intended for use in specifications, so it is simpler than `permutations_aux2`,
which plays roughly the same role in `permutations`.
Note that `(permutations_aux2 t [] [] ts id).2` is similar to this function, but skips the last
position:
permutations'_aux 10 [1, 2, 3] =
[[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3], [1, 2, 3, 10]]
(permutations_aux2 10 [] [] [1, 2, 3] id).2 =
[[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3]] -/
@[simp] def permutations'_aux (t : α) : list α → list (list α)
| [] := [[t]]
| (y::ys) := (t :: y :: ys) :: (permutations'_aux ys).map (cons y)
/-- List of all permutations of `l`. This version of `permutations` is less efficient but has
simpler definitional equations. The permutations are in a different order,
but are equal up to permutation, as shown by `list.permutations_perm_permutations'`.
permutations [1, 2, 3] =
[[1, 2, 3], [2, 1, 3], [2, 3, 1],
[1, 3, 2], [3, 1, 2], [3, 2, 1]] -/
@[simp] def permutations' : list α → list (list α)
| [] := [[]]
| (t::ts) := (permutations' ts).bind $ permutations'_aux t
end permutations
/-- `erasep p l` removes the first element of `l` satisfying the predicate `p`. -/
def erasep (p : α → Prop) [decidable_pred p] : list α → list α
| [] := []
| (a::l) := if p a then l else a :: erasep l
/-- `extractp p l` returns a pair of an element `a` of `l` satisfying the predicate
`p`, and `l`, with `a` removed. If there is no such element `a` it returns `(none, l)`. -/
def extractp (p : α → Prop) [decidable_pred p] : list α → option α × list α
| [] := (none, [])
| (a::l) := if p a then (some a, l) else
let (a', l') := extractp l in (a', a :: l')
/-- `revzip l` returns a list of pairs of the elements of `l` paired
with the elements of `l` in reverse order.
`revzip [1,2,3,4,5] = [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]`
-/
def revzip (l : list α) : list (α × α) := zip l l.reverse
/-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`.
product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/
def product (l₁ : list α) (l₂ : list β) : list (α × β) :=
l₁.bind $ λ a, l₂.map $ prod.mk a
/- This notation binds more strongly than (pre)images, unions and intersections. -/
infixr (name := list.product) ` ×ˢ `:82 := list.product
/-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`.
sigma [1, 2] (λ_, [(5 : ℕ), 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/
protected def sigma {σ : α → Type*} (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) :=
l₁.bind $ λ a, (l₂ a).map $ sigma.mk a
/-- Auxliary definition used to define `of_fn`.
`of_fn_aux f m h l` returns the first `m` elements of `of_fn f`
appended to `l` -/
def of_fn_aux {n} (f : fin n → α) : ∀ m, m ≤ n → list α → list α
| 0 h l := l
| (succ m) h l := of_fn_aux m (le_of_lt h) (f ⟨m, h⟩ :: l)
/-- `of_fn f` with `f : fin n → α` returns the list whose ith element is `f i`
`of_fun f = [f 0, f 1, ... , f(n - 1)]` -/
def of_fn {n} (f : fin n → α) : list α :=
of_fn_aux f n (le_refl _) []
/-- `of_fn_nth_val f i` returns `some (f i)` if `i < n` and `none` otherwise. -/
def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α :=
if h : i < n then some (f ⟨i, h⟩) else none
/-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/
def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false
section pairwise
variables (R : α → α → Prop)
/-- `pairwise R l` means that all the elements with earlier indexes are
`R`-related to all the elements with later indexes.
pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3
For example if `R = (≠)` then it asserts `l` has no duplicates,
and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/
inductive pairwise : list α → Prop
| nil : pairwise []
| cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l)
variables {R}
@[simp] theorem pairwise_cons {a : α} {l : list α} :
pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l :=
⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩
attribute [simp] pairwise.nil
instance decidable_pairwise [decidable_rel R] (l : list α) : decidable (pairwise R l) :=
by induction l with hd tl ih; [exact is_true pairwise.nil,
exactI decidable_of_iff' _ pairwise_cons]
end pairwise
/-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`.
`pw_filter (≠)` is the erase duplicates function (cf. `dedup`), and `pw_filter (<)` finds
a maximal increasing subsequence in `l`. For example,
pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 2, 3, 4] -/
def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α
| [] := []
| (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH
section chain
variable (R : α → α → Prop)
/-- `chain R a l` means that `R` holds between adjacent elements of `a::l`.
chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d -/
inductive chain : α → list α → Prop
| nil {a : α} : chain a []
| cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l)
/-- `chain' R l` means that `R` holds between adjacent elements of `l`.
chain' R [a, b, c, d] ↔ R a b ∧ R b c ∧ R c d -/
def chain' : list α → Prop
| [] := true
| (a :: l) := chain R a l
variable {R}
@[simp] theorem chain_cons {a b : α} {l : list α} :
chain R a (b::l) ↔ R a b ∧ chain R b l :=
⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩
attribute [simp] chain.nil
instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) :=
by induction l generalizing a; simp only [chain.nil, chain_cons]; resetI; apply_instance
instance decidable_chain' [decidable_rel R] (l : list α) : decidable (chain' R l) :=
by cases l; dunfold chain'; apply_instance
end chain
/-- `nodup l` means that `l` has no duplicates, that is, any element appears at most
once in the list. It is defined as `pairwise (≠)`. -/
def nodup : list α → Prop := pairwise (≠)
instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) :=
list.decidable_pairwise
/-- `dedup l` removes duplicates from `l` (taking only the last occurrence).
Defined as `pw_filter (≠)`.
dedup [1, 0, 2, 2, 1] = [0, 2, 1] -/
def dedup [decidable_eq α] : list α → list α := pw_filter (≠)
/-- Greedily create a sublist of `a :: l` such that, for every two adjacent elements `a, b`,
`R a b` holds. Mostly used with ≠; for example, `destutter' (≠) 1 [2, 2, 1, 1] = [1, 2, 1]`,
`destutter' (≠) 1, [2, 3, 3] = [1, 2, 3]`, `destutter' (<) 1 [2, 5, 2, 3, 4, 9] = [1, 2, 5, 9]`. -/
def destutter' (R : α → α → Prop) [decidable_rel R] : α → list α → list α
| a [] := [a]
| a (h :: l) := if R a h then a :: destutter' h l else destutter' a l
/-- Greedily create a sublist of `l` such that, for every two adjacent elements `a, b ∈ l`,
`R a b` holds. Mostly used with ≠; for example, `destutter (≠) [1, 2, 2, 1, 1] = [1, 2, 1]`,
`destutter (≠) [1, 2, 3, 3] = [1, 2, 3]`, `destutter (<) [1, 2, 5, 2, 3, 4, 9] = [1, 2, 5, 9]`. -/
def destutter (R : α → α → Prop) [decidable_rel R] : list α → list α
| (h :: l) := destutter' R h l
| [] := []
/-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`.
It is intended mainly for proving properties of `range` and `iota`. -/
@[simp] def range' : ℕ → ℕ → list ℕ
| s 0 := []
| s (n+1) := s :: range' (s+1) n
/-- Drop `none`s from a list, and replace each remaining `some a` with `a`. -/
def reduce_option {α} : list (option α) → list α :=
list.filter_map id
/-- `ilast' x xs` returns the last element of `xs` if `xs` is non-empty;
it returns `x` otherwise -/
@[simp] def ilast' {α} : α → list α → α
| a [] := a
| a (b::l) := ilast' b l
/-- `last' xs` returns the last element of `xs` if `xs` is non-empty;
it returns `none` otherwise -/
@[simp] def last' {α} : list α → option α
| [] := none
| [a] := some a
| (b::l) := last' l
/-- `rotate l n` rotates the elements of `l` to the left by `n`
rotate [0, 1, 2, 3, 4, 5] 2 = [2, 3, 4, 5, 0, 1] -/
def rotate (l : list α) (n : ℕ) : list α :=
let (l₁, l₂) := list.split_at (n % l.length) l in l₂ ++ l₁
/-- rotate' is the same as `rotate`, but slower. Used for proofs about `rotate`-/
def rotate' : list α → ℕ → list α
| [] n := []
| l 0 := l
| (a::l) (n+1) := rotate' (l ++ [a]) n
section choose
variables (p : α → Prop) [decidable_pred p] (l : list α)
/-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`,
choose the first element with this property. This version returns both `a` and proofs
of `a ∈ l` and `p a`. -/
def choose_x : Π l : list α, Π hp : (∃ a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a }
| [] hp := false.elim (exists.elim hp (assume a h, not_mem_nil a h.left))
| (l :: ls) hp := if pl : p l then ⟨l, ⟨or.inl rfl, pl⟩⟩ else
let ⟨a, ⟨a_mem_ls, pa⟩⟩ := choose_x ls (hp.imp
(λ b ⟨o, h₂⟩, ⟨o.resolve_left (λ e, pl $ e ▸ h₂), h₂⟩)) in
⟨a, ⟨or.inr a_mem_ls, pa⟩⟩
/-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`,
choose the first element with this property. This version returns `a : α`, and properties
are given by `choose_mem` and `choose_property`. -/
def choose (hp : ∃ a, a ∈ l ∧ p a) : α := choose_x p l hp
end choose
/-- Filters and maps elements of a list -/
def mmap_filter {m : Type → Type v} [monad m] {α β} (f : α → m (option β)) :
list α → m (list β)
| [] := return []
| (h :: t) := do b ← f h, t' ← t.mmap_filter, return $
match b with none := t' | (some x) := x::t' end
/--
`mmap_upper_triangle f l` calls `f` on all elements in the upper triangular part of `l × l`.
That is, for each `e ∈ l`, it will run `f e e` and then `f e e'`
for each `e'` that appears after `e` in `l`.
Example: suppose `l = [1, 2, 3]`. `mmap_upper_triangle f l` will produce the list
`[f 1 1, f 1 2, f 1 3, f 2 2, f 2 3, f 3 3]`.
-/
def mmap_upper_triangle {m} [monad m] {α β : Type u} (f : α → α → m β) : list α → m (list β)
| [] := return []
| (h::t) := do v ← f h h, l ← t.mmap (f h), t ← t.mmap_upper_triangle, return $ (v::l) ++ t
/--
`mmap'_diag f l` calls `f` on all elements in the upper triangular part of `l × l`.
That is, for each `e ∈ l`, it will run `f e e` and then `f e e'`
for each `e'` that appears after `e` in `l`.
Example: suppose `l = [1, 2, 3]`. `mmap'_diag f l` will evaluate, in this order,
`f 1 1`, `f 1 2`, `f 1 3`, `f 2 2`, `f 2 3`, `f 3 3`.
-/
def mmap'_diag {m} [monad m] {α} (f : α → α → m unit) : list α → m unit
| [] := return ()
| (h::t) := f h h >> t.mmap' (f h) >> t.mmap'_diag
protected def traverse {F : Type u → Type v} [applicative F] {α β : Type*} (f : α → F β) :
list α → F (list β)
| [] := pure []
| (x :: xs) := list.cons <$> f x <*> traverse xs
/-- `get_rest l l₁` returns `some l₂` if `l = l₁ ++ l₂`.
If `l₁` is not a prefix of `l`, returns `none` -/
def get_rest [decidable_eq α] : list α → list α → option (list α)
| l [] := some l
| [] _ := none
| (x::l) (y::l₁) := if x = y then get_rest l l₁ else none
/--
`list.slice n m xs` removes a slice of length `m` at index `n` in list `xs`.
-/
def slice {α} : ℕ → ℕ → list α → list α
| 0 n xs := xs.drop n
| (succ n) m [] := []
| (succ n) m (x :: xs) := x :: slice n m xs
/--
Left-biased version of `list.map₂`. `map₂_left' f as bs` applies `f` to each
pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is
applied to `none` for the remaining `aᵢ`. Returns the results of the `f`
applications and the remaining `bs`.
```
map₂_left' prod.mk [1, 2] ['a'] = ([(1, some 'a'), (2, none)], [])
map₂_left' prod.mk [1] ['a', 'b'] = ([(1, some 'a')], ['b'])
```
-/
@[simp] def map₂_left' (f : α → option β → γ) : list α → list β → (list γ × list β)
| [] bs := ([], bs)
| (a :: as) [] :=
((a :: as).map (λ a, f a none), [])
| (a :: as) (b :: bs) :=
let rec := map₂_left' as bs in
(f a (some b) :: rec.fst, rec.snd)
/--
Right-biased version of `list.map₂`. `map₂_right' f as bs` applies `f` to each
pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is
applied to `none` for the remaining `bᵢ`. Returns the results of the `f`
applications and the remaining `as`.
```
map₂_right' prod.mk [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], [])
map₂_right' prod.mk [1, 2] ['a'] = ([(some 1, 'a')], [2])
```
-/
def map₂_right' (f : option α → β → γ) (as : list α) (bs : list β) : (list γ × list α) :=
map₂_left' (flip f) bs as
/--
Left-biased version of `list.zip`. `zip_left' as bs` returns the list of
pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the
remaining `aᵢ` are paired with `none`. Also returns the remaining `bs`.
```
zip_left' [1, 2] ['a'] = ([(1, some 'a'), (2, none)], [])
zip_left' [1] ['a', 'b'] = ([(1, some 'a')], ['b'])
zip_left' = map₂_left' prod.mk
```
-/
def zip_left' : list α → list β → list (α × option β) × list β :=
map₂_left' prod.mk
/--
Right-biased version of `list.zip`. `zip_right' as bs` returns the list of
pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the
remaining `bᵢ` are paired with `none`. Also returns the remaining `as`.
```
zip_right' [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], [])
zip_right' [1, 2] ['a'] = ([(some 1, 'a')], [2])
zip_right' = map₂_right' prod.mk
```
-/
def zip_right' : list α → list β → list (option α × β) × list α :=
map₂_right' prod.mk
/--
Left-biased version of `list.map₂`. `map₂_left f as bs` applies `f` to each pair
`aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none`
for the remaining `aᵢ`.
```
map₂_left prod.mk [1, 2] ['a'] = [(1, some 'a'), (2, none)]
map₂_left prod.mk [1] ['a', 'b'] = [(1, some 'a')]
map₂_left f as bs = (map₂_left' f as bs).fst
```
-/
@[simp] def map₂_left (f : α → option β → γ) : list α → list β → list γ
| [] _ := []
| (a :: as) [] := (a :: as).map (λ a, f a none)
| (a :: as) (b :: bs) := f a (some b) :: map₂_left as bs
/--
Right-biased version of `list.map₂`. `map₂_right f as bs` applies `f` to each
pair `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is applied to
`none` for the remaining `bᵢ`.
```
map₂_right prod.mk [1, 2] ['a'] = [(some 1, 'a')]
map₂_right prod.mk [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')]
map₂_right f as bs = (map₂_right' f as bs).fst
```
-/
def map₂_right (f : option α → β → γ) (as : list α) (bs : list β) :
list γ :=
map₂_left (flip f) bs as
/--
Left-biased version of `list.zip`. `zip_left as bs` returns the list of pairs
`(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the
remaining `aᵢ` are paired with `none`.
```
zip_left [1, 2] ['a'] = [(1, some 'a'), (2, none)]
zip_left [1] ['a', 'b'] = [(1, some 'a')]
zip_left = map₂_left prod.mk
```
-/
def zip_left : list α → list β → list (α × option β) :=
map₂_left prod.mk
/--
Right-biased version of `list.zip`. `zip_right as bs` returns the list of pairs
`(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the
remaining `bᵢ` are paired with `none`.
```
zip_right [1, 2] ['a'] = [(some 1, 'a')]
zip_right [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')]
zip_right = map₂_right prod.mk
```
-/
def zip_right : list α → list β → list (option α × β) :=
map₂_right prod.mk
/--
If all elements of `xs` are `some xᵢ`, `all_some xs` returns the `xᵢ`. Otherwise
it returns `none`.
```
all_some [some 1, some 2] = some [1, 2]
all_some [some 1, none ] = none
```
-/
def all_some : list (option α) → option (list α)
| [] := some []
| (some a :: as) := cons a <$> all_some as
| (none :: as) := none
/--
`fill_nones xs ys` replaces the `none`s in `xs` with elements of `ys`. If there
are not enough `ys` to replace all the `none`s, the remaining `none`s are
dropped from `xs`.
```
fill_nones [none, some 1, none, none] [2, 3] = [2, 1, 3]
```
-/
def fill_nones {α} : list (option α) → list α → list α
| [] _ := []
| (some a :: as) as' := a :: fill_nones as as'
| (none :: as) [] := as.reduce_option
| (none :: as) (a :: as') := a :: fill_nones as as'
/--
`take_list as ns` extracts successive sublists from `as`. For `ns = n₁ ... nₘ`,
it first takes the `n₁` initial elements from `as`, then the next `n₂` ones,
etc. It returns the sublists of `as` -- one for each `nᵢ` -- and the remaining
elements of `as`. If `as` does not have at least as many elements as the sum of
the `nᵢ`, the corresponding sublists will have less than `nᵢ` elements.
```
take_list ['a', 'b', 'c', 'd', 'e'] [2, 1, 1] = ([['a', 'b'], ['c'], ['d']], ['e'])
take_list ['a', 'b'] [3, 1] = ([['a', 'b'], []], [])
```
-/
def take_list {α} : list α → list ℕ → list (list α) × list α
| xs [] := ([], xs)
| xs (n :: ns) :=
let ⟨xs₁, xs₂⟩ := xs.split_at n in
let ⟨xss, rest⟩ := take_list xs₂ ns in
(xs₁ :: xss, rest)
/--
`to_rbmap as` is the map that associates each index `i` of `as` with the
corresponding element of `as`.
```
to_rbmap ['a', 'b', 'c'] = rbmap_of [(0, 'a'), (1, 'b'), (2, 'c')]
```
-/
def to_rbmap {α : Type*} : list α → rbmap ℕ α :=
foldl_with_index (λ i mapp a, mapp.insert i a) (mk_rbmap ℕ α)
/-- Auxliary definition used to define `to_chunks`.
`to_chunks_aux n xs i` returns `(xs.take i, (xs.drop i).to_chunks (n+1))`,
that is, the first `i` elements of `xs`, and the remaining elements chunked into
sublists of length `n+1`. -/
def to_chunks_aux {α} (n : ℕ) : list α → ℕ → list α × list (list α)
| [] i := ([], [])
| (x::xs) 0 := let (l, L) := to_chunks_aux xs n in ([], (x::l)::L)
| (x::xs) (i+1) := let (l, L) := to_chunks_aux xs i in (x::l, L)
/--
`xs.to_chunks n` splits the list into sublists of size at most `n`,
such that `(xs.to_chunks n).join = xs`.
```
[1, 2, 3, 4, 5, 6, 7, 8].to_chunks 10 = [[1, 2, 3, 4, 5, 6, 7, 8]]
[1, 2, 3, 4, 5, 6, 7, 8].to_chunks 3 = [[1, 2, 3], [4, 5, 6], [7, 8]]
[1, 2, 3, 4, 5, 6, 7, 8].to_chunks 2 = [[1, 2], [3, 4], [5, 6], [7, 8]]
[1, 2, 3, 4, 5, 6, 7, 8].to_chunks 0 = [[1, 2, 3, 4, 5, 6, 7, 8]]
```
-/
def to_chunks {α} : ℕ → list α → list (list α)
| _ [] := []
| 0 xs := [xs]
| (n+1) (x::xs) := let (l, L) := to_chunks_aux n xs n in (x::l)::L
/--
Asynchronous version of `list.map`.
-/
meta def map_async_chunked {α β} (f : α → β) (xs : list α) (chunk_size := 1024) : list β :=
((xs.to_chunks chunk_size).map (λ xs, task.delay (λ _, list.map f xs))).bind task.get
/-!
We add some n-ary versions of `list.zip_with` for functions with more than two arguments.
These can also be written in terms of `list.zip` or `list.zip_with`.
For example, `zip_with3 f xs ys zs` could also be written as
`zip_with id (zip_with f xs ys) zs`
or as
`(zip xs $ zip ys zs).map $ λ ⟨x, y, z⟩, f x y z`.
-/
/-- Ternary version of `list.zip_with`. -/
def zip_with3 (f : α → β → γ → δ) : list α → list β → list γ → list δ
| (x::xs) (y::ys) (z::zs) := f x y z :: zip_with3 xs ys zs
| _ _ _ := []
/-- Quaternary version of `list.zip_with`. -/
def zip_with4 (f : α → β → γ → δ → ε) : list α → list β → list γ → list δ → list ε
| (x::xs) (y::ys) (z::zs) (u::us) := f x y z u :: zip_with4 xs ys zs us
| _ _ _ _ := []
/-- Quinary version of `list.zip_with`. -/
def zip_with5 (f : α → β → γ → δ → ε → ζ) : list α → list β → list γ → list δ → list ε → list ζ
| (x::xs) (y::ys) (z::zs) (u::us) (v::vs) := f x y z u v :: zip_with5 xs ys zs us vs
| _ _ _ _ _ := []
/-- Given a starting list `old`, a list of booleans and a replacement list `new`,
read the items in `old` in succession and either replace them with the next element of `new` or
not, according as to whether the corresponding boolean is `tt` or `ff`. -/
def replace_if : list α → list bool → list α → list α
| l _ [] := l
| [] _ _ := []
| l [] _ := l
| (n::ns) (tf::bs) e@(c::cs) := if tf then c :: ns.replace_if bs cs else n :: ns.replace_if bs e
/-- An auxiliary function for `list.map_with_prefix_suffix`. -/
def map_with_prefix_suffix_aux {α β} (f : list α → α → list α → β) : list α → list α → list β
| prev [] := []
| prev (h::t) := f prev h t :: map_with_prefix_suffix_aux (prev.concat h) t
/--
`list.map_with_prefix_suffix f l` maps `f` across a list `l`.
For each `a ∈ l` with `l = pref ++ [a] ++ suff`, `a` is mapped to `f pref a suff`.
Example: if `f : list ℕ → ℕ → list ℕ → β`,
`list.map_with_prefix_suffix f [1, 2, 3]` will produce the list
`[f [] 1 [2, 3], f [1] 2 [3], f [1, 2] 3 []]`.
-/
def map_with_prefix_suffix {α β} (f : list α → α → list α → β) (l : list α) : list β :=
map_with_prefix_suffix_aux f [] l
/--
`list.map_with_complement f l` is a variant of `list.map_with_prefix_suffix`
that maps `f` across a list `l`.
For each `a ∈ l` with `l = pref ++ [a] ++ suff`, `a` is mapped to `f a (pref ++ suff)`,
i.e., the list input to `f` is `l` with `a` removed.
Example: if `f : ℕ → list ℕ → β`, `list.map_with_complement f [1, 2, 3]` will produce the list
`[f 1 [2, 3], f 2 [1, 3], f 3 [1, 2]]`.
-/
def map_with_complement {α β} (f : α → list α → β) : list α → list β :=
map_with_prefix_suffix $ λ pref a suff, f a (pref ++ suff)
end list
|
3056d04722622419c1469f5ee5f57e892e0d18be
|
b9d8165d695e844c92d9d4cdcac7b5ab9efe09f7
|
/src/analysis/specific_limits.lean
|
5fde3f5b558f104c84e37d7cee28bd5b2679553b
|
[
"Apache-2.0"
] |
permissive
|
spapinistarkware/mathlib
|
e917d9c44bf85ef51db18e7a11615959f714efc5
|
0a9a1ff463a1f26e27d7c391eb7f6334f0d90383
|
refs/heads/master
| 1,606,808,129,547
| 1,577,478,369,000
| 1,577,478,369,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 18,975
|
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 specific limit computations.
-/
import analysis.normed_space.basic algebra.geom_sum
import topology.instances.ennreal
noncomputable theory
open_locale classical topological_space
open classical function lattice filter finset metric
variables {α : Type*} {β : Type*} {ι : Type*}
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the left) also tends to infinity. The archimedean assumption is convenient to get a
statement that works on `ℕ`, `ℤ` and `ℝ`, although not necessary (a version in ordered fields is
given in `tendsto_at_top_mul_left'`). -/
lemma tendsto_at_top_mul_left [decidable_linear_ordered_semiring α] [archimedean α]
{l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) :
tendsto (λx, r * f x) l at_top :=
begin
apply (tendsto_at_top _ _).2 (λb, _),
obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1 : α) ≤ n • r := archimedean.arch 1 hr,
have hn' : 1 ≤ r * n, by rwa add_monoid.smul_eq_mul' at hn,
filter_upwards [(tendsto_at_top _ _).1 hf (n * max b 0)],
assume x hx,
calc b ≤ 1 * max b 0 : by { rw [one_mul], exact le_max_left _ _ }
... ≤ (r * n) * max b 0 : mul_le_mul_of_nonneg_right hn' (le_max_right _ _)
... = r * (n * max b 0) : by rw [mul_assoc]
... ≤ r * f x : mul_le_mul_of_nonneg_left hx (le_of_lt hr)
end
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the right) also tends to infinity. The archimedean assumption is convenient to get a
statement that works on `ℕ`, `ℤ` and `ℝ`, although not necessary (a version in ordered fields is
given in `tendsto_at_top_mul_right'`). -/
lemma tendsto_at_top_mul_right [decidable_linear_ordered_semiring α] [archimedean α]
{l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) :
tendsto (λx, f x * r) l at_top :=
begin
apply (tendsto_at_top _ _).2 (λb, _),
obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1 : α) ≤ n • r := archimedean.arch 1 hr,
have hn' : 1 ≤ (n : α) * r, by rwa add_monoid.smul_eq_mul at hn,
filter_upwards [(tendsto_at_top _ _).1 hf (max b 0 * n)],
assume x hx,
calc b ≤ max b 0 * 1 : by { rw [mul_one], exact le_max_left _ _ }
... ≤ max b 0 * (n * r) : mul_le_mul_of_nonneg_left hn' (le_max_right _ _)
... = (max b 0 * n) * r : by rw [mul_assoc]
... ≤ f x * r : mul_le_mul_of_nonneg_right hx (le_of_lt hr)
end
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the left) also tends to infinity. For a version working in `ℕ` or `ℤ`, use
`tendsto_at_top_mul_left` instead. -/
lemma tendsto_at_top_mul_left' [linear_ordered_field α]
{l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) :
tendsto (λx, r * f x) l at_top :=
begin
apply (tendsto_at_top _ _).2 (λb, _),
filter_upwards [(tendsto_at_top _ _).1 hf (b/r)],
assume x hx,
simpa [div_le_iff' hr] using hx
end
/-- If a function tends to infinity along a filter, then this function multiplied by a positive
constant (on the right) also tends to infinity. For a version working in `ℕ` or `ℤ`, use
`tendsto_at_top_mul_right` instead. -/
lemma tendsto_at_top_mul_right' [linear_ordered_field α]
{l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) :
tendsto (λx, f x * r) l at_top :=
by simpa [mul_comm] using tendsto_at_top_mul_left' hr hf
/-- If a function tends to infinity along a filter, then this function divided by a positive
constant also tends to infinity. -/
lemma tendsto_at_top_div [linear_ordered_field α]
{l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) :
tendsto (λx, f x / r) l at_top :=
tendsto_at_top_mul_right' (inv_pos hr) hf
/-- The function `x ↦ x⁻¹` tends to `+∞` on the right of `0`. -/
lemma tendsto_inv_zero_at_top [discrete_linear_ordered_field α] [topological_space α]
[orderable_topology α] : tendsto (λx:α, x⁻¹) (nhds_within (0 : α) (set.Ioi 0)) at_top :=
begin
apply (tendsto_at_top _ _).2 (λb, _),
refine mem_nhds_within_Ioi_iff_exists_Ioo_subset.2 ⟨(max b 1)⁻¹, by simp [zero_lt_one], λx hx, _⟩,
calc b ≤ max b 1 : le_max_left _ _
... ≤ x⁻¹ : begin
apply (le_inv _ hx.1).2 (le_of_lt hx.2),
exact lt_of_lt_of_le zero_lt_one (le_max_right _ _)
end
end
lemma summable_of_absolute_convergence_real {f : ℕ → ℝ} :
(∃r, tendsto (λn, (range n).sum (λi, abs (f i))) at_top (𝓝 r)) → summable f
| ⟨r, hr⟩ :=
begin
refine summable_of_summable_norm ⟨r, (has_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩,
exact assume i, norm_nonneg _,
simpa only using hr
end
lemma tendsto_pow_at_top_at_top_of_gt_1 {r : ℝ} (h : 1 < r) :
tendsto (λn:ℕ, r ^ n) at_top at_top :=
(tendsto_at_top_at_top _).2 $ assume p,
let ⟨n, hn⟩ := pow_unbounded_of_one_lt p h in
⟨n, λ m hnm, le_of_lt $
lt_of_lt_of_le hn (pow_le_pow (le_of_lt h) hnm)⟩
lemma tendsto_inverse_at_top_nhds_0 : tendsto (λr:ℝ, r⁻¹) at_top (𝓝 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 tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) :
tendsto (λn:ℕ, r^n) at_top (𝓝 0) :=
by_cases
(assume : r = 0, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, this, tendsto_const_nhds])
(assume : r ≠ 0,
have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (𝓝 0),
from tendsto.comp tendsto_inverse_at_top_nhds_0
(tendsto_pow_at_top_at_top_of_gt_1 $ one_lt_inv (lt_of_le_of_ne h₁ this.symm) h₂),
tendsto.congr' (univ_mem_sets' $ by simp *) this)
lemma nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : nnreal} (hr : r < 1) :
tendsto (λ n:ℕ, r^n) at_top (𝓝 0) :=
nnreal.tendsto_coe.1 $ by simp only [nnreal.coe_pow, nnreal.coe_zero,
tendsto_pow_at_top_nhds_0_of_lt_1 r.coe_nonneg hr]
lemma ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ennreal} (hr : r < 1) :
tendsto (λ n:ℕ, r^n) at_top (𝓝 0) :=
begin
rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩,
rw [← ennreal.coe_zero],
norm_cast at *,
apply nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 hr
end
lemma tendsto_pow_at_top_nhds_0_of_lt_1_normed_field {K : Type*} [normed_field K] {ξ : K}
(_ : ∥ξ∥ < 1) : tendsto (λ n : ℕ, ξ^n) at_top (𝓝 0) :=
begin
rw[tendsto_iff_norm_tendsto_zero],
convert tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg ξ) ‹∥ξ∥ < 1›,
ext n,
simp
end
lemma tendsto_pow_at_top_at_top_of_gt_1_nat {k : ℕ} (h : 1 < k) :
tendsto (λn:ℕ, k ^ n) at_top at_top :=
tendsto_coe_nat_real_at_top_iff.1 $
have hr : 1 < (k : ℝ), by rw [← nat.cast_one, nat.cast_lt]; exact h,
by simpa using tendsto_pow_at_top_at_top_of_gt_1 hr
lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (𝓝 0) :=
tendsto.comp tendsto_inverse_at_top_nhds_0 (tendsto_coe_nat_real_at_top_iff.2 tendsto_id)
lemma tendsto_const_div_at_top_nhds_0_nat (C : ℝ) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) :=
by simpa only [mul_zero] using tendsto_const_nhds.mul tendsto_inverse_at_top_nhds_0_nat
lemma tendsto_one_div_add_at_top_nhds_0_nat :
tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (𝓝 0) :=
suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (𝓝 0), by simpa,
(tendsto_add_at_top_iff_nat 1).2 (tendsto_const_div_at_top_nhds_0_nat 1)
lemma has_sum_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) :
has_sum (λn:ℕ, r ^ n) (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 (𝓝 ((0 - 1) * (r - 1)⁻¹)),
from ((tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂).sub tendsto_const_nhds).mul tendsto_const_nhds,
have (λ n, (range n).sum (λ i, r ^ i)) = (λ n, geom_series r n) := rfl,
(has_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $
by simp [neg_inv, geom_sum, div_eq_mul_inv, *] at *
lemma summable_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : summable (λn:ℕ, r ^ n) :=
⟨_, has_sum_geometric h₁ h₂⟩
lemma tsum_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : (∑n:ℕ, r ^ n) = (1 - r)⁻¹ :=
tsum_eq_has_sum (has_sum_geometric h₁ h₂)
lemma has_sum_geometric_two : has_sum (λn:ℕ, ((1:ℝ)/2) ^ n) 2 :=
by convert has_sum_geometric _ _; norm_num
lemma summable_geometric_two : summable (λn:ℕ, ((1:ℝ)/2) ^ n) :=
⟨_, has_sum_geometric_two⟩
lemma tsum_geometric_two : (∑n:ℕ, ((1:ℝ)/2) ^ n) = 2 :=
tsum_eq_has_sum has_sum_geometric_two
lemma has_sum_geometric_two' (a : ℝ) : has_sum (λn:ℕ, (a / 2) / 2 ^ n) a :=
begin
convert has_sum_mul_left (a / 2) (has_sum_geometric
(le_of_lt one_half_pos) one_half_lt_one),
{ funext n, simp,
rw ← pow_inv; [refl, exact two_ne_zero] },
{ norm_num, rw div_mul_cancel _ two_ne_zero }
end
lemma summable_geometric_two' (a : ℝ) : summable (λ n:ℕ, (a / 2) / 2 ^ n) :=
⟨a, has_sum_geometric_two' a⟩
lemma tsum_geometric_two' (a : ℝ) : (∑ n:ℕ, (a / 2) / 2^n) = a :=
tsum_eq_has_sum $ has_sum_geometric_two' a
lemma nnreal.has_sum_geometric {r : nnreal} (hr : r < 1) :
has_sum (λ n : ℕ, r ^ n) (1 - r)⁻¹ :=
begin
apply nnreal.has_sum_coe.1,
push_cast,
rw [nnreal.coe_sub (le_of_lt hr)],
exact has_sum_geometric r.coe_nonneg hr
end
lemma nnreal.summable_geometric {r : nnreal} (hr : r < 1) : summable (λn:ℕ, r ^ n) :=
⟨_, nnreal.has_sum_geometric hr⟩
lemma tsum_geometric_nnreal {r : nnreal} (hr : r < 1) : (∑n:ℕ, r ^ n) = (1 - r)⁻¹ :=
tsum_eq_has_sum (nnreal.has_sum_geometric hr)
/-- The series `pow r` converges to `(1-r)⁻¹`. For `r < 1` the RHS is a finite number,
and for `1 ≤ r` the RHS equals `∞`. -/
lemma ennreal.tsum_geometric (r : ennreal) : (∑n:ℕ, r ^ n) = (1 - r)⁻¹ :=
begin
cases lt_or_le r 1 with hr hr,
{ rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩,
norm_cast at *,
convert ennreal.tsum_coe_eq (nnreal.has_sum_geometric hr),
rw [ennreal.coe_inv $ ne_of_gt $ nnreal.sub_pos.2 hr] },
{ rw [ennreal.sub_eq_zero_of_le hr, ennreal.inv_zero, ennreal.tsum_eq_supr_nat, supr_eq_top],
refine λ a ha, (ennreal.exists_nat_gt (lt_top_iff_ne_top.1 ha)).imp
(λ n hn, lt_of_lt_of_le hn _),
have : ∀ k:ℕ, 1 ≤ r^k, by simpa using canonically_ordered_semiring.pow_le_pow_of_le_left hr,
calc (n:ennreal) = (range n).sum (λ _, 1) : by rw [sum_const, add_monoid.smul_one, card_range]
... ≤ (range n).sum (pow r) : sum_le_sum (λ k _, this k) }
end
/-- For any positive `ε`, define on an encodable type a positive sequence with sum less than `ε` -/
def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε)
(ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, has_sum ε' c ∧ c ≤ ε} :=
begin
let f := λ n, (ε / 2) / 2 ^ n,
have hf : has_sum f ε := has_sum_geometric_two' _,
have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos two_pos _),
refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩,
rcases summable_comp_of_summable_of_injective f (summable_spec hf) (@encodable.encode_injective ι _)
with ⟨c, hg⟩,
refine ⟨c, hg, has_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩,
{ assume i _, exact le_of_lt (f0 _) },
{ assume n, exact le_refl _ }
end
section edist_le_geometric
variables [emetric_space α] (r C : ennreal) (hr : r < 1) (hC : C ≠ ⊤) {f : ℕ → α}
(hu : ∀n, edist (f n) (f (n+1)) ≤ C * r^n)
include hr hC hu
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, `C ≠ ∞`, `r < 1`,
then `f` is a Cauchy sequence.-/
lemma cauchy_seq_of_edist_le_geometric : cauchy_seq f :=
begin
refine cauchy_seq_of_edist_le_of_tsum_ne_top _ hu _,
rw [ennreal.mul_tsum, ennreal.tsum_geometric],
refine ennreal.mul_ne_top hC (ennreal.inv_ne_top.2 _),
exact ne_of_gt (ennreal.zero_lt_sub_iff_lt.2 hr)
end
omit hr hC
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from
`f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/
lemma edist_le_of_edist_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
edist (f n) a ≤ (C * r^n) / (1 - r) :=
begin
convert edist_le_tsum_of_edist_le_of_tendsto _ hu ha _,
simp only [pow_add, ennreal.mul_tsum, ennreal.tsum_geometric, ennreal.div_def, mul_assoc]
end
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from
`f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/
lemma edist_le_of_edist_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
edist (f 0) a ≤ C / (1 - r) :=
by simpa only [pow_zero, mul_one] using edist_le_of_edist_le_geometric_of_tendsto r C hu ha 0
end edist_le_geometric
section edist_le_geometric_two
variables [emetric_space α] (C : ennreal) (hC : C ≠ ⊤) {f : ℕ → α}
(hu : ∀n, edist (f n) (f (n+1)) ≤ C / 2^n) {a : α} (ha : tendsto f at_top (𝓝 a))
include hC hu
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then `f` is a Cauchy sequence.-/
lemma cauchy_seq_of_edist_le_geometric_two : cauchy_seq f :=
begin
simp only [ennreal.div_def, ennreal.inv_pow'] at hu,
refine cauchy_seq_of_edist_le_geometric 2⁻¹ C _ hC hu,
simp [ennreal.one_lt_two]
end
omit hC
include ha
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from
`f n` to the limit of `f` is bounded above by `2 * C * 2^-n`. -/
lemma edist_le_of_edist_le_geometric_two_of_tendsto (n : ℕ) :
edist (f n) a ≤ 2 * C / 2^n :=
begin
simp only [ennreal.div_def, ennreal.inv_pow'] at hu,
rw [ennreal.div_def, mul_assoc, mul_comm, ennreal.inv_pow'],
convert edist_le_of_edist_le_geometric_of_tendsto 2⁻¹ C hu ha n,
rw [ennreal.one_sub_inv_two, ennreal.inv_inv]
end
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from
`f 0` to the limit of `f` is bounded above by `2 * C`. -/
lemma edist_le_of_edist_le_geometric_two_of_tendsto₀: edist (f 0) a ≤ 2 * C :=
by simpa only [pow_zero, ennreal.div_def, ennreal.inv_one, mul_one]
using edist_le_of_edist_le_geometric_two_of_tendsto C hu ha 0
end edist_le_geometric_two
section le_geometric
variables [metric_space α] {r C : ℝ} (hr : r < 1) {f : ℕ → α}
(hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n)
include hr hu
lemma aux_has_sum_of_le_geometric : has_sum (λ n : ℕ, C * r^n) (C / (1 - r)) :=
begin
have h0 : 0 ≤ C,
by simpa using le_trans dist_nonneg (hu 0),
rcases eq_or_lt_of_le h0 with rfl | Cpos,
{ simp [has_sum_zero] },
{ have rnonneg: r ≥ 0, from nonneg_of_mul_nonneg_left
(by simpa only [pow_one] using le_trans dist_nonneg (hu 1)) Cpos,
refine has_sum_mul_left C _,
by simpa using has_sum_geometric rnonneg hr }
end
variables (r C)
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then `f` is a Cauchy sequence.
Note that this lemma does not assume `0 ≤ C` or `0 ≤ r`. -/
lemma cauchy_seq_of_le_geometric : cauchy_seq f :=
cauchy_seq_of_dist_le_of_summable _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from
`f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/
lemma dist_le_of_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ C / (1 - r) :=
(tsum_eq_has_sum $ aux_has_sum_of_le_geometric hr hu) ▸
dist_le_tsum_of_dist_le_of_tendsto₀ _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ ha
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from
`f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/
lemma dist_le_of_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
dist (f n) a ≤ (C * r^n) / (1 - r) :=
begin
have := aux_has_sum_of_le_geometric hr hu,
convert dist_le_tsum_of_dist_le_of_tendsto _ hu ⟨_, this⟩ ha n,
simp only [pow_add, mul_left_comm C, mul_div_right_comm],
rw [mul_comm],
exact (eq.symm $ tsum_eq_has_sum $ has_sum_mul_left _ this)
end
omit hr hu
variable (hu₂ : ∀ n, dist (f n) (f (n+1)) ≤ (C / 2) / 2^n)
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then `f` is a Cauchy sequence. -/
lemma cauchy_seq_of_le_geometric_two : cauchy_seq f :=
cauchy_seq_of_dist_le_of_summable _ hu₂ $ ⟨_, has_sum_geometric_two' C⟩
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from
`f 0` to the limit of `f` is bounded above by `C`. -/
lemma dist_le_of_le_geometric_two_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ C :=
(tsum_geometric_two' C) ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu₂ (summable_geometric_two' C) ha
include hu₂
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from
`f n` to the limit of `f` is bounded above by `C / 2^n`. -/
lemma dist_le_of_le_geometric_two_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
dist (f n) a ≤ C / 2^n :=
begin
convert dist_le_tsum_of_dist_le_of_tendsto _ hu₂ (summable_geometric_two' C) ha n,
simp only [add_comm n, pow_add, (div_div_eq_div_mul _ _ _).symm],
symmetry,
exact tsum_eq_has_sum (has_sum_mul_right _ $ has_sum_geometric_two' C)
end
end le_geometric
namespace nnreal
theorem exists_pos_sum_of_encodable {ε : nnreal} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ ∃c, has_sum ε' c ∧ c < ε :=
let ⟨a, a0, aε⟩ := dense hε in
let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in
⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt.2 $ hε' i,
⟨c, has_sum_le (assume i, le_of_lt $ hε' i) has_sum_zero hc ⟩, nnreal.has_sum_coe.1 hc,
lt_of_le_of_lt (nnreal.coe_le.1 hcε) aε ⟩
end nnreal
namespace ennreal
theorem exists_pos_sum_of_encodable {ε : ennreal} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ (∑ i, (ε' i : ennreal)) < ε :=
begin
rcases dense hε with ⟨r, h0r, hrε⟩,
rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩,
rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩,
exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩
end
end ennreal
|
2f5bdaec7bcc30ac83c937cf6d46eb9499983f8f
|
9dc8cecdf3c4634764a18254e94d43da07142918
|
/src/data/rat/floor.lean
|
4b76ae26228f2ff9dfea4730e42fe625fbfa69bd
|
[
"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,652
|
lean
|
/-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Kevin Kappelmann
-/
import algebra.order.floor
import tactic.field_simp
/-!
# Floor Function for Rational Numbers
## Summary
We define the `floor` function and the `floor_ring` instance on `ℚ`. Some technical lemmas relating
`floor` to integer division and modulo arithmetic are derived as well as some simple inequalities.
## Tags
rat, rationals, ℚ, floor
-/
open int
namespace rat
variables {α : Type*} [linear_ordered_field α] [floor_ring α]
/-- `floor q` is the largest integer `z` such that `z ≤ q` -/
protected def floor : ℚ → ℤ
| ⟨n, d, h, c⟩ := n / d
protected theorem le_floor {z : ℤ} : ∀ {r : ℚ}, z ≤ rat.floor r ↔ (z : ℚ) ≤ r
| ⟨n, d, h, c⟩ := begin
simp [rat.floor],
rw [num_denom'],
have h' := int.coe_nat_lt.2 h,
conv { to_rhs,
rw [coe_int_eq_mk, rat.le_def zero_lt_one h', mul_one] },
exact int.le_div_iff_mul_le h'
end
instance : floor_ring ℚ :=
floor_ring.of_floor ℚ rat.floor $ λ a z, rat.le_floor.symm
protected lemma floor_def {q : ℚ} : ⌊q⌋ = q.num / q.denom := by { cases q, refl }
lemma floor_int_div_nat_eq_div {n : ℤ} {d : ℕ} : ⌊(↑n : ℚ) / (↑d : ℚ)⌋ = n / (↑d : ℤ) :=
begin
rw [rat.floor_def],
obtain rfl | hd := @eq_zero_or_pos _ _ d,
{ simp },
set q := (n : ℚ) / d with q_eq,
obtain ⟨c, n_eq_c_mul_num, d_eq_c_mul_denom⟩ : ∃ c, n = c * q.num ∧ (d : ℤ) = c * q.denom, by
{ rw q_eq,
exact_mod_cast @rat.exists_eq_mul_div_num_and_eq_mul_div_denom n d (by exact_mod_cast hd.ne') },
rw [n_eq_c_mul_num, d_eq_c_mul_denom],
refine (int.mul_div_mul_of_pos _ _ $ pos_of_mul_pos_left _ $ int.coe_nat_nonneg q.denom).symm,
rwa [←d_eq_c_mul_denom, int.coe_nat_pos],
end
@[simp, norm_cast] lemma floor_cast (x : ℚ) : ⌊(x : α)⌋ = ⌊x⌋ :=
floor_eq_iff.2 (by exact_mod_cast floor_eq_iff.1 (eq.refl ⌊x⌋))
@[simp, norm_cast] lemma ceil_cast (x : ℚ) : ⌈(x : α)⌉ = ⌈x⌉ :=
by rw [←neg_inj, ←floor_neg, ←floor_neg, ← rat.cast_neg, rat.floor_cast]
@[simp, norm_cast] lemma round_cast (x : ℚ) : round (x : α) = round x :=
have ((x + 1 / 2 : ℚ) : α) = x + 1 / 2, by simp,
by rw [round_eq, round_eq, ← this, floor_cast]
@[simp, norm_cast] lemma cast_fract (x : ℚ) : (↑(fract x) : α) = fract x :=
by simp only [fract, cast_sub, cast_coe_int, floor_cast]
end rat
lemma int.mod_nat_eq_sub_mul_floor_rat_div {n : ℤ} {d : ℕ} : n % d = n - d * ⌊(n : ℚ) / d⌋ :=
by rw [(eq_sub_of_add_eq $ int.mod_add_div n d), rat.floor_int_div_nat_eq_div]
lemma nat.coprime_sub_mul_floor_rat_div_of_coprime {n d : ℕ} (n_coprime_d : n.coprime d) :
((n : ℤ) - d * ⌊(n : ℚ)/ d⌋).nat_abs.coprime d :=
begin
have : (n : ℤ) % d = n - d * ⌊(n : ℚ)/ d⌋, from int.mod_nat_eq_sub_mul_floor_rat_div,
rw ←this,
have : d.coprime n, from n_coprime_d.symm,
rwa [nat.coprime, nat.gcd_rec] at this
end
namespace rat
lemma num_lt_succ_floor_mul_denom (q : ℚ) : q.num < (⌊q⌋ + 1) * q.denom :=
begin
suffices : (q.num : ℚ) < (⌊q⌋ + 1) * q.denom, by exact_mod_cast this,
suffices : (q.num : ℚ) < (q - fract q + 1) * q.denom, by
{ have : (⌊q⌋ : ℚ) = q - fract q, from (eq_sub_of_add_eq $ floor_add_fract q),
rwa this },
suffices : (q.num : ℚ) < q.num + (1 - fract q) * q.denom, by
{ have : (q - fract q + 1) * q.denom = q.num + (1 - fract q) * q.denom, calc
(q - fract q + 1) * q.denom = (q + (1 - fract q)) * q.denom : by ring
... = q * q.denom + (1 - fract q) * q.denom : by rw add_mul
... = q.num + (1 - fract q) * q.denom : by simp,
rwa this },
suffices : 0 < (1 - fract q) * q.denom, by { rw ←sub_lt_iff_lt_add', simpa },
have : 0 < 1 - fract q, by
{ have : fract q < 1, from fract_lt_one q,
have : 0 + fract q < 1, by simp [this],
rwa lt_sub_iff_add_lt },
exact mul_pos this (by exact_mod_cast q.pos)
end
lemma fract_inv_num_lt_num_of_pos {q : ℚ} (q_pos : 0 < q): (fract q⁻¹).num < q.num :=
begin
-- we know that the numerator must be positive
have q_num_pos : 0 < q.num, from rat.num_pos_iff_pos.elim_right q_pos,
-- we will work with the absolute value of the numerator, which is equal to the numerator
have q_num_abs_eq_q_num : (q.num.nat_abs : ℤ) = q.num, from
(int.nat_abs_of_nonneg q_num_pos.le),
set q_inv := (q.denom : ℚ) / q.num with q_inv_def,
have q_inv_eq : q⁻¹ = q_inv, from rat.inv_def',
suffices : (q_inv - ⌊q_inv⌋).num < q.num, by rwa q_inv_eq,
suffices : ((q.denom - q.num * ⌊q_inv⌋ : ℚ) / q.num).num < q.num, by
field_simp [this, (ne_of_gt q_num_pos)],
suffices : (q.denom : ℤ) - q.num * ⌊q_inv⌋ < q.num, by
{ -- use that `q.num` and `q.denom` are coprime to show that the numerator stays unreduced
have : ((q.denom - q.num * ⌊q_inv⌋ : ℚ) / q.num).num = q.denom - q.num * ⌊q_inv⌋, by
{ suffices : ((q.denom : ℤ) - q.num * ⌊q_inv⌋).nat_abs.coprime q.num.nat_abs, by
exact_mod_cast (rat.num_div_eq_of_coprime q_num_pos this),
have : (q.num.nat_abs : ℚ) = (q.num : ℚ), by exact_mod_cast q_num_abs_eq_q_num,
have tmp := nat.coprime_sub_mul_floor_rat_div_of_coprime q.cop.symm,
simpa only [this, q_num_abs_eq_q_num] using tmp },
rwa this },
-- to show the claim, start with the following inequality
have q_inv_num_denom_ineq : q⁻¹.num - ⌊q⁻¹⌋ * q⁻¹.denom < q⁻¹.denom, by
{ have : q⁻¹.num < (⌊q⁻¹⌋ + 1) * q⁻¹.denom, from rat.num_lt_succ_floor_mul_denom q⁻¹,
have : q⁻¹.num < ⌊q⁻¹⌋ * q⁻¹.denom + q⁻¹.denom, by rwa [right_distrib, one_mul] at this,
rwa [←sub_lt_iff_lt_add'] at this },
-- use that `q.num` and `q.denom` are coprime to show that q_inv is the unreduced reciprocal
-- of `q`
have : q_inv.num = q.denom ∧ q_inv.denom = q.num.nat_abs, by
{ have coprime_q_denom_q_num : q.denom.coprime q.num.nat_abs, from q.cop.symm,
have : int.nat_abs q.denom = q.denom, by simp,
rw ←this at coprime_q_denom_q_num,
rw q_inv_def,
split,
{ exact_mod_cast (rat.num_div_eq_of_coprime q_num_pos coprime_q_denom_q_num) },
{ suffices : (((q.denom : ℚ) / q.num).denom : ℤ) = q.num.nat_abs, by exact_mod_cast this,
rw q_num_abs_eq_q_num,
exact_mod_cast (rat.denom_div_eq_of_coprime q_num_pos coprime_q_denom_q_num) } },
rwa [q_inv_eq, this.left, this.right, q_num_abs_eq_q_num, mul_comm] at q_inv_num_denom_ineq
end
end rat
|
8d2ecafbe14f979c6393ab713489dd59f9903b87
|
cf39355caa609c0f33405126beee2739aa3cb77e
|
/tests/lean/type_context.lean
|
b968e99dfcffb6994408c5c9a8793d2a40a2699b
|
[
"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
| 8,700
|
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 `int.eq_neg_of_eq_neg,
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
)
#eval to_bool $ local_context.empty = local_context.empty
|
5e5ef6229f12a2f96402168f3edc2c200f0ae837
|
4efff1f47634ff19e2f786deadd394270a59ecd2
|
/src/category_theory/functor.lean
|
5a20e931bea8846c368a66a6f95307c30ea6a399
|
[
"Apache-2.0"
] |
permissive
|
agjftucker/mathlib
|
d634cd0d5256b6325e3c55bb7fb2403548371707
|
87fe50de17b00af533f72a102d0adefe4a2285e8
|
refs/heads/master
| 1,625,378,131,941
| 1,599,166,526,000
| 1,599,166,526,000
| 160,748,509
| 0
| 0
|
Apache-2.0
| 1,544,141,789,000
| 1,544,141,789,000
| null |
UTF-8
|
Lean
| false
| false
| 3,180
|
lean
|
/-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baumann, Stephen Morgan, Scott Morrison
Defines a functor between categories.
(As it is a 'bundled' object rather than the `is_functorial` typeclass parametrised
by the underlying function on objects, the name is capitalised.)
Introduces notations
`C ⥤ D` for the type of all functors from `C` to `D`.
(I would like a better arrow here, unfortunately ⇒ (`\functor`) is taken by core.)
-/
import tactic.reassoc_axiom
namespace category_theory
universes v v₁ v₂ v₃ u u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation
/--
`functor C D` represents a functor between categories `C` and `D`.
To apply a functor `F` to an object use `F.obj X`, and to a morphism use `F.map f`.
The axiom `map_id` expresses preservation of identities, and
`map_comp` expresses functoriality.
-/
structure functor (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] :
Type (max v₁ v₂ u₁ u₂) :=
(obj [] : C → D)
(map : Π {X Y : C}, (X ⟶ Y) → ((obj X) ⟶ (obj Y)))
(map_id' : ∀ (X : C), map (𝟙 X) = 𝟙 (obj X) . obviously)
(map_comp' : ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), map (f ≫ g) = (map f) ≫ (map g) . obviously)
-- A functor is basically a function, so give ⥤ a similar precedence to → (25).
-- For example, `C × D ⥤ E` should parse as `(C × D) ⥤ E` not `C × (D ⥤ E)`.
infixr ` ⥤ `:26 := functor -- type as \func --
restate_axiom functor.map_id'
attribute [simp] functor.map_id
restate_axiom functor.map_comp'
attribute [reassoc, simp] functor.map_comp
namespace functor
section
variables (C : Type u₁) [category.{v₁} C]
/-- `𝟭 C` is the identity functor on a category `C`. -/
protected def id : C ⥤ C :=
{ obj := λ X, X,
map := λ _ _ f, f }
notation `𝟭` := functor.id -- Type this as `\sb1`
instance : inhabited (C ⥤ C) := ⟨functor.id C⟩
variable {C}
@[simp] lemma id_obj (X : C) : (𝟭 C).obj X = X := rfl
@[simp] lemma id_map {X Y : C} (f : X ⟶ Y) : (𝟭 C).map f = f := rfl
end
section
variables {C : Type u₁} [category.{v₁} C]
{D : Type u₂} [category.{v₂} D]
{E : Type u₃} [category.{v₃} E]
/--
`F ⋙ G` is the composition of a functor `F` and a functor `G` (`F` first, then `G`).
-/
def comp (F : C ⥤ D) (G : D ⥤ E) : C ⥤ E :=
{ obj := λ X, G.obj (F.obj X),
map := λ _ _ f, G.map (F.map f) }
infixr ` ⋙ `:80 := comp
@[simp] lemma comp_obj (F : C ⥤ D) (G : D ⥤ E) (X : C) : (F ⋙ G).obj X = G.obj (F.obj X) := rfl
@[simp] lemma comp_map (F : C ⥤ D) (G : D ⥤ E) {X Y : C} (f : X ⟶ Y) :
(F ⋙ G).map f = G.map (F.map f) := rfl
-- These are not simp lemmas because rewriting along equalities between functors
-- is not necessarily a good idea.
-- Natural isomorphisms are also provided in `whiskering.lean`.
protected lemma comp_id (F : C ⥤ D) : F ⋙ (𝟭 D) = F := by cases F; refl
protected lemma id_comp (F : C ⥤ D) : (𝟭 C) ⋙ F = F := by cases F; refl
end
end functor
end category_theory
|
56b360705797948ce1abc2776d49c16171441b99
|
74addaa0e41490cbaf2abd313a764c96df57b05d
|
/Mathlib/analysis/calculus/specific_functions_auto.lean
|
feadf0dac0dd79152360ba0d8e463b2394a112b7
|
[] |
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
| 4,495
|
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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.analysis.calculus.extend_deriv
import Mathlib.analysis.calculus.iterated_deriv
import Mathlib.analysis.special_functions.exp_log
import Mathlib.topology.algebra.polynomial
import Mathlib.PostPort
namespace Mathlib
/-!
# Smoothness of specific functions
The real function `exp_neg_inv_glue` given by `x ↦ exp (-1/x)` for `x > 0` and `0`
for `x ≤ 0` is a basic building block to construct smooth partitions of unity. We prove that it
is `C^∞` in `exp_neg_inv_glue.smooth`.
-/
/-- `exp_neg_inv_glue` is the real function given by `x ↦ exp (-1/x)` for `x > 0` and `0`
for `x ≤ 0`. is a basic building block to construct smooth partitions of unity. Its main property
is that it vanishes for `x ≤ 0`, it is positive for `x > 0`, and the junction between the two
behaviors is flat enough to retain smoothness. The fact that this function is `C^∞` is proved in
`exp_neg_inv_glue.smooth`. -/
def exp_neg_inv_glue (x : ℝ) : ℝ := ite (x ≤ 0) 0 (real.exp (-(x⁻¹)))
namespace exp_neg_inv_glue
/-- Our goal is to prove that `exp_neg_inv_glue` is `C^∞`. For this, we compute its successive
derivatives for `x > 0`. The `n`-th derivative is of the form `P_aux n (x) exp(-1/x) / x^(2 n)`,
where `P_aux n` is computed inductively. -/
def P_aux : ℕ → polynomial ℝ := sorry
/-- Formula for the `n`-th derivative of `exp_neg_inv_glue`, as an auxiliary function `f_aux`. -/
def f_aux (n : ℕ) (x : ℝ) : ℝ :=
ite (x ≤ 0) 0 (polynomial.eval x (P_aux n) * real.exp (-(x⁻¹)) / x ^ (bit0 1 * n))
/-- The `0`-th auxiliary function `f_aux 0` coincides with `exp_neg_inv_glue`, by definition. -/
theorem f_aux_zero_eq : f_aux 0 = exp_neg_inv_glue := sorry
/-- For positive values, the derivative of the `n`-th auxiliary function `f_aux n`
(given in this statement in unfolded form) is the `n+1`-th auxiliary function, since
the polynomial `P_aux (n+1)` was chosen precisely to ensure this. -/
theorem f_aux_deriv (n : ℕ) (x : ℝ) (hx : x ≠ 0) :
has_deriv_at (fun (x : ℝ) => polynomial.eval x (P_aux n) * real.exp (-(x⁻¹)) / x ^ (bit0 1 * n))
(polynomial.eval x (P_aux (n + 1)) * real.exp (-(x⁻¹)) / x ^ (bit0 1 * (n + 1))) x :=
sorry
/-- For positive values, the derivative of the `n`-th auxiliary function `f_aux n`
is the `n+1`-th auxiliary function. -/
theorem f_aux_deriv_pos (n : ℕ) (x : ℝ) (hx : 0 < x) :
has_deriv_at (f_aux n)
(polynomial.eval x (P_aux (n + 1)) * real.exp (-(x⁻¹)) / x ^ (bit0 1 * (n + 1))) x :=
sorry
/-- To get differentiability at `0` of the auxiliary functions, we need to know that their limit
is `0`, to be able to apply general differentiability extension theorems. This limit is checked in
this lemma. -/
theorem f_aux_limit (n : ℕ) :
filter.tendsto
(fun (x : ℝ) => polynomial.eval x (P_aux n) * real.exp (-(x⁻¹)) / x ^ (bit0 1 * n))
(nhds_within 0 (set.Ioi 0)) (nhds 0) :=
sorry
/-- Deduce from the limiting behavior at `0` of its derivative and general differentiability
extension theorems that the auxiliary function `f_aux n` is differentiable at `0`,
with derivative `0`. -/
theorem f_aux_deriv_zero (n : ℕ) : has_deriv_at (f_aux n) 0 0 := sorry
/-- At every point, the auxiliary function `f_aux n` has a derivative which is
equal to `f_aux (n+1)`. -/
theorem f_aux_has_deriv_at (n : ℕ) (x : ℝ) : has_deriv_at (f_aux n) (f_aux (n + 1) x) x := sorry
/-- The successive derivatives of the auxiliary function `f_aux 0` are the
functions `f_aux n`, by induction. -/
theorem f_aux_iterated_deriv (n : ℕ) : iterated_deriv n (f_aux 0) = f_aux n := sorry
/-- The function `exp_neg_inv_glue` is smooth. -/
theorem smooth : times_cont_diff ℝ ⊤ exp_neg_inv_glue := sorry
/-- The function `exp_neg_inv_glue` vanishes on `(-∞, 0]`. -/
theorem zero_of_nonpos {x : ℝ} (hx : x ≤ 0) : exp_neg_inv_glue x = 0 := sorry
/-- The function `exp_neg_inv_glue` is positive on `(0, +∞)`. -/
theorem pos_of_pos {x : ℝ} (hx : 0 < x) : 0 < exp_neg_inv_glue x := sorry
/-- The function exp_neg_inv_glue` is nonnegative. -/
theorem nonneg (x : ℝ) : 0 ≤ exp_neg_inv_glue x :=
or.dcases_on (le_or_gt x 0) (fun (h : x ≤ 0) => ge_of_eq (zero_of_nonpos h))
fun (h : x > 0) => le_of_lt (pos_of_pos h)
end Mathlib
|
926ad7922cee9c376e88f3d4ad1f33abf72da752
|
c777c32c8e484e195053731103c5e52af26a25d1
|
/src/order/bounds/basic.lean
|
6cfd3c71db1d33bc22dac512b61a59ab87ea3a6b
|
[
"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
| 50,599
|
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, Yury Kudryashov
-/
import data.set.intervals.basic
import data.set.n_ary
/-!
# Upper / lower bounds
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define:
* `upper_bounds`, `lower_bounds` : the set of upper bounds (resp., lower bounds) of a set;
* `bdd_above s`, `bdd_below s` : the set `s` is bounded above (resp., below), i.e., the set of upper
(resp., lower) bounds of `s` is nonempty;
* `is_least s a`, `is_greatest s a` : `a` is a least (resp., greatest) element of `s`;
for a partial order, it is unique if exists;
* `is_lub s a`, `is_glb s a` : `a` is a least upper bound (resp., a greatest lower bound)
of `s`; for a partial order, it is unique if exists.
We also prove various lemmas about monotonicity, behaviour under `∪`, `∩`, `insert`, and provide
formulas for `∅`, `univ`, and intervals.
-/
open function set order_dual (to_dual of_dual)
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}
section
variables [preorder α] [preorder β] {s t : set α} {a b : α}
/-!
### Definitions
-/
/-- The set of upper bounds of a set. -/
def upper_bounds (s : set α) : set α := { x | ∀ ⦃a⦄, a ∈ s → a ≤ x }
/-- The set of lower bounds of a set. -/
def lower_bounds (s : set α) : set α := { x | ∀ ⦃a⦄, a ∈ s → x ≤ a }
/-- A set is bounded above if there exists an upper bound. -/
def bdd_above (s : set α) := (upper_bounds s).nonempty
/-- A set is bounded below if there exists a lower bound. -/
def bdd_below (s : set α) := (lower_bounds s).nonempty
/-- `a` is a least element of a set `s`; for a partial order, it is unique if exists. -/
def is_least (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ lower_bounds s
/-- `a` is a greatest element of a set `s`; for a partial order, it is unique if exists -/
def is_greatest (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ upper_bounds s
/-- `a` is a least upper bound of a set `s`; for a partial order, it is unique if exists. -/
def is_lub (s : set α) : α → Prop := is_least (upper_bounds s)
/-- `a` is a greatest lower bound of a set `s`; for a partial order, it is unique if exists. -/
def is_glb (s : set α) : α → Prop := is_greatest (lower_bounds s)
lemma mem_upper_bounds : a ∈ upper_bounds s ↔ ∀ x ∈ s, x ≤ a := iff.rfl
lemma mem_lower_bounds : a ∈ lower_bounds s ↔ ∀ x ∈ s, a ≤ x := iff.rfl
lemma bdd_above_def : bdd_above s ↔ ∃ x, ∀ y ∈ s, y ≤ x := iff.rfl
lemma bdd_below_def : bdd_below s ↔ ∃ x, ∀ y ∈ s, x ≤ y := iff.rfl
lemma bot_mem_lower_bounds [order_bot α] (s : set α) : ⊥ ∈ lower_bounds s := λ _ _, bot_le
lemma top_mem_upper_bounds [order_top α] (s : set α) : ⊤ ∈ upper_bounds s := λ _ _, le_top
@[simp] lemma is_least_bot_iff [order_bot α] : is_least s ⊥ ↔ ⊥ ∈ s :=
and_iff_left $ bot_mem_lower_bounds _
@[simp] lemma is_greatest_top_iff [order_top α] : is_greatest s ⊤ ↔ ⊤ ∈ s :=
and_iff_left $ top_mem_upper_bounds _
/-- A set `s` is not bounded above if and only if for each `x` there exists `y ∈ s` such that `x`
is not greater than or equal to `y`. This version only assumes `preorder` structure and uses
`¬(y ≤ x)`. A version for linear orders is called `not_bdd_above_iff`. -/
lemma not_bdd_above_iff' : ¬bdd_above s ↔ ∀ x, ∃ y ∈ s, ¬(y ≤ x) :=
by simp [bdd_above, upper_bounds, set.nonempty]
/-- A set `s` is not bounded below if and only if for each `x` there exists `y ∈ s` such that `x`
is not less than or equal to `y`. This version only assumes `preorder` structure and uses
`¬(x ≤ y)`. A version for linear orders is called `not_bdd_below_iff`. -/
lemma not_bdd_below_iff' : ¬bdd_below s ↔ ∀ x, ∃ y ∈ s, ¬ x ≤ y := @not_bdd_above_iff' αᵒᵈ _ _
/-- A set `s` is not bounded above if and only if for each `x` there exists `y ∈ s` that is greater
than `x`. A version for preorders is called `not_bdd_above_iff'`. -/
lemma not_bdd_above_iff {α : Type*} [linear_order α] {s : set α} :
¬bdd_above s ↔ ∀ x, ∃ y ∈ s, x < y :=
by simp only [not_bdd_above_iff', not_le]
/-- A set `s` is not bounded below if and only if for each `x` there exists `y ∈ s` that is less
than `x`. A version for preorders is called `not_bdd_below_iff'`. -/
lemma not_bdd_below_iff {α : Type*} [linear_order α] {s : set α} :
¬bdd_below s ↔ ∀ x, ∃ y ∈ s, y < x :=
@not_bdd_above_iff αᵒᵈ _ _
lemma bdd_above.dual (h : bdd_above s) : bdd_below (of_dual ⁻¹' s) := h
lemma bdd_below.dual (h : bdd_below s) : bdd_above (of_dual ⁻¹' s) := h
lemma is_least.dual (h : is_least s a) : is_greatest (of_dual ⁻¹' s) (to_dual a) := h
lemma is_greatest.dual (h : is_greatest s a) : is_least (of_dual ⁻¹' s) (to_dual a) := h
lemma is_lub.dual (h : is_lub s a) : is_glb (of_dual ⁻¹' s) (to_dual a) := h
lemma is_glb.dual (h : is_glb s a) : is_lub (of_dual ⁻¹' s) (to_dual a) := h
/-- If `a` is the least element of a set `s`, then subtype `s` is an order with bottom element. -/
@[reducible] def is_least.order_bot (h : is_least s a) : order_bot s :=
{ bot := ⟨a, h.1⟩,
bot_le := subtype.forall.2 h.2 }
/-- If `a` is the greatest element of a set `s`, then subtype `s` is an order with top element. -/
@[reducible] def is_greatest.order_top (h : is_greatest s a) : order_top s :=
{ top := ⟨a, h.1⟩,
le_top := subtype.forall.2 h.2 }
/-!
### Monotonicity
-/
lemma upper_bounds_mono_set ⦃s t : set α⦄ (hst : s ⊆ t) :
upper_bounds t ⊆ upper_bounds s :=
λ b hb x h, hb $ hst h
lemma lower_bounds_mono_set ⦃s t : set α⦄ (hst : s ⊆ t) :
lower_bounds t ⊆ lower_bounds s :=
λ b hb x h, hb $ hst h
lemma upper_bounds_mono_mem ⦃a b⦄ (hab : a ≤ b) : a ∈ upper_bounds s → b ∈ upper_bounds s :=
λ ha x h, le_trans (ha h) hab
lemma lower_bounds_mono_mem ⦃a b⦄ (hab : a ≤ b) : b ∈ lower_bounds s → a ∈ lower_bounds s :=
λ hb x h, le_trans hab (hb h)
lemma upper_bounds_mono ⦃s t : set α⦄ (hst : s ⊆ t) ⦃a b⦄ (hab : a ≤ b) :
a ∈ upper_bounds t → b ∈ upper_bounds s :=
λ ha, upper_bounds_mono_set hst $ upper_bounds_mono_mem hab ha
lemma lower_bounds_mono ⦃s t : set α⦄ (hst : s ⊆ t) ⦃a b⦄ (hab : a ≤ b) :
b ∈ lower_bounds t → a ∈ lower_bounds s :=
λ hb, lower_bounds_mono_set hst $ lower_bounds_mono_mem hab hb
/-- If `s ⊆ t` and `t` is bounded above, then so is `s`. -/
lemma bdd_above.mono ⦃s t : set α⦄ (h : s ⊆ t) : bdd_above t → bdd_above s :=
nonempty.mono $ upper_bounds_mono_set h
/-- If `s ⊆ t` and `t` is bounded below, then so is `s`. -/
lemma bdd_below.mono ⦃s t : set α⦄ (h : s ⊆ t) : bdd_below t → bdd_below s :=
nonempty.mono $ lower_bounds_mono_set h
/-- If `a` is a least upper bound for sets `s` and `p`, then it is a least upper bound for any
set `t`, `s ⊆ t ⊆ p`. -/
lemma is_lub.of_subset_of_superset {s t p : set α} (hs : is_lub s a) (hp : is_lub p a)
(hst : s ⊆ t) (htp : t ⊆ p) : is_lub t a :=
⟨upper_bounds_mono_set htp hp.1, lower_bounds_mono_set (upper_bounds_mono_set hst) hs.2⟩
/-- If `a` is a greatest lower bound for sets `s` and `p`, then it is a greater lower bound for any
set `t`, `s ⊆ t ⊆ p`. -/
lemma is_glb.of_subset_of_superset {s t p : set α} (hs : is_glb s a) (hp : is_glb p a)
(hst : s ⊆ t) (htp : t ⊆ p) : is_glb t a :=
hs.dual.of_subset_of_superset hp hst htp
lemma is_least.mono (ha : is_least s a) (hb : is_least t b) (hst : s ⊆ t) : b ≤ a :=
hb.2 (hst ha.1)
lemma is_greatest.mono (ha : is_greatest s a) (hb : is_greatest t b) (hst : s ⊆ t) : a ≤ b :=
hb.2 (hst ha.1)
lemma is_lub.mono (ha : is_lub s a) (hb : is_lub t b) (hst : s ⊆ t) : a ≤ b :=
hb.mono ha $ upper_bounds_mono_set hst
lemma is_glb.mono (ha : is_glb s a) (hb : is_glb t b) (hst : s ⊆ t) : b ≤ a :=
hb.mono ha $ lower_bounds_mono_set hst
lemma subset_lower_bounds_upper_bounds (s : set α) : s ⊆ lower_bounds (upper_bounds s) :=
λ x hx y hy, hy hx
lemma subset_upper_bounds_lower_bounds (s : set α) : s ⊆ upper_bounds (lower_bounds s) :=
λ x hx y hy, hy hx
lemma set.nonempty.bdd_above_lower_bounds (hs : s.nonempty) : bdd_above (lower_bounds s) :=
hs.mono (subset_upper_bounds_lower_bounds s)
lemma set.nonempty.bdd_below_upper_bounds (hs : s.nonempty) : bdd_below (upper_bounds s) :=
hs.mono (subset_lower_bounds_upper_bounds s)
/-!
### Conversions
-/
lemma is_least.is_glb (h : is_least s a) : is_glb s a := ⟨h.2, λ b hb, hb h.1⟩
lemma is_greatest.is_lub (h : is_greatest s a) : is_lub s a := ⟨h.2, λ b hb, hb h.1⟩
lemma is_lub.upper_bounds_eq (h : is_lub s a) : upper_bounds s = Ici a :=
set.ext $ λ b, ⟨λ hb, h.2 hb, λ hb, upper_bounds_mono_mem hb h.1⟩
lemma is_glb.lower_bounds_eq (h : is_glb s a) : lower_bounds s = Iic a := h.dual.upper_bounds_eq
lemma is_least.lower_bounds_eq (h : is_least s a) : lower_bounds s = Iic a :=
h.is_glb.lower_bounds_eq
lemma is_greatest.upper_bounds_eq (h : is_greatest s a) : upper_bounds s = Ici a :=
h.is_lub.upper_bounds_eq
lemma is_lub_le_iff (h : is_lub s a) : a ≤ b ↔ b ∈ upper_bounds s :=
by { rw h.upper_bounds_eq, refl }
lemma le_is_glb_iff (h : is_glb s a) : b ≤ a ↔ b ∈ lower_bounds s :=
by { rw h.lower_bounds_eq, refl }
lemma is_lub_iff_le_iff : is_lub s a ↔ ∀ b, a ≤ b ↔ b ∈ upper_bounds s :=
⟨λ h b, is_lub_le_iff h, λ H, ⟨(H _).1 le_rfl, λ b hb, (H b).2 hb⟩⟩
lemma is_glb_iff_le_iff : is_glb s a ↔ ∀ b, b ≤ a ↔ b ∈ lower_bounds s :=
@is_lub_iff_le_iff αᵒᵈ _ _ _
/-- If `s` has a least upper bound, then it is bounded above. -/
lemma is_lub.bdd_above (h : is_lub s a) : bdd_above s := ⟨a, h.1⟩
/-- If `s` has a greatest lower bound, then it is bounded below. -/
lemma is_glb.bdd_below (h : is_glb s a) : bdd_below s := ⟨a, h.1⟩
/-- If `s` has a greatest element, then it is bounded above. -/
lemma is_greatest.bdd_above (h : is_greatest s a) : bdd_above s := ⟨a, h.2⟩
/-- If `s` has a least element, then it is bounded below. -/
lemma is_least.bdd_below (h : is_least s a) : bdd_below s := ⟨a, h.2⟩
lemma is_least.nonempty (h : is_least s a) : s.nonempty := ⟨a, h.1⟩
lemma is_greatest.nonempty (h : is_greatest s a) : s.nonempty := ⟨a, h.1⟩
/-!
### Union and intersection
-/
@[simp] lemma upper_bounds_union : upper_bounds (s ∪ t) = upper_bounds s ∩ upper_bounds t :=
subset.antisymm
(λ b hb, ⟨λ x hx, hb (or.inl hx), λ x hx, hb (or.inr hx)⟩)
(λ b hb x hx, hx.elim (λ hs, hb.1 hs) (λ ht, hb.2 ht))
@[simp] lemma lower_bounds_union : lower_bounds (s ∪ t) = lower_bounds s ∩ lower_bounds t :=
@upper_bounds_union αᵒᵈ _ s t
lemma union_upper_bounds_subset_upper_bounds_inter :
upper_bounds s ∪ upper_bounds t ⊆ upper_bounds (s ∩ t) :=
union_subset
(upper_bounds_mono_set $ inter_subset_left _ _)
(upper_bounds_mono_set $ inter_subset_right _ _)
lemma union_lower_bounds_subset_lower_bounds_inter :
lower_bounds s ∪ lower_bounds t ⊆ lower_bounds (s ∩ t) :=
@union_upper_bounds_subset_upper_bounds_inter αᵒᵈ _ s t
lemma is_least_union_iff {a : α} {s t : set α} :
is_least (s ∪ t) a ↔ (is_least s a ∧ a ∈ lower_bounds t ∨ a ∈ lower_bounds s ∧ is_least t a) :=
by simp [is_least, lower_bounds_union, or_and_distrib_right, and_comm (a ∈ t), and_assoc]
lemma is_greatest_union_iff :
is_greatest (s ∪ t) a ↔ (is_greatest s a ∧ a ∈ upper_bounds t ∨
a ∈ upper_bounds s ∧ is_greatest t a) :=
@is_least_union_iff αᵒᵈ _ a s t
/-- If `s` is bounded, then so is `s ∩ t` -/
lemma bdd_above.inter_of_left (h : bdd_above s) : bdd_above (s ∩ t) :=
h.mono $ inter_subset_left s t
/-- If `t` is bounded, then so is `s ∩ t` -/
lemma bdd_above.inter_of_right (h : bdd_above t) : bdd_above (s ∩ t) :=
h.mono $ inter_subset_right s t
/-- If `s` is bounded, then so is `s ∩ t` -/
lemma bdd_below.inter_of_left (h : bdd_below s) : bdd_below (s ∩ t) :=
h.mono $ inter_subset_left s t
/-- If `t` is bounded, then so is `s ∩ t` -/
lemma bdd_below.inter_of_right (h : bdd_below t) : bdd_below (s ∩ t) :=
h.mono $ inter_subset_right s t
/-- If `s` and `t` are bounded above sets in a `semilattice_sup`, then so is `s ∪ t`. -/
lemma bdd_above.union [semilattice_sup γ] {s t : set γ} :
bdd_above s → bdd_above t → bdd_above (s ∪ t) :=
begin
rintros ⟨bs, hs⟩ ⟨bt, ht⟩,
use bs ⊔ bt,
rw upper_bounds_union,
exact ⟨upper_bounds_mono_mem le_sup_left hs,
upper_bounds_mono_mem le_sup_right ht⟩
end
/-- The union of two sets is bounded above if and only if each of the sets is. -/
lemma bdd_above_union [semilattice_sup γ] {s t : set γ} :
bdd_above (s ∪ t) ↔ bdd_above s ∧ bdd_above t :=
⟨λ h, ⟨h.mono $ subset_union_left s t, h.mono $ subset_union_right s t⟩,
λ h, h.1.union h.2⟩
lemma bdd_below.union [semilattice_inf γ] {s t : set γ} :
bdd_below s → bdd_below t → bdd_below (s ∪ t) :=
@bdd_above.union γᵒᵈ _ s t
/--The union of two sets is bounded above if and only if each of the sets is.-/
lemma bdd_below_union [semilattice_inf γ] {s t : set γ} :
bdd_below (s ∪ t) ↔ bdd_below s ∧ bdd_below t :=
@bdd_above_union γᵒᵈ _ s t
/-- If `a` is the least upper bound of `s` and `b` is the least upper bound of `t`,
then `a ⊔ b` is the least upper bound of `s ∪ t`. -/
lemma is_lub.union [semilattice_sup γ] {a b : γ} {s t : set γ}
(hs : is_lub s a) (ht : is_lub t b) :
is_lub (s ∪ t) (a ⊔ b) :=
⟨λ c h, h.cases_on (λ h, le_sup_of_le_left $ hs.left h) (λ h, le_sup_of_le_right $ ht.left h),
λ c hc, sup_le (hs.right $ λ d hd, hc $ or.inl hd) (ht.right $ λ d hd, hc $ or.inr hd)⟩
/-- If `a` is the greatest lower bound of `s` and `b` is the greatest lower bound of `t`,
then `a ⊓ b` is the greatest lower bound of `s ∪ t`. -/
lemma is_glb.union [semilattice_inf γ] {a₁ a₂ : γ} {s t : set γ}
(hs : is_glb s a₁) (ht : is_glb t a₂) :
is_glb (s ∪ t) (a₁ ⊓ a₂) :=
hs.dual.union ht
/-- If `a` is the least element of `s` and `b` is the least element of `t`,
then `min a b` is the least element of `s ∪ t`. -/
lemma is_least.union [linear_order γ] {a b : γ} {s t : set γ}
(ha : is_least s a) (hb : is_least t b) : is_least (s ∪ t) (min a b) :=
⟨by cases (le_total a b) with h h; simp [h, ha.1, hb.1],
(ha.is_glb.union hb.is_glb).1⟩
/-- If `a` is the greatest element of `s` and `b` is the greatest element of `t`,
then `max a b` is the greatest element of `s ∪ t`. -/
lemma is_greatest.union [linear_order γ] {a b : γ} {s t : set γ}
(ha : is_greatest s a) (hb : is_greatest t b) : is_greatest (s ∪ t) (max a b) :=
⟨by cases (le_total a b) with h h; simp [h, ha.1, hb.1],
(ha.is_lub.union hb.is_lub).1⟩
lemma is_lub.inter_Ici_of_mem [linear_order γ] {s : set γ} {a b : γ} (ha : is_lub s a)
(hb : b ∈ s) : is_lub (s ∩ Ici b) a :=
⟨λ x hx, ha.1 hx.1, λ c hc, have hbc : b ≤ c, from hc ⟨hb, le_rfl⟩,
ha.2 $ λ x hx, (le_total x b).elim (λ hxb, hxb.trans hbc) $ λ hbx, hc ⟨hx, hbx⟩⟩
lemma is_glb.inter_Iic_of_mem [linear_order γ] {s : set γ} {a b : γ} (ha : is_glb s a)
(hb : b ∈ s) : is_glb (s ∩ Iic b) a :=
ha.dual.inter_Ici_of_mem hb
lemma bdd_above_iff_exists_ge [semilattice_sup γ] {s : set γ} (x₀ : γ) :
bdd_above s ↔ ∃ x, x₀ ≤ x ∧ ∀ y ∈ s, y ≤ x :=
by { rw [bdd_above_def, exists_ge_and_iff_exists], exact monotone.ball (λ x hx, monotone_le) }
lemma bdd_below_iff_exists_le [semilattice_inf γ] {s : set γ} (x₀ : γ) :
bdd_below s ↔ ∃ x, x ≤ x₀ ∧ ∀ y ∈ s, x ≤ y :=
bdd_above_iff_exists_ge (to_dual x₀)
lemma bdd_above.exists_ge [semilattice_sup γ] {s : set γ} (hs : bdd_above s) (x₀ : γ) :
∃ x, x₀ ≤ x ∧ ∀ y ∈ s, y ≤ x :=
(bdd_above_iff_exists_ge x₀).mp hs
lemma bdd_below.exists_le [semilattice_inf γ] {s : set γ} (hs : bdd_below s) (x₀ : γ) :
∃ x, x ≤ x₀ ∧ ∀ y ∈ s, x ≤ y :=
(bdd_below_iff_exists_le x₀).mp hs
/-!
### Specific sets
#### Unbounded intervals
-/
lemma is_least_Ici : is_least (Ici a) a := ⟨left_mem_Ici, λ x, id⟩
lemma is_greatest_Iic : is_greatest (Iic a) a := ⟨right_mem_Iic, λ x, id⟩
lemma is_lub_Iic : is_lub (Iic a) a := is_greatest_Iic.is_lub
lemma is_glb_Ici : is_glb (Ici a) a := is_least_Ici.is_glb
lemma upper_bounds_Iic : upper_bounds (Iic a) = Ici a := is_lub_Iic.upper_bounds_eq
lemma lower_bounds_Ici : lower_bounds (Ici a) = Iic a := is_glb_Ici.lower_bounds_eq
lemma bdd_above_Iic : bdd_above (Iic a) := is_lub_Iic.bdd_above
lemma bdd_below_Ici : bdd_below (Ici a) := is_glb_Ici.bdd_below
lemma bdd_above_Iio : bdd_above (Iio a) := ⟨a, λ x hx, le_of_lt hx⟩
lemma bdd_below_Ioi : bdd_below (Ioi a) := ⟨a, λ x hx, le_of_lt hx⟩
lemma lub_Iio_le (a : α) (hb : is_lub (set.Iio a) b) : b ≤ a :=
(is_lub_le_iff hb).mpr $ λ k hk, le_of_lt hk
lemma le_glb_Ioi (a : α) (hb : is_glb (set.Ioi a) b) : a ≤ b := @lub_Iio_le αᵒᵈ _ _ a hb
lemma lub_Iio_eq_self_or_Iio_eq_Iic [partial_order γ] {j : γ} (i : γ) (hj : is_lub (set.Iio i) j) :
j = i ∨ set.Iio i = set.Iic j :=
begin
cases eq_or_lt_of_le (lub_Iio_le i hj) with hj_eq_i hj_lt_i,
{ exact or.inl hj_eq_i, },
{ right,
exact set.ext (λ k, ⟨λ hk_lt, hj.1 hk_lt, λ hk_le_j, lt_of_le_of_lt hk_le_j hj_lt_i⟩), },
end
lemma glb_Ioi_eq_self_or_Ioi_eq_Ici [partial_order γ] {j : γ} (i : γ) (hj : is_glb (set.Ioi i) j) :
j = i ∨ set.Ioi i = set.Ici j :=
@lub_Iio_eq_self_or_Iio_eq_Iic γᵒᵈ _ j i hj
section
variables [linear_order γ]
lemma exists_lub_Iio (i : γ) : ∃ j, is_lub (set.Iio i) j :=
begin
by_cases h_exists_lt : ∃ j, j ∈ upper_bounds (set.Iio i) ∧ j < i,
{ obtain ⟨j, hj_ub, hj_lt_i⟩ := h_exists_lt,
exact ⟨j, hj_ub, λ k hk_ub, hk_ub hj_lt_i⟩, },
{ refine ⟨i, λ j hj, le_of_lt hj, _⟩,
rw mem_lower_bounds,
by_contra,
refine h_exists_lt _,
push_neg at h,
exact h, },
end
lemma exists_glb_Ioi (i : γ) : ∃ j, is_glb (set.Ioi i) j := @exists_lub_Iio γᵒᵈ _ i
variables [densely_ordered γ]
lemma is_lub_Iio {a : γ} : is_lub (Iio a) a :=
⟨λ x hx, le_of_lt hx, λ y hy, le_of_forall_ge_of_dense hy⟩
lemma is_glb_Ioi {a : γ} : is_glb (Ioi a) a := @is_lub_Iio γᵒᵈ _ _ a
lemma upper_bounds_Iio {a : γ} : upper_bounds (Iio a) = Ici a := is_lub_Iio.upper_bounds_eq
lemma lower_bounds_Ioi {a : γ} : lower_bounds (Ioi a) = Iic a := is_glb_Ioi.lower_bounds_eq
end
/-!
#### Singleton
-/
lemma is_greatest_singleton : is_greatest {a} a :=
⟨mem_singleton a, λ x hx, le_of_eq $ eq_of_mem_singleton hx⟩
lemma is_least_singleton : is_least {a} a := @is_greatest_singleton αᵒᵈ _ a
lemma is_lub_singleton : is_lub {a} a := is_greatest_singleton.is_lub
lemma is_glb_singleton : is_glb {a} a := is_least_singleton.is_glb
lemma bdd_above_singleton : bdd_above ({a} : set α) := is_lub_singleton.bdd_above
lemma bdd_below_singleton : bdd_below ({a} : set α) := is_glb_singleton.bdd_below
@[simp] lemma upper_bounds_singleton : upper_bounds {a} = Ici a := is_lub_singleton.upper_bounds_eq
@[simp] lemma lower_bounds_singleton : lower_bounds {a} = Iic a := is_glb_singleton.lower_bounds_eq
/-!
#### Bounded intervals
-/
lemma bdd_above_Icc : bdd_above (Icc a b) := ⟨b, λ _, and.right⟩
lemma bdd_below_Icc : bdd_below (Icc a b) := ⟨a, λ _, and.left⟩
lemma bdd_above_Ico : bdd_above (Ico a b) := bdd_above_Icc.mono Ico_subset_Icc_self
lemma bdd_below_Ico : bdd_below (Ico a b) := bdd_below_Icc.mono Ico_subset_Icc_self
lemma bdd_above_Ioc : bdd_above (Ioc a b) := bdd_above_Icc.mono Ioc_subset_Icc_self
lemma bdd_below_Ioc : bdd_below (Ioc a b) := bdd_below_Icc.mono Ioc_subset_Icc_self
lemma bdd_above_Ioo : bdd_above (Ioo a b) := bdd_above_Icc.mono Ioo_subset_Icc_self
lemma bdd_below_Ioo : bdd_below (Ioo a b) := bdd_below_Icc.mono Ioo_subset_Icc_self
lemma is_greatest_Icc (h : a ≤ b) : is_greatest (Icc a b) b :=
⟨right_mem_Icc.2 h, λ x, and.right⟩
lemma is_lub_Icc (h : a ≤ b) : is_lub (Icc a b) b := (is_greatest_Icc h).is_lub
lemma upper_bounds_Icc (h : a ≤ b) : upper_bounds (Icc a b) = Ici b :=
(is_lub_Icc h).upper_bounds_eq
lemma is_least_Icc (h : a ≤ b) : is_least (Icc a b) a :=
⟨left_mem_Icc.2 h, λ x, and.left⟩
lemma is_glb_Icc (h : a ≤ b) : is_glb (Icc a b) a := (is_least_Icc h).is_glb
lemma lower_bounds_Icc (h : a ≤ b) : lower_bounds (Icc a b) = Iic a :=
(is_glb_Icc h).lower_bounds_eq
lemma is_greatest_Ioc (h : a < b) : is_greatest (Ioc a b) b :=
⟨right_mem_Ioc.2 h, λ x, and.right⟩
lemma is_lub_Ioc (h : a < b) : is_lub (Ioc a b) b :=
(is_greatest_Ioc h).is_lub
lemma upper_bounds_Ioc (h : a < b) : upper_bounds (Ioc a b) = Ici b :=
(is_lub_Ioc h).upper_bounds_eq
lemma is_least_Ico (h : a < b) : is_least (Ico a b) a :=
⟨left_mem_Ico.2 h, λ x, and.left⟩
lemma is_glb_Ico (h : a < b) : is_glb (Ico a b) a :=
(is_least_Ico h).is_glb
lemma lower_bounds_Ico (h : a < b) : lower_bounds (Ico a b) = Iic a :=
(is_glb_Ico h).lower_bounds_eq
section
variables [semilattice_sup γ] [densely_ordered γ]
lemma is_glb_Ioo {a b : γ} (h : a < b) :
is_glb (Ioo a b) a :=
⟨λ x hx, hx.1.le, λ x hx,
begin
cases eq_or_lt_of_le (le_sup_right : a ≤ x ⊔ a) with h₁ h₂,
{ exact h₁.symm ▸ le_sup_left },
obtain ⟨y, lty, ylt⟩ := exists_between h₂,
apply (not_lt_of_le (sup_le (hx ⟨lty, ylt.trans_le (sup_le _ h.le)⟩) lty.le) ylt).elim,
obtain ⟨u, au, ub⟩ := exists_between h,
apply (hx ⟨au, ub⟩).trans ub.le,
end⟩
lemma lower_bounds_Ioo {a b : γ} (hab : a < b) : lower_bounds (Ioo a b) = Iic a :=
(is_glb_Ioo hab).lower_bounds_eq
lemma is_glb_Ioc {a b : γ} (hab : a < b) : is_glb (Ioc a b) a :=
(is_glb_Ioo hab).of_subset_of_superset (is_glb_Icc hab.le) Ioo_subset_Ioc_self Ioc_subset_Icc_self
lemma lower_bound_Ioc {a b : γ} (hab : a < b) : lower_bounds (Ioc a b) = Iic a :=
(is_glb_Ioc hab).lower_bounds_eq
end
section
variables [semilattice_inf γ] [densely_ordered γ]
lemma is_lub_Ioo {a b : γ} (hab : a < b) : is_lub (Ioo a b) b :=
by simpa only [dual_Ioo] using is_glb_Ioo hab.dual
lemma upper_bounds_Ioo {a b : γ} (hab : a < b) : upper_bounds (Ioo a b) = Ici b :=
(is_lub_Ioo hab).upper_bounds_eq
lemma is_lub_Ico {a b : γ} (hab : a < b) : is_lub (Ico a b) b :=
by simpa only [dual_Ioc] using is_glb_Ioc hab.dual
lemma upper_bounds_Ico {a b : γ} (hab : a < b) : upper_bounds (Ico a b) = Ici b :=
(is_lub_Ico hab).upper_bounds_eq
end
lemma bdd_below_iff_subset_Ici : bdd_below s ↔ ∃ a, s ⊆ Ici a := iff.rfl
lemma bdd_above_iff_subset_Iic : bdd_above s ↔ ∃ a, s ⊆ Iic a := iff.rfl
lemma bdd_below_bdd_above_iff_subset_Icc : bdd_below s ∧ bdd_above s ↔ ∃ a b, s ⊆ Icc a b :=
by simp only [Ici_inter_Iic.symm, subset_inter_iff, bdd_below_iff_subset_Ici,
bdd_above_iff_subset_Iic, exists_and_distrib_left, exists_and_distrib_right]
/-!
#### Univ
-/
@[simp] lemma is_greatest_univ_iff : is_greatest univ a ↔ is_top a :=
by simp [is_greatest, mem_upper_bounds, is_top]
lemma is_greatest_univ [order_top α] : is_greatest (univ : set α) ⊤ :=
is_greatest_univ_iff.2 is_top_top
@[simp] lemma order_top.upper_bounds_univ [partial_order γ] [order_top γ] :
upper_bounds (univ : set γ) = {⊤} :=
by rw [is_greatest_univ.upper_bounds_eq, Ici_top]
lemma is_lub_univ [order_top α] : is_lub (univ : set α) ⊤ := is_greatest_univ.is_lub
@[simp] lemma order_bot.lower_bounds_univ [partial_order γ] [order_bot γ] :
lower_bounds (univ : set γ) = {⊥} :=
@order_top.upper_bounds_univ γᵒᵈ _ _
@[simp] lemma is_least_univ_iff : is_least univ a ↔ is_bot a := @is_greatest_univ_iff αᵒᵈ _ _
lemma is_least_univ [order_bot α] : is_least (univ : set α) ⊥ := @is_greatest_univ αᵒᵈ _ _
lemma is_glb_univ [order_bot α] : is_glb (univ : set α) ⊥ := is_least_univ.is_glb
@[simp] lemma no_max_order.upper_bounds_univ [no_max_order α] : upper_bounds (univ : set α) = ∅ :=
eq_empty_of_subset_empty $ λ b hb, let ⟨x, hx⟩ := exists_gt b in
not_le_of_lt hx (hb trivial)
@[simp] lemma no_min_order.lower_bounds_univ [no_min_order α] : lower_bounds (univ : set α) = ∅ :=
@no_max_order.upper_bounds_univ αᵒᵈ _ _
@[simp] lemma not_bdd_above_univ [no_max_order α] : ¬bdd_above (univ : set α) :=
by simp [bdd_above]
@[simp] lemma not_bdd_below_univ [no_min_order α] : ¬bdd_below (univ : set α) :=
@not_bdd_above_univ αᵒᵈ _ _
/-!
#### Empty set
-/
@[simp] lemma upper_bounds_empty : upper_bounds (∅ : set α) = univ :=
by simp only [upper_bounds, eq_univ_iff_forall, mem_set_of_eq, ball_empty_iff, forall_true_iff]
@[simp] lemma lower_bounds_empty : lower_bounds (∅ : set α) = univ := @upper_bounds_empty αᵒᵈ _
@[simp] lemma bdd_above_empty [nonempty α] : bdd_above (∅ : set α) :=
by simp only [bdd_above, upper_bounds_empty, univ_nonempty]
@[simp] lemma bdd_below_empty [nonempty α] : bdd_below (∅ : set α) :=
by simp only [bdd_below, lower_bounds_empty, univ_nonempty]
@[simp] lemma is_glb_empty_iff : is_glb ∅ a ↔ is_top a := by simp [is_glb]
@[simp] lemma is_lub_empty_iff : is_lub ∅ a ↔ is_bot a := @is_glb_empty_iff αᵒᵈ _ _
lemma is_glb_empty [order_top α] : is_glb ∅ (⊤:α) := is_glb_empty_iff.2 is_top_top
lemma is_lub_empty [order_bot α] : is_lub ∅ (⊥:α) := @is_glb_empty αᵒᵈ _ _
lemma is_lub.nonempty [no_min_order α] (hs : is_lub s a) : s.nonempty :=
let ⟨a', ha'⟩ := exists_lt a in
nonempty_iff_ne_empty.2 $ λ h, not_le_of_lt ha' $ hs.right $ by simp only [h, upper_bounds_empty]
lemma is_glb.nonempty [no_max_order α] (hs : is_glb s a) : s.nonempty := hs.dual.nonempty
lemma nonempty_of_not_bdd_above [ha : nonempty α] (h : ¬bdd_above s) : s.nonempty :=
nonempty.elim ha $ λ x, (not_bdd_above_iff'.1 h x).imp $ λ a ha, ha.fst
lemma nonempty_of_not_bdd_below [ha : nonempty α] (h : ¬bdd_below s) : s.nonempty :=
@nonempty_of_not_bdd_above αᵒᵈ _ _ _ h
/-!
#### insert
-/
/-- Adding a point to a set preserves its boundedness above. -/
@[simp] lemma bdd_above_insert [semilattice_sup γ] (a : γ) {s : set γ} :
bdd_above (insert a s) ↔ bdd_above s :=
by simp only [insert_eq, bdd_above_union, bdd_above_singleton, true_and]
lemma bdd_above.insert [semilattice_sup γ] (a : γ) {s : set γ} (hs : bdd_above s) :
bdd_above (insert a s) :=
(bdd_above_insert a).2 hs
/--Adding a point to a set preserves its boundedness below.-/
@[simp] lemma bdd_below_insert [semilattice_inf γ] (a : γ) {s : set γ} :
bdd_below (insert a s) ↔ bdd_below s :=
by simp only [insert_eq, bdd_below_union, bdd_below_singleton, true_and]
lemma bdd_below.insert [semilattice_inf γ] (a : γ) {s : set γ} (hs : bdd_below s) :
bdd_below (insert a s) :=
(bdd_below_insert a).2 hs
lemma is_lub.insert [semilattice_sup γ] (a) {b} {s : set γ} (hs : is_lub s b) :
is_lub (insert a s) (a ⊔ b) :=
by { rw insert_eq, exact is_lub_singleton.union hs }
lemma is_glb.insert [semilattice_inf γ] (a) {b} {s : set γ} (hs : is_glb s b) :
is_glb (insert a s) (a ⊓ b) :=
by { rw insert_eq, exact is_glb_singleton.union hs }
lemma is_greatest.insert [linear_order γ] (a) {b} {s : set γ} (hs : is_greatest s b) :
is_greatest (insert a s) (max a b) :=
by { rw insert_eq, exact is_greatest_singleton.union hs }
lemma is_least.insert [linear_order γ] (a) {b} {s : set γ} (hs : is_least s b) :
is_least (insert a s) (min a b) :=
by { rw insert_eq, exact is_least_singleton.union hs }
@[simp] lemma upper_bounds_insert (a : α) (s : set α) :
upper_bounds (insert a s) = Ici a ∩ upper_bounds s :=
by rw [insert_eq, upper_bounds_union, upper_bounds_singleton]
@[simp] lemma lower_bounds_insert (a : α) (s : set α) :
lower_bounds (insert a s) = Iic a ∩ lower_bounds s :=
by rw [insert_eq, lower_bounds_union, lower_bounds_singleton]
/-- When there is a global maximum, every set is bounded above. -/
@[simp] protected lemma order_top.bdd_above [order_top α] (s : set α) : bdd_above s :=
⟨⊤, λ a ha, order_top.le_top a⟩
/-- When there is a global minimum, every set is bounded below. -/
@[simp] protected lemma order_bot.bdd_below [order_bot α] (s : set α) : bdd_below s :=
⟨⊥, λ a ha, order_bot.bot_le a⟩
/-!
#### Pair
-/
lemma is_lub_pair [semilattice_sup γ] {a b : γ} : is_lub {a, b} (a ⊔ b) :=
is_lub_singleton.insert _
lemma is_glb_pair [semilattice_inf γ] {a b : γ} : is_glb {a, b} (a ⊓ b) :=
is_glb_singleton.insert _
lemma is_least_pair [linear_order γ] {a b : γ} : is_least {a, b} (min a b) :=
is_least_singleton.insert _
lemma is_greatest_pair [linear_order γ] {a b : γ} : is_greatest {a, b} (max a b) :=
is_greatest_singleton.insert _
/-!
#### Lower/upper bounds
-/
@[simp] lemma is_lub_lower_bounds : is_lub (lower_bounds s) a ↔ is_glb s a :=
⟨λ H, ⟨λ x hx, H.2 $ subset_upper_bounds_lower_bounds s hx, H.1⟩, is_greatest.is_lub⟩
@[simp] lemma is_glb_upper_bounds : is_glb (upper_bounds s) a ↔ is_lub s a :=
@is_lub_lower_bounds αᵒᵈ _ _ _
end
/-!
### (In)equalities with the least upper bound and the greatest lower bound
-/
section preorder
variables [preorder α] {s : set α} {a b : α}
lemma lower_bounds_le_upper_bounds (ha : a ∈ lower_bounds s) (hb : b ∈ upper_bounds s) :
s.nonempty → a ≤ b
| ⟨c, hc⟩ := le_trans (ha hc) (hb hc)
lemma is_glb_le_is_lub (ha : is_glb s a) (hb : is_lub s b) (hs : s.nonempty) : a ≤ b :=
lower_bounds_le_upper_bounds ha.1 hb.1 hs
lemma is_lub_lt_iff (ha : is_lub s a) : a < b ↔ ∃ c ∈ upper_bounds s, c < b :=
⟨λ hb, ⟨a, ha.1, hb⟩, λ ⟨c, hcs, hcb⟩, lt_of_le_of_lt (ha.2 hcs) hcb⟩
lemma lt_is_glb_iff (ha : is_glb s a) : b < a ↔ ∃ c ∈ lower_bounds s, b < c := is_lub_lt_iff ha.dual
lemma le_of_is_lub_le_is_glb {x y} (ha : is_glb s a) (hb : is_lub s b) (hab : b ≤ a)
(hx : x ∈ s) (hy : y ∈ s) : x ≤ y :=
calc x ≤ b : hb.1 hx
... ≤ a : hab
... ≤ y : ha.1 hy
end preorder
section partial_order
variables [partial_order α] {s : set α} {a b : α}
lemma is_least.unique (Ha : is_least s a) (Hb : is_least s b) : a = b :=
le_antisymm (Ha.right Hb.left) (Hb.right Ha.left)
lemma is_least.is_least_iff_eq (Ha : is_least s a) : is_least s b ↔ a = b :=
iff.intro Ha.unique (λ h, h ▸ Ha)
lemma is_greatest.unique (Ha : is_greatest s a) (Hb : is_greatest s b) : a = b :=
le_antisymm (Hb.right Ha.left) (Ha.right Hb.left)
lemma is_greatest.is_greatest_iff_eq (Ha : is_greatest s a) : is_greatest s b ↔ a = b :=
iff.intro Ha.unique (λ h, h ▸ Ha)
lemma is_lub.unique (Ha : is_lub s a) (Hb : is_lub s b) : a = b :=
Ha.unique Hb
lemma is_glb.unique (Ha : is_glb s a) (Hb : is_glb s b) : a = b :=
Ha.unique Hb
lemma set.subsingleton_of_is_lub_le_is_glb (Ha : is_glb s a) (Hb : is_lub s b) (hab : b ≤ a) :
s.subsingleton :=
λ x hx y hy, le_antisymm (le_of_is_lub_le_is_glb Ha Hb hab hx hy)
(le_of_is_lub_le_is_glb Ha Hb hab hy hx)
lemma is_glb_lt_is_lub_of_ne (Ha : is_glb s a) (Hb : is_lub s b)
{x y} (Hx : x ∈ s) (Hy : y ∈ s) (Hxy : x ≠ y) :
a < b :=
lt_iff_le_not_le.2
⟨lower_bounds_le_upper_bounds Ha.1 Hb.1 ⟨x, Hx⟩,
λ hab, Hxy $ set.subsingleton_of_is_lub_le_is_glb Ha Hb hab Hx Hy⟩
end partial_order
section linear_order
variables [linear_order α] {s : set α} {a b : α}
lemma lt_is_lub_iff (h : is_lub s a) : b < a ↔ ∃ c ∈ s, b < c :=
by simp only [← not_le, is_lub_le_iff h, mem_upper_bounds, not_forall]
lemma is_glb_lt_iff (h : is_glb s a) : a < b ↔ ∃ c ∈ s, c < b := lt_is_lub_iff h.dual
lemma is_lub.exists_between (h : is_lub s a) (hb : b < a) :
∃ c ∈ s, b < c ∧ c ≤ a :=
let ⟨c, hcs, hbc⟩ := (lt_is_lub_iff h).1 hb in ⟨c, hcs, hbc, h.1 hcs⟩
lemma is_lub.exists_between' (h : is_lub s a) (h' : a ∉ s) (hb : b < a) :
∃ c ∈ s, b < c ∧ c < a :=
let ⟨c, hcs, hbc, hca⟩ := h.exists_between hb
in ⟨c, hcs, hbc, hca.lt_of_ne $ λ hac, h' $ hac ▸ hcs⟩
lemma is_glb.exists_between (h : is_glb s a) (hb : a < b) :
∃ c ∈ s, a ≤ c ∧ c < b :=
let ⟨c, hcs, hbc⟩ := (is_glb_lt_iff h).1 hb in ⟨c, hcs, h.1 hcs, hbc⟩
lemma is_glb.exists_between' (h : is_glb s a) (h' : a ∉ s) (hb : a < b) :
∃ c ∈ s, a < c ∧ c < b :=
let ⟨c, hcs, hac, hcb⟩ := h.exists_between hb
in ⟨c, hcs, hac.lt_of_ne $ λ hac, h' $ hac.symm ▸ hcs, hcb⟩
end linear_order
/-!
### Images of upper/lower bounds under monotone functions
-/
namespace monotone_on
variables [preorder α] [preorder β] {f : α → β} {s t : set α}
(Hf : monotone_on f t) {a : α} (Hst : s ⊆ t)
include Hf
lemma mem_upper_bounds_image (Has : a ∈ upper_bounds s) (Hat : a ∈ t) :
f a ∈ upper_bounds (f '' s) :=
ball_image_of_ball (λ x H, Hf (Hst H) Hat (Has H))
lemma mem_upper_bounds_image_self : a ∈ upper_bounds t → a ∈ t → f a ∈ upper_bounds (f '' t) :=
Hf.mem_upper_bounds_image subset_rfl
lemma mem_lower_bounds_image (Has : a ∈ lower_bounds s) (Hat : a ∈ t) :
f a ∈ lower_bounds (f '' s) :=
ball_image_of_ball (λ x H, Hf Hat (Hst H) (Has H))
lemma mem_lower_bounds_image_self : a ∈ lower_bounds t → a ∈ t → f a ∈ lower_bounds (f '' t) :=
Hf.mem_lower_bounds_image subset_rfl
lemma image_upper_bounds_subset_upper_bounds_image (Hst : s ⊆ t) :
f '' (upper_bounds s ∩ t) ⊆ upper_bounds (f '' s) :=
by { rintro _ ⟨a, ha, rfl⟩, exact Hf.mem_upper_bounds_image Hst ha.1 ha.2 }
lemma image_lower_bounds_subset_lower_bounds_image :
f '' (lower_bounds s ∩ t) ⊆ lower_bounds (f '' s) :=
Hf.dual.image_upper_bounds_subset_upper_bounds_image Hst
/-- The image under a monotone function on a set `t` of a subset which has an upper bound in `t`
is bounded above. -/
lemma map_bdd_above : (upper_bounds s ∩ t).nonempty → bdd_above (f '' s) :=
λ ⟨C, hs, ht⟩, ⟨f C, Hf.mem_upper_bounds_image Hst hs ht⟩
/-- The image under a monotone function on a set `t` of a subset which has a lower bound in `t`
is bounded below. -/
lemma map_bdd_below : (lower_bounds s ∩ t).nonempty → bdd_below (f '' s) :=
λ ⟨C, hs, ht⟩, ⟨f C, Hf.mem_lower_bounds_image Hst hs ht⟩
/-- A monotone map sends a least element of a set to a least element of its image. -/
lemma map_is_least (Ha : is_least t a) : is_least (f '' t) (f a) :=
⟨mem_image_of_mem _ Ha.1, Hf.mem_lower_bounds_image_self Ha.2 Ha.1⟩
/-- A monotone map sends a greatest element of a set to a greatest element of its image. -/
lemma map_is_greatest (Ha : is_greatest t a) : is_greatest (f '' t) (f a) :=
⟨mem_image_of_mem _ Ha.1, Hf.mem_upper_bounds_image_self Ha.2 Ha.1⟩
end monotone_on
namespace antitone_on
variables [preorder α] [preorder β] {f : α → β} {s t : set α}
(Hf : antitone_on f t) {a : α} (Hst : s ⊆ t)
include Hf
lemma mem_upper_bounds_image (Has : a ∈ lower_bounds s) : a ∈ t → f a ∈ upper_bounds (f '' s) :=
Hf.dual_right.mem_lower_bounds_image Hst Has
lemma mem_upper_bounds_image_self : a ∈ lower_bounds t → a ∈ t → f a ∈ upper_bounds (f '' t) :=
Hf.dual_right.mem_lower_bounds_image_self
lemma mem_lower_bounds_image : a ∈ upper_bounds s → a ∈ t → f a ∈ lower_bounds (f '' s) :=
Hf.dual_right.mem_upper_bounds_image Hst
lemma mem_lower_bounds_image_self : a ∈ upper_bounds t → a ∈ t → f a ∈ lower_bounds (f '' t) :=
Hf.dual_right.mem_upper_bounds_image_self
lemma image_lower_bounds_subset_upper_bounds_image :
f '' (lower_bounds s ∩ t) ⊆ upper_bounds (f '' s) :=
Hf.dual_right.image_lower_bounds_subset_lower_bounds_image Hst
lemma image_upper_bounds_subset_lower_bounds_image :
f '' (upper_bounds s ∩ t) ⊆ lower_bounds (f '' s) :=
Hf.dual_right.image_upper_bounds_subset_upper_bounds_image Hst
/-- The image under an antitone function of a set which is bounded above is bounded below. -/
lemma map_bdd_above : (upper_bounds s ∩ t).nonempty → bdd_below (f '' s) :=
Hf.dual_right.map_bdd_above Hst
/-- The image under an antitone function of a set which is bounded below is bounded above. -/
lemma map_bdd_below : (lower_bounds s ∩ t).nonempty → bdd_above (f '' s) :=
Hf.dual_right.map_bdd_below Hst
/-- An antitone map sends a greatest element of a set to a least element of its image. -/
lemma map_is_greatest : is_greatest t a → is_least (f '' t) (f a) :=
Hf.dual_right.map_is_greatest
/-- An antitone map sends a least element of a set to a greatest element of its image. -/
lemma map_is_least : is_least t a → is_greatest (f '' t) (f a) :=
Hf.dual_right.map_is_least
end antitone_on
namespace monotone
variables [preorder α] [preorder β] {f : α → β} (Hf : monotone f) {a : α} {s : set α}
include Hf
lemma mem_upper_bounds_image (Ha : a ∈ upper_bounds s) : f a ∈ upper_bounds (f '' s) :=
ball_image_of_ball (λ x H, Hf (Ha H))
lemma mem_lower_bounds_image (Ha : a ∈ lower_bounds s) : f a ∈ lower_bounds (f '' s) :=
ball_image_of_ball (λ x H, Hf (Ha H))
lemma image_upper_bounds_subset_upper_bounds_image : f '' upper_bounds s ⊆ upper_bounds (f '' s) :=
by { rintro _ ⟨a, ha, rfl⟩, exact Hf.mem_upper_bounds_image ha }
lemma image_lower_bounds_subset_lower_bounds_image : f '' lower_bounds s ⊆ lower_bounds (f '' s) :=
Hf.dual.image_upper_bounds_subset_upper_bounds_image
/-- The image under a monotone function of a set which is bounded above is bounded above. See also
`bdd_above.image2`. -/
lemma map_bdd_above : bdd_above s → bdd_above (f '' s)
| ⟨C, hC⟩ := ⟨f C, Hf.mem_upper_bounds_image hC⟩
/-- The image under a monotone function of a set which is bounded below is bounded below. See also
`bdd_below.image2`. -/
lemma map_bdd_below : bdd_below s → bdd_below (f '' s)
| ⟨C, hC⟩ := ⟨f C, Hf.mem_lower_bounds_image hC⟩
/-- A monotone map sends a least element of a set to a least element of its image. -/
lemma map_is_least (Ha : is_least s a) : is_least (f '' s) (f a) :=
⟨mem_image_of_mem _ Ha.1, Hf.mem_lower_bounds_image Ha.2⟩
/-- A monotone map sends a greatest element of a set to a greatest element of its image. -/
lemma map_is_greatest (Ha : is_greatest s a) : is_greatest (f '' s) (f a) :=
⟨mem_image_of_mem _ Ha.1, Hf.mem_upper_bounds_image Ha.2⟩
end monotone
namespace antitone
variables [preorder α] [preorder β] {f : α → β} (hf : antitone f) {a : α} {s : set α}
lemma mem_upper_bounds_image : a ∈ lower_bounds s → f a ∈ upper_bounds (f '' s) :=
hf.dual_right.mem_lower_bounds_image
lemma mem_lower_bounds_image : a ∈ upper_bounds s → f a ∈ lower_bounds (f '' s) :=
hf.dual_right.mem_upper_bounds_image
lemma image_lower_bounds_subset_upper_bounds_image : f '' lower_bounds s ⊆ upper_bounds (f '' s) :=
hf.dual_right.image_lower_bounds_subset_lower_bounds_image
lemma image_upper_bounds_subset_lower_bounds_image : f '' upper_bounds s ⊆ lower_bounds (f '' s) :=
hf.dual_right.image_upper_bounds_subset_upper_bounds_image
/-- The image under an antitone function of a set which is bounded above is bounded below. -/
lemma map_bdd_above : bdd_above s → bdd_below (f '' s) :=
hf.dual_right.map_bdd_above
/-- The image under an antitone function of a set which is bounded below is bounded above. -/
lemma map_bdd_below : bdd_below s → bdd_above (f '' s) :=
hf.dual_right.map_bdd_below
/-- An antitone map sends a greatest element of a set to a least element of its image. -/
lemma map_is_greatest : is_greatest s a → is_least (f '' s) (f a) :=
hf.dual_right.map_is_greatest
/-- An antitone map sends a least element of a set to a greatest element of its image. -/
lemma map_is_least : is_least s a → is_greatest (f '' s) (f a) :=
hf.dual_right.map_is_least
end antitone
section image2
variables [preorder α] [preorder β] [preorder γ] {f : α → β → γ} {s : set α} {t : set β} {a : α}
{b : β}
section monotone_monotone
variables (h₀ : ∀ b, monotone (swap f b)) (h₁ : ∀ a, monotone (f a))
include h₀ h₁
lemma mem_upper_bounds_image2 (ha : a ∈ upper_bounds s) (hb : b ∈ upper_bounds t) :
f a b ∈ upper_bounds (image2 f s t) :=
forall_image2_iff.2 $ λ x hx y hy, (h₀ _ $ ha hx).trans $ h₁ _ $ hb hy
lemma mem_lower_bounds_image2 (ha : a ∈ lower_bounds s) (hb : b ∈ lower_bounds t) :
f a b ∈ lower_bounds (image2 f s t) :=
forall_image2_iff.2 $ λ x hx y hy, (h₀ _ $ ha hx).trans $ h₁ _ $ hb hy
lemma image2_upper_bounds_upper_bounds_subset :
image2 f (upper_bounds s) (upper_bounds t) ⊆ upper_bounds (image2 f s t) :=
by { rintro _ ⟨a, b, ha, hb, rfl⟩, exact mem_upper_bounds_image2 h₀ h₁ ha hb }
lemma image2_lower_bounds_lower_bounds_subset :
image2 f (lower_bounds s) (lower_bounds t) ⊆ lower_bounds (image2 f s t) :=
by { rintro _ ⟨a, b, ha, hb, rfl⟩, exact mem_lower_bounds_image2 h₀ h₁ ha hb }
/-- See also `monotone.map_bdd_above`. -/
lemma bdd_above.image2 : bdd_above s → bdd_above t → bdd_above (image2 f s t) :=
by { rintro ⟨a, ha⟩ ⟨b, hb⟩, exact ⟨f a b, mem_upper_bounds_image2 h₀ h₁ ha hb⟩ }
/-- See also `monotone.map_bdd_below`. -/
lemma bdd_below.image2 : bdd_below s → bdd_below t → bdd_below (image2 f s t) :=
by { rintro ⟨a, ha⟩ ⟨b, hb⟩, exact ⟨f a b, mem_lower_bounds_image2 h₀ h₁ ha hb⟩ }
lemma is_greatest.image2 (ha : is_greatest s a) (hb : is_greatest t b) :
is_greatest (image2 f s t) (f a b) :=
⟨mem_image2_of_mem ha.1 hb.1, mem_upper_bounds_image2 h₀ h₁ ha.2 hb.2⟩
lemma is_least.image2 (ha : is_least s a) (hb : is_least t b) : is_least (image2 f s t) (f a b) :=
⟨mem_image2_of_mem ha.1 hb.1, mem_lower_bounds_image2 h₀ h₁ ha.2 hb.2⟩
end monotone_monotone
section monotone_antitone
variables (h₀ : ∀ b, monotone (swap f b)) (h₁ : ∀ a, antitone (f a))
include h₀ h₁
lemma mem_upper_bounds_image2_of_mem_upper_bounds_of_mem_lower_bounds (ha : a ∈ upper_bounds s)
(hb : b ∈ lower_bounds t) : f a b ∈ upper_bounds (image2 f s t) :=
forall_image2_iff.2 $ λ x hx y hy, (h₀ _ $ ha hx).trans $ h₁ _ $ hb hy
lemma mem_lower_bounds_image2_of_mem_lower_bounds_of_mem_upper_bounds (ha : a ∈ lower_bounds s)
(hb : b ∈ upper_bounds t) : f a b ∈ lower_bounds (image2 f s t) :=
forall_image2_iff.2 $ λ x hx y hy, (h₀ _ $ ha hx).trans $ h₁ _ $ hb hy
lemma image2_upper_bounds_lower_bounds_subset_upper_bounds_image2 :
image2 f (upper_bounds s) (lower_bounds t) ⊆ upper_bounds (image2 f s t) :=
by { rintro _ ⟨a, b, ha, hb, rfl⟩,
exact mem_upper_bounds_image2_of_mem_upper_bounds_of_mem_lower_bounds h₀ h₁ ha hb }
lemma image2_lower_bounds_upper_bounds_subset_lower_bounds_image2 :
image2 f (lower_bounds s) (upper_bounds t) ⊆ lower_bounds (image2 f s t) :=
by { rintro _ ⟨a, b, ha, hb, rfl⟩,
exact mem_lower_bounds_image2_of_mem_lower_bounds_of_mem_upper_bounds h₀ h₁ ha hb }
lemma bdd_above.bdd_above_image2_of_bdd_below :
bdd_above s → bdd_below t → bdd_above (image2 f s t) :=
by { rintro ⟨a, ha⟩ ⟨b, hb⟩,
exact ⟨f a b, mem_upper_bounds_image2_of_mem_upper_bounds_of_mem_lower_bounds h₀ h₁ ha hb⟩ }
lemma bdd_below.bdd_below_image2_of_bdd_above :
bdd_below s → bdd_above t → bdd_below (image2 f s t) :=
by { rintro ⟨a, ha⟩ ⟨b, hb⟩,
exact ⟨f a b, mem_lower_bounds_image2_of_mem_lower_bounds_of_mem_upper_bounds h₀ h₁ ha hb⟩ }
lemma is_greatest.is_greatest_image2_of_is_least (ha : is_greatest s a) (hb : is_least t b) :
is_greatest (image2 f s t) (f a b) :=
⟨mem_image2_of_mem ha.1 hb.1,
mem_upper_bounds_image2_of_mem_upper_bounds_of_mem_lower_bounds h₀ h₁ ha.2 hb.2⟩
lemma is_least.is_least_image2_of_is_greatest (ha : is_least s a) (hb : is_greatest t b) :
is_least (image2 f s t) (f a b) :=
⟨mem_image2_of_mem ha.1 hb.1,
mem_lower_bounds_image2_of_mem_lower_bounds_of_mem_upper_bounds h₀ h₁ ha.2 hb.2⟩
end monotone_antitone
section antitone_antitone
variables (h₀ : ∀ b, antitone (swap f b)) (h₁ : ∀ a, antitone (f a))
include h₀ h₁
lemma mem_upper_bounds_image2_of_mem_lower_bounds (ha : a ∈ lower_bounds s)
(hb : b ∈ lower_bounds t) :
f a b ∈ upper_bounds (image2 f s t) :=
forall_image2_iff.2 $ λ x hx y hy, (h₀ _ $ ha hx).trans $ h₁ _ $ hb hy
lemma mem_lower_bounds_image2_of_mem_upper_bounds (ha : a ∈ upper_bounds s)
(hb : b ∈ upper_bounds t) :
f a b ∈ lower_bounds (image2 f s t) :=
forall_image2_iff.2 $ λ x hx y hy, (h₀ _ $ ha hx).trans $ h₁ _ $ hb hy
lemma image2_upper_bounds_upper_bounds_subset_upper_bounds_image2 :
image2 f (lower_bounds s) (lower_bounds t) ⊆ upper_bounds (image2 f s t) :=
by { rintro _ ⟨a, b, ha, hb, rfl⟩, exact mem_upper_bounds_image2_of_mem_lower_bounds h₀ h₁ ha hb }
lemma image2_lower_bounds_lower_bounds_subset_lower_bounds_image2 :
image2 f (upper_bounds s) (upper_bounds t) ⊆ lower_bounds (image2 f s t) :=
by { rintro _ ⟨a, b, ha, hb, rfl⟩, exact mem_lower_bounds_image2_of_mem_upper_bounds h₀ h₁ ha hb }
lemma bdd_below.image2_bdd_above : bdd_below s → bdd_below t → bdd_above (image2 f s t) :=
by { rintro ⟨a, ha⟩ ⟨b, hb⟩,
exact ⟨f a b, mem_upper_bounds_image2_of_mem_lower_bounds h₀ h₁ ha hb⟩ }
lemma bdd_above.image2_bdd_below : bdd_above s → bdd_above t → bdd_below (image2 f s t) :=
by { rintro ⟨a, ha⟩ ⟨b, hb⟩,
exact ⟨f a b, mem_lower_bounds_image2_of_mem_upper_bounds h₀ h₁ ha hb⟩ }
lemma is_least.is_greatest_image2 (ha : is_least s a) (hb : is_least t b) :
is_greatest (image2 f s t) (f a b) :=
⟨mem_image2_of_mem ha.1 hb.1, mem_upper_bounds_image2_of_mem_lower_bounds h₀ h₁ ha.2 hb.2⟩
lemma is_greatest.is_least_image2 (ha : is_greatest s a) (hb : is_greatest t b) :
is_least (image2 f s t) (f a b) :=
⟨mem_image2_of_mem ha.1 hb.1, mem_lower_bounds_image2_of_mem_upper_bounds h₀ h₁ ha.2 hb.2⟩
end antitone_antitone
section antitone_monotone
variables (h₀ : ∀ b, antitone (swap f b)) (h₁ : ∀ a, monotone (f a))
include h₀ h₁
lemma mem_upper_bounds_image2_of_mem_upper_bounds_of_mem_upper_bounds (ha : a ∈ lower_bounds s)
(hb : b ∈ upper_bounds t) : f a b ∈ upper_bounds (image2 f s t) :=
forall_image2_iff.2 $ λ x hx y hy, (h₀ _ $ ha hx).trans $ h₁ _ $ hb hy
lemma mem_lower_bounds_image2_of_mem_lower_bounds_of_mem_lower_bounds (ha : a ∈ upper_bounds s)
(hb : b ∈ lower_bounds t) : f a b ∈ lower_bounds (image2 f s t) :=
forall_image2_iff.2 $ λ x hx y hy, (h₀ _ $ ha hx).trans $ h₁ _ $ hb hy
lemma image2_lower_bounds_upper_bounds_subset_upper_bounds_image2 :
image2 f (lower_bounds s) (upper_bounds t) ⊆ upper_bounds (image2 f s t) :=
by { rintro _ ⟨a, b, ha, hb, rfl⟩,
exact mem_upper_bounds_image2_of_mem_upper_bounds_of_mem_upper_bounds h₀ h₁ ha hb }
lemma image2_upper_bounds_lower_bounds_subset_lower_bounds_image2 :
image2 f (upper_bounds s) (lower_bounds t) ⊆ lower_bounds (image2 f s t) :=
by { rintro _ ⟨a, b, ha, hb, rfl⟩,
exact mem_lower_bounds_image2_of_mem_lower_bounds_of_mem_lower_bounds h₀ h₁ ha hb }
lemma bdd_below.bdd_above_image2_of_bdd_above :
bdd_below s → bdd_above t → bdd_above (image2 f s t) :=
by { rintro ⟨a, ha⟩ ⟨b, hb⟩,
exact ⟨f a b, mem_upper_bounds_image2_of_mem_upper_bounds_of_mem_upper_bounds h₀ h₁ ha hb⟩ }
lemma bdd_above.bdd_below_image2_of_bdd_above :
bdd_above s → bdd_below t → bdd_below (image2 f s t) :=
by { rintro ⟨a, ha⟩ ⟨b, hb⟩,
exact ⟨f a b, mem_lower_bounds_image2_of_mem_lower_bounds_of_mem_lower_bounds h₀ h₁ ha hb⟩ }
lemma is_least.is_greatest_image2_of_is_greatest (ha : is_least s a) (hb : is_greatest t b) :
is_greatest (image2 f s t) (f a b) :=
⟨mem_image2_of_mem ha.1 hb.1,
mem_upper_bounds_image2_of_mem_upper_bounds_of_mem_upper_bounds h₀ h₁ ha.2 hb.2⟩
lemma is_greatest.is_least_image2_of_is_least (ha : is_greatest s a) (hb : is_least t b) :
is_least (image2 f s t) (f a b) :=
⟨mem_image2_of_mem ha.1 hb.1,
mem_lower_bounds_image2_of_mem_lower_bounds_of_mem_lower_bounds h₀ h₁ ha.2 hb.2⟩
end antitone_monotone
end image2
lemma is_glb.of_image [preorder α] [preorder β] {f : α → β} (hf : ∀ {x y}, f x ≤ f y ↔ x ≤ y)
{s : set α} {x : α} (hx : is_glb (f '' s) (f x)) :
is_glb s x :=
⟨λ y hy, hf.1 $ hx.1 $ mem_image_of_mem _ hy,
λ y hy, hf.1 $ hx.2 $ monotone.mem_lower_bounds_image (λ x y, hf.2) hy⟩
lemma is_lub.of_image [preorder α] [preorder β] {f : α → β} (hf : ∀ {x y}, f x ≤ f y ↔ x ≤ y)
{s : set α} {x : α} (hx : is_lub (f '' s) (f x)) :
is_lub s x :=
@is_glb.of_image αᵒᵈ βᵒᵈ _ _ f (λ x y, hf) _ _ hx
lemma is_lub_pi {π : α → Type*} [Π a, preorder (π a)] {s : set (Π a, π a)} {f : Π a, π a} :
is_lub s f ↔ ∀ a, is_lub (function.eval a '' s) (f a) :=
begin
classical,
refine ⟨λ H a, ⟨(function.monotone_eval a).mem_upper_bounds_image H.1, λ b hb, _⟩, λ H, ⟨_, _⟩⟩,
{ suffices : function.update f a b ∈ upper_bounds s,
from function.update_same a b f ▸ H.2 this a,
refine λ g hg, le_update_iff.2 ⟨hb $ mem_image_of_mem _ hg, λ i hi, H.1 hg i⟩ },
{ exact λ g hg a, (H a).1 (mem_image_of_mem _ hg) },
{ exact λ g hg a, (H a).2 ((function.monotone_eval a).mem_upper_bounds_image hg) }
end
lemma is_glb_pi {π : α → Type*} [Π a, preorder (π a)] {s : set (Π a, π a)} {f : Π a, π a} :
is_glb s f ↔ ∀ a, is_glb (function.eval a '' s) (f a) :=
@is_lub_pi α (λ a, (π a)ᵒᵈ) _ s f
lemma is_lub_prod [preorder α] [preorder β] {s : set (α × β)} (p : α × β) :
is_lub s p ↔ is_lub (prod.fst '' s) p.1 ∧ is_lub (prod.snd '' s) p.2 :=
begin
refine ⟨λ H, ⟨⟨monotone_fst.mem_upper_bounds_image H.1, λ a ha, _⟩,
⟨monotone_snd.mem_upper_bounds_image H.1, λ a ha, _⟩⟩, λ H, ⟨_, _⟩⟩,
{ suffices : (a, p.2) ∈ upper_bounds s, from (H.2 this).1,
exact λ q hq, ⟨ha $ mem_image_of_mem _ hq, (H.1 hq).2⟩ },
{ suffices : (p.1, a) ∈ upper_bounds s, from (H.2 this).2,
exact λ q hq, ⟨(H.1 hq).1, ha $ mem_image_of_mem _ hq⟩ },
{ exact λ q hq, ⟨H.1.1 $ mem_image_of_mem _ hq, H.2.1 $ mem_image_of_mem _ hq⟩ },
{ exact λ q hq, ⟨H.1.2 $ monotone_fst.mem_upper_bounds_image hq,
H.2.2 $ monotone_snd.mem_upper_bounds_image hq⟩ }
end
lemma is_glb_prod [preorder α] [preorder β] {s : set (α × β)} (p : α × β) :
is_glb s p ↔ is_glb (prod.fst '' s) p.1 ∧ is_glb (prod.snd '' s) p.2 :=
@is_lub_prod αᵒᵈ βᵒᵈ _ _ _ _
|
f21bb3edde78f498319294cb09833afb7f481449
|
b7f22e51856f4989b970961f794f1c435f9b8f78
|
/tests/lean/run/contra2.lean
|
5fb5b27e971127504e17d6fe223fc232ff5559f5
|
[
"Apache-2.0"
] |
permissive
|
soonhokong/lean
|
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
|
38607e3eb57f57f77c0ac114ad169e9e4262e24f
|
refs/heads/master
| 1,611,187,284,081
| 1,450,766,737,000
| 1,476,122,547,000
| 11,513,992
| 2
| 0
| null | 1,401,763,102,000
| 1,374,182,235,000
|
C++
|
UTF-8
|
Lean
| false
| false
| 455
|
lean
|
open nat
example (q p : Prop) (h₁ : p) (h₂ : ¬ p) : q :=
by contradiction
example (q p : Prop) (h₁ : p) (h₂ : p → false) : q :=
by contradiction
example (q : Prop) (a b : nat) (h₁ : a + b = 0) (h₂ : ¬ a + b = 0) : q :=
by contradiction
example (q : Prop) (a b : nat) (h₁ : a + b = 0) (h₂ : a + b ≠ 0) : q :=
by contradiction
example (q : Prop) (a b : nat) (h₁ : a + b = 0) (h₂ : a + b = 0 → false) : q :=
by contradiction
|
d94c55ded90ccb6438be960a4ff7742897b72c43
|
205f0fc16279a69ea36e9fd158e3a97b06834ce2
|
/src/08_Bi_implication/00_intro.lean
|
651d940a89ba01c93e266e17a92c678f0852610d
|
[] |
no_license
|
kevinsullivan/cs-dm-lean
|
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
|
a06a94e98be77170ca1df486c8189338b16cf6c6
|
refs/heads/master
| 1,585,948,743,595
| 1,544,339,346,000
| 1,544,339,346,000
| 155,570,767
| 1
| 3
| null | 1,541,540,372,000
| 1,540,995,993,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 6,133
|
lean
|
/-
If P and Q are propositions, then
so is P ↔ Q. We call this form of
proposition a bi-implication. It
means P → Q ∧ Q → P.
Here's a somewhat silly example:
if it has been raining the ground
in the desert is wet (R → W) and
if the ground in the desert is wet
then it has been raining (W → R).
In this case, we can say that the
ground in the desert is wet "if and
only if" (iff) it has been raining.
In such a situation we say that
"it has been raining" and "the
ground in the desert is wet" are
equivalent, as the two states of
affairs invariable occur or do not
occur together.
The rules for ↔ introducing and
elimination are conceptually the same
as for ∧ applied to two implications,
one going in each direction (R to W
and W to R, respectively).
We recommend that you pronounce
P ↔ Q as "P and Q are equivalent".
Most mathematicians pronounce it
as "P if and only if Q", which
they generally abbreviate P iff
Q (note the extra f). Figuring
out why the phrase "if and only
if" actually makes sense is arguably
more trouble than it's worth. Just
know that people use this phrase
in mathematics and logic all the
time.
/-
*************************
*** Introduction Rule ***
*************************
-/
To construct a proof of P ↔ Q you
must have (or have assumed) proofs
of two propositions: a proof of
P → Q, and a proof of Q → P. The
inference rule is thus as follows:
P Q : Prop, p2q : P → Q, q2p: Q → P
-----------------------------------
PiffQ : P ↔ Q
In informal mathematical writing, a
proof of P ↔ Q will start with the
following kind of language. "We are
to prove P ↔ Q. To prove it we must
first prove P → Q, then we must prove
P → Q. We consider the case P → Q
first. " "first we consider the implication
from P to Q, ..." Once that part
is proved, it will say "and now
we consider the implication in
the other direction." When that
part is also done, it will then
say, combing these results thus
proves P ↔ Q. QED."
Lean provides the iff.intro rule
to construct a proof of P ↔ Q
from the requisite sub-proofs.
Here's an example of its use
in a program whose type makes
clear what's required to use it.
-/
lemma bi_implication :
∀ { P Q : Prop },
(P → Q) → (Q → P) → (P ↔ Q) :=
λ P Q pfPQ pfQP,
iff.intro pfPQ pfQP
/-
The logical way to read this is as
saying that if we assume that P and
Q are propositions, and if we assume
we're given a proof of P → Q and we
furthermore assume we're given a
proof of Q → P then we can derive a
proof of P ↔ Q by appealing to (by
applying) the iff introduction rule
of the natural deduction system of
logical reasoning.
-/
/-
Let's assume we have two propositions,
P and Q.
-/
variables P Q : Prop
/-
and that we have proofs of both P → Q
and of Q → P
-/
variable forward: P → Q
variable backward: Q → P
/-
then we can apply iff-intro to derive
a proof of P ↔ Q.
-/
def pqEquiv := iff.intro forward backward
/-
Going the other way, if we're given a
proof of P ↔ Q, then we can derive proofs
of P → Q and of Q → P using the iff.elim
left and right rules.
-/
#check pqEquiv
/-
A proof of P ↔ Q is essentially a
proof of the conjunction (P → Q) ∧
(Q → P). iff.intro is like ∧-intro,
and the left and right iff.elim
rules are like the ∧-elim left and
right rules.
-/
/-
EXERCISE: Construct a proof, pqequiv, of
the proposition, P ∧ Q ↔ Q ∧ P. Note:
we don't need to know whether P and Q
are true, false, or unknown to provide
such a proof.
-/
theorem andcomm : P ∧ Q ↔ Q ∧ P :=
begin
apply iff.intro,
-- left to right
assume pq : P ∧ Q,
show Q ∧ P,
from and.intro (pq.right) (pq.left),
-- in other direction
assume qp: Q ∧ P,
show P ∧ Q,
from and.intro (qp.right) (qp.left),
end
/-
Note that the proposition that andcomm
proves is: ∀ P Q: Prop, P ∧ Q ↔ Q ∧ P.
The use of "variables P Q : Prop" above
basically adds a "∀ P Q : Prop" to each
of the propositions that follow.
As a result, andcomm in effect takes
any two propositions as arguments and
returns a proof that the conjunctions
are equivalent no matter the order of
the conjuncts.
-/
#check andcomm (0=0) (1=1)
#reduce andcomm (0=0) (1=1)
/-
In the following trivial example,
we can see how the bi_implication
introduction rule (run backwards)
gives us a way to split a goal of
proving P ↔ Q into two sub-goals,
one implication in each direction.
Knowing to do that split and then
to provide two proofs, one for each
direction, is the key to proving
bi-implications, whether using a
prover such as Lean or just using
paper and pencil.
-/
theorem easy_iff: 0 = 0 ↔ 1 = 1 :=
begin
apply bi_implication,
exact λ e, eq.refl 1, -- ignores argument
exact λ e, eq.refl 0, -- ignores argument
end
/-
EXERCISE:
1. Prove that A → B → C ↔ A ∧ B → C.
2. Given that you can prove this, does this
mean that A → B = A ∧ B?
-/
lemma a_imp_b_imp_c_iff_a_and_b_imp_c:
∀ A B C: Prop, (A → B → C) ↔ ((A ∧ B) → C) :=
λ A B C: Prop,
begin
apply iff.intro,
-- forward
assume abc : (A → B → C),
assume ab : A ∧ B,
show C,
from
begin
have a : A := ab.left,
have b : B := ab.right,
show C,
from abc a b,
end,
-- backward
assume abc : (A ∧ B → C),
show A → B → C,
from
begin
assume (a : A) (b : B),
have ab := and.intro a b,
show C,
from abc ab
end,
end
/-
*************************
*** Elimination Rules ***
*************************
-/
/-
As with ∧, the elimination rules,
iff.elim_left and iff.elim_right,
take a proof of P ↔ Q and return
the constituent sub-proofs, P → Q,
and Q → P, respectively.
-/
#check iff.elim_left (andcomm P Q)
#check iff.elim_right (andcomm P Q)
theorem PIffQImpP2Q : (P ↔ Q) → P → Q :=
begin
assume piffq p,
show Q,
from
begin
have p2q := iff.elim_left piffq,
exact (p2q p)
end
end
-- even easier is this
theorem PIffQImpP2Q' : (P ↔ Q) → P -> Q :=
begin
assume piffq,
show P → Q,
from iff.elim_left piffq
end
/-
EXERCISE: Prove P ↔ Q) → Q -> P
-/
|
b5a65a4295180122af858b09dfae213c900e6082
|
c9b68131de1dfe4e7f0ea5749b11e67a774bc839
|
/src/constraints_autogen.lean
|
a0946d4aba0371654484f61816fb57614afe049c
|
[] |
no_license
|
congge666/formal-proofs
|
2013f158f310abcfc07c156bb2a5113fb78f7831
|
b5f6964d0220c8f89668357f2c08e44861128fe3
|
refs/heads/master
| 1,691,374,567,671
| 1,632,704,604,000
| 1,632,706,366,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 37,539
|
lean
|
/- This file is generated automatically. -/
import algebra.field_power
notation `offset_size` := 2^16
notation `half_offset_size` := 2^15
/- data available to verifier -/
structure input_data (F : Type*) :=
(trace_length : nat)
(initial_ap : nat)
(initial_pc : nat)
(final_ap : nat)
(final_pc : nat)
(m_star : F → option F)
structure public_data (F : Type*) :=
(memory__multi_column_perm__perm__interaction_elm : F)
(memory__multi_column_perm__hash_interaction_elm0 : F)
(memory__multi_column_perm__perm__public_memory_prod : F)
(rc16__perm__interaction_elm : F)
(rc16__perm__public_memory_prod : F)
(rc_min : nat)
(rc_max : nat)
(initial_rc_addr : nat)
(pedersen__points__x : F)
(pedersen__points__y : F)
(pedersen__shift_point_x : F)
(pedersen__shift_point_y : F)
(initial_pedersen_addr : nat)
(ecdsa__sig_config_alpha : F)
(ecdsa__sig_config_beta : F)
(ecdsa__generator_points__x : F)
(ecdsa__generator_points__y : F)
(ecdsa__sig_config_shift_point_x : F)
(ecdsa__sig_config_shift_point_y : F)
(initial_ecdsa_addr : F)
(initial_checkpoints_addr : F)
(final_checkpoints_addr : F)
/- prover's data -/
def column (F : Type*) := nat → F
def column.off {F : Type*} (c : column F) (i j : nat) := c (i + j)
structure columns (F : Type*) :=
(column0 : column F)
(column1 : column F)
(column2 : column F)
(column3 : column F)
(column4 : column F)
(column5 : column F)
(column6 : column F)
(column7 : column F)
(column8 : column F)
(column9 : column F)
(column10 : column F)
(column11 : column F)
(column12 : column F)
(column13 : column F)
(column14 : column F)
(column15 : column F)
(column16 : column F)
(column17 : column F)
(column18 : column F)
(column19 : column F)
(column20 : column F)
(column21 : column F)
(column22 : column F)
structure columns_inter (F : Type*) :=
(column23_inter1 : column F)
(column24_inter1 : column F)
/- accessors -/
namespace columns
variables {F : Type*} (c : columns F) (i : nat)
@[simp] def rc16_pool := c.column0.off i 0
@[simp] def cpu__decode__opcode_rc__column := c.column1.off i 0
@[simp] def rc16__sorted := c.column2.off i 0
@[simp] def pedersen__hash0__ec_subset_sum__partial_sum__x := c.column3.off i 0
@[simp] def pedersen__hash0__ec_subset_sum__partial_sum__y := c.column4.off i 0
@[simp] def pedersen__hash0__ec_subset_sum__slope := c.column5.off i 0
@[simp] def pedersen__hash0__ec_subset_sum__selector := c.column6.off i 0
@[simp] def pedersen__hash1__ec_subset_sum__partial_sum__x := c.column7.off i 0
@[simp] def pedersen__hash1__ec_subset_sum__partial_sum__y := c.column8.off i 0
@[simp] def pedersen__hash1__ec_subset_sum__slope := c.column9.off i 0
@[simp] def pedersen__hash1__ec_subset_sum__selector := c.column10.off i 0
@[simp] def pedersen__hash2__ec_subset_sum__partial_sum__x := c.column11.off i 0
@[simp] def pedersen__hash2__ec_subset_sum__partial_sum__y := c.column12.off i 0
@[simp] def pedersen__hash2__ec_subset_sum__slope := c.column13.off i 0
@[simp] def pedersen__hash2__ec_subset_sum__selector := c.column14.off i 0
@[simp] def pedersen__hash3__ec_subset_sum__partial_sum__x := c.column15.off i 0
@[simp] def pedersen__hash3__ec_subset_sum__partial_sum__y := c.column16.off i 0
@[simp] def pedersen__hash3__ec_subset_sum__slope := c.column17.off i 0
@[simp] def pedersen__hash3__ec_subset_sum__selector := c.column18.off i 0
@[simp] def mem_pool__addr := c.column19.off i 0
@[simp] def mem_pool__value := c.column19.off i 1
@[simp] def memory__sorted__addr := c.column20.off i 0
@[simp] def memory__sorted__value := c.column20.off i 1
@[simp] def cpu__registers__ap := c.column21.off i 0
@[simp] def cpu__registers__fp := c.column21.off i 8
@[simp] def cpu__operands__ops_mul := c.column21.off i 4
@[simp] def cpu__operands__res := c.column21.off i 12
@[simp] def cpu__update_registers__update_pc__tmp0 := c.column21.off i 2
@[simp] def cpu__update_registers__update_pc__tmp1 := c.column21.off i 10
@[simp] def ecdsa__signature0__key_points__x := c.column21.off i 6
@[simp] def ecdsa__signature0__key_points__y := c.column21.off i 14
@[simp] def ecdsa__signature0__doubling_slope := c.column21.off i 1
@[simp] def ecdsa__signature0__exponentiate_key__partial_sum__x := c.column21.off i 9
@[simp] def ecdsa__signature0__exponentiate_key__partial_sum__y := c.column21.off i 5
@[simp] def ecdsa__signature0__exponentiate_key__slope := c.column21.off i 13
@[simp] def ecdsa__signature0__exponentiate_key__selector := c.column21.off i 3
@[simp] def ecdsa__signature0__exponentiate_key__x_diff_inv := c.column21.off i 11
@[simp] def ecdsa__signature0__exponentiate_generator__partial_sum__x := c.column21.off i 7
@[simp] def ecdsa__signature0__exponentiate_generator__partial_sum__y := c.column21.off i 23
@[simp] def ecdsa__signature0__exponentiate_generator__slope := c.column21.off i 15
@[simp] def ecdsa__signature0__exponentiate_generator__selector := c.column21.off i 31
@[simp] def ecdsa__signature0__exponentiate_generator__x_diff_inv := c.column22.off i 0
@[simp] def ecdsa__signature0__r_w_inv := c.column21.off i 4091
@[simp] def ecdsa__signature0__add_results_slope := c.column22.off i 8160
@[simp] def ecdsa__signature0__add_results_inv := c.column21.off i 8175
@[simp] def ecdsa__signature0__extract_r_slope := c.column21.off i 4093
@[simp] def ecdsa__signature0__extract_r_inv := c.column21.off i 8189
@[simp] def ecdsa__signature0__z_inv := c.column21.off i 4081
@[simp] def ecdsa__signature0__q_x_squared := c.column21.off i 8177
@[simp] def cpu__decode__mem_inst__addr := c.column19.off i 0
@[simp] def cpu__decode__mem_inst__value := c.column19.off i 1
@[simp] def cpu__decode__pc := c.column19.off i 0
@[simp] def cpu__decode__instruction := c.column19.off i 1
@[simp] def cpu__decode__off0 := c.column0.off i 0
@[simp] def cpu__decode__off1 := c.column0.off i 8
@[simp] def cpu__decode__off2 := c.column0.off i 4
@[simp] def cpu__operands__mem_dst__addr := c.column19.off i 8
@[simp] def cpu__operands__mem_dst__value := c.column19.off i 9
@[simp] def cpu__operands__mem_op0__addr := c.column19.off i 4
@[simp] def cpu__operands__mem_op0__value := c.column19.off i 5
@[simp] def cpu__operands__mem_op1__addr := c.column19.off i 12
@[simp] def cpu__operands__mem_op1__value := c.column19.off i 13
@[simp] def orig__public_memory__addr := c.column19.off i 2
@[simp] def orig__public_memory__value := c.column19.off i 3
@[simp] def pedersen__input0__addr := c.column19.off i 6
@[simp] def pedersen__input0__value := c.column19.off i 7
@[simp] def pedersen__input1__addr := c.column19.off i 70
@[simp] def pedersen__input1__value := c.column19.off i 71
@[simp] def pedersen__output__addr := c.column19.off i 38
@[simp] def pedersen__output__value := c.column19.off i 39
@[simp] def rc_builtin__mem__addr := c.column19.off i 102
@[simp] def rc_builtin__mem__value := c.column19.off i 103
@[simp] def rc_builtin__inner_rc := c.column0.off i 12
@[simp] def ecdsa__pubkey__addr := c.column19.off i 22
@[simp] def ecdsa__pubkey__value := c.column19.off i 23
@[simp] def ecdsa__message__addr := c.column19.off i 4118
@[simp] def ecdsa__message__value := c.column19.off i 4119
@[simp] def checkpoints__req_pc__addr := c.column19.off i 150
@[simp] def checkpoints__req_pc__value := c.column19.off i 151
@[simp] def checkpoints__req_fp__addr := c.column19.off i 86
@[simp] def checkpoints__req_fp__value := c.column19.off i 87
end columns
namespace columns_inter
variables {F : Type*} (ci : columns_inter F) (i : nat)
@[simp] def rc16__perm__cum_prod0 := ci.column23_inter1.off i 0
@[simp] def memory__multi_column_perm__perm__cum_prod0 := ci.column24_inter1.off i 0
end columns_inter
/- constraints -/
variables {F: Type*} [field F]
structure cpu__decode (c : columns F) : Prop :=
(opcode_rc__bit : ∀ i: nat, (¬ ((i % 16 = 15))) → (c.column1.off i 0 - (c.column1.off i 1 + c.column1.off i 1)) * (c.column1.off i 0 - (c.column1.off i 1 + c.column1.off i 1)) - (c.column1.off i 0 - (c.column1.off i 1 + c.column1.off i 1)) = 0)
(opcode_rc__zero : ∀ i: nat, (((i % 16 = 15))) → c.column1.off i 0 = 0)
(opcode_rc_input : ∀ i: nat, (((i % 16 = 0))) → c.column19.off i 1 - (((c.column1.off i 0 * 2^16 + c.column0.off i 4) * offset_size + c.column0.off i 8) * offset_size + c.column0.off i 0) = 0)
structure cpu__operands (c : columns F) : Prop :=
(mem_dst_addr : ∀ i: nat, (((i % 16 = 0))) → c.column19.off i 8 + half_offset_size - ((c.column1.off i 0 - (c.column1.off i 1 + c.column1.off i 1)) * c.column21.off i 8 + (1 - (c.column1.off i 0 - (c.column1.off i 1 + c.column1.off i 1))) * c.column21.off i 0 + c.column0.off i 0) = 0)
(mem0_addr : ∀ i: nat, (((i % 16 = 0))) → c.column19.off i 4 + half_offset_size - ((c.column1.off i 1 - (c.column1.off i 2 + c.column1.off i 2)) * c.column21.off i 8 + (1 - (c.column1.off i 1 - (c.column1.off i 2 + c.column1.off i 2))) * c.column21.off i 0 + c.column0.off i 8) = 0)
(mem1_addr : ∀ i: nat, (((i % 16 = 0))) → c.column19.off i 12 + half_offset_size - ((c.column1.off i 2 - (c.column1.off i 3 + c.column1.off i 3)) * c.column19.off i 0 + (c.column1.off i 4 - (c.column1.off i 5 + c.column1.off i 5)) * c.column21.off i 0 + (c.column1.off i 3 - (c.column1.off i 4 + c.column1.off i 4)) * c.column21.off i 8 + (1 - (c.column1.off i 2 - (c.column1.off i 3 + c.column1.off i 3) + c.column1.off i 4 - (c.column1.off i 5 + c.column1.off i 5) + c.column1.off i 3 - (c.column1.off i 4 + c.column1.off i 4))) * c.column19.off i 5 + c.column0.off i 4) = 0)
(ops_mul : ∀ i: nat, (((i % 16 = 0))) → c.column21.off i 4 - c.column19.off i 5 * c.column19.off i 13 = 0)
(res : ∀ i: nat, (((i % 16 = 0))) → (1 - (c.column1.off i 9 - (c.column1.off i 10 + c.column1.off i 10))) * c.column21.off i 12 - ((c.column1.off i 5 - (c.column1.off i 6 + c.column1.off i 6)) * (c.column19.off i 5 + c.column19.off i 13) + (c.column1.off i 6 - (c.column1.off i 7 + c.column1.off i 7)) * c.column21.off i 4 + (1 - (c.column1.off i 5 - (c.column1.off i 6 + c.column1.off i 6) + c.column1.off i 6 - (c.column1.off i 7 + c.column1.off i 7) + c.column1.off i 9 - (c.column1.off i 10 + c.column1.off i 10))) * c.column19.off i 13) = 0)
structure cpu__update_registers (c : columns F) (inp : input_data F) : Prop :=
(update_pc__tmp0 : ∀ i: nat, (((i % 16 = 0)) ∧ ¬ (i = 16 * (inp.trace_length / 16 - 1))) → c.column21.off i 2 - (c.column1.off i 9 - (c.column1.off i 10 + c.column1.off i 10)) * c.column19.off i 9 = 0)
(update_pc__tmp1 : ∀ i: nat, (((i % 16 = 0)) ∧ ¬ (i = 16 * (inp.trace_length / 16 - 1))) → c.column21.off i 10 - c.column21.off i 2 * c.column21.off i 12 = 0)
(update_pc__pc_cond_negative : ∀ i: nat, (((i % 16 = 0)) ∧ ¬ (i = 16 * (inp.trace_length / 16 - 1))) → (1 - (c.column1.off i 9 - (c.column1.off i 10 + c.column1.off i 10))) * c.column19.off i 16 + c.column21.off i 2 * (c.column19.off i 16 - (c.column19.off i 0 + c.column19.off i 13)) - ((1 - (c.column1.off i 7 - (c.column1.off i 8 + c.column1.off i 8) + c.column1.off i 8 - (c.column1.off i 9 + c.column1.off i 9) + c.column1.off i 9 - (c.column1.off i 10 + c.column1.off i 10))) * (c.column19.off i 0 + c.column1.off i 2 - (c.column1.off i 3 + c.column1.off i 3) + 1) + (c.column1.off i 7 - (c.column1.off i 8 + c.column1.off i 8)) * c.column21.off i 12 + (c.column1.off i 8 - (c.column1.off i 9 + c.column1.off i 9)) * (c.column19.off i 0 + c.column21.off i 12)) = 0)
(update_pc__pc_cond_positive : ∀ i: nat, (((i % 16 = 0)) ∧ ¬ (i = 16 * (inp.trace_length / 16 - 1))) → (c.column21.off i 10 - (c.column1.off i 9 - (c.column1.off i 10 + c.column1.off i 10))) * (c.column19.off i 16 - (c.column19.off i 0 + c.column1.off i 2 - (c.column1.off i 3 + c.column1.off i 3) + 1)) = 0)
(update_ap__ap_update : ∀ i: nat, (((i % 16 = 0)) ∧ ¬ (i = 16 * (inp.trace_length / 16 - 1))) → c.column21.off i 16 - (c.column21.off i 0 + (c.column1.off i 10 - (c.column1.off i 11 + c.column1.off i 11)) * c.column21.off i 12 + c.column1.off i 11 - (c.column1.off i 12 + c.column1.off i 12) + (c.column1.off i 12 - (c.column1.off i 13 + c.column1.off i 13)) * 2) = 0)
(update_fp__fp_update : ∀ i: nat, (((i % 16 = 0)) ∧ ¬ (i = 16 * (inp.trace_length / 16 - 1))) → c.column21.off i 24 - ((1 - (c.column1.off i 12 - (c.column1.off i 13 + c.column1.off i 13) + c.column1.off i 13 - (c.column1.off i 14 + c.column1.off i 14))) * c.column21.off i 8 + (c.column1.off i 13 - (c.column1.off i 14 + c.column1.off i 14)) * c.column19.off i 9 + (c.column1.off i 12 - (c.column1.off i 13 + c.column1.off i 13)) * (c.column21.off i 0 + 2)) = 0)
structure cpu__opcodes (c : columns F) : Prop :=
(call__push_fp : ∀ i: nat, (((i % 16 = 0))) → (c.column1.off i 12 - (c.column1.off i 13 + c.column1.off i 13)) * (c.column19.off i 9 - c.column21.off i 8) = 0)
(call__push_pc : ∀ i: nat, (((i % 16 = 0))) → (c.column1.off i 12 - (c.column1.off i 13 + c.column1.off i 13)) * (c.column19.off i 5 - (c.column19.off i 0 + c.column1.off i 2 - (c.column1.off i 3 + c.column1.off i 3) + 1)) = 0)
(assert_eq__assert_eq : ∀ i: nat, (((i % 16 = 0))) → (c.column1.off i 14 - (c.column1.off i 15 + c.column1.off i 15)) * (c.column19.off i 9 - c.column21.off i 12) = 0)
structure initial_and_final (inp : input_data F) (c : columns F) : Prop :=
(initial_ap : ∀ i: nat, ((i = 0)) → c.column21.off i 0 - inp.initial_ap = 0)
(initial_fp : ∀ i: nat, ((i = 0)) → c.column21.off i 8 - inp.initial_ap = 0)
(initial_pc : ∀ i: nat, ((i = 0)) → c.column19.off i 0 - inp.initial_pc = 0)
(final_ap : ∀ i: nat, ((i = 16 * (inp.trace_length / 16 - 1))) → c.column21.off i 0 - inp.final_ap = 0)
(final_pc : ∀ i: nat, ((i = 16 * (inp.trace_length / 16 - 1))) → c.column19.off i 0 - inp.final_pc = 0)
structure memory (inp : input_data F) (pd : public_data F) (c : columns F) (ci : columns_inter F) : Prop :=
(multi_column_perm__perm__init0 : ∀ i: nat, ((i = 0)) → (pd.memory__multi_column_perm__perm__interaction_elm - (c.column20.off i 0 + pd.memory__multi_column_perm__hash_interaction_elm0 * c.column20.off i 1)) * ci.column24_inter1.off i 0 + c.column19.off i 0 + pd.memory__multi_column_perm__hash_interaction_elm0 * c.column19.off i 1 - pd.memory__multi_column_perm__perm__interaction_elm = 0)
(multi_column_perm__perm__step0 : ∀ i: nat, (((i % 2 = 0)) ∧ ¬ (i = 2 * (inp.trace_length / 2 - 1))) → (pd.memory__multi_column_perm__perm__interaction_elm - (c.column20.off i 2 + pd.memory__multi_column_perm__hash_interaction_elm0 * c.column20.off i 3)) * ci.column24_inter1.off i 2 - (pd.memory__multi_column_perm__perm__interaction_elm - (c.column19.off i 2 + pd.memory__multi_column_perm__hash_interaction_elm0 * c.column19.off i 3)) * ci.column24_inter1.off i 0 = 0)
(multi_column_perm__perm__last : ∀ i: nat, ((i = 2 * (inp.trace_length / 2 - 1))) → ci.column24_inter1.off i 0 - pd.memory__multi_column_perm__perm__public_memory_prod = 0)
(diff_is_bit : ∀ i: nat, (((i % 2 = 0)) ∧ ¬ (i = 2 * (inp.trace_length / 2 - 1))) → (c.column20.off i 2 - c.column20.off i 0) * (c.column20.off i 2 - c.column20.off i 0) - (c.column20.off i 2 - c.column20.off i 0) = 0)
(is_func : ∀ i: nat, (((i % 2 = 0)) ∧ ¬ (i = 2 * (inp.trace_length / 2 - 1))) → (c.column20.off i 2 - c.column20.off i 0 - 1) * (c.column20.off i 1 - c.column20.off i 3) = 0)
structure public_memory (c : columns F) : Prop :=
(memory_addr_zero : ∀ i: nat, (((i % 8 = 0))) → c.column19.off i 2 = 0)
(memory_value_zero : ∀ i: nat, (((i % 8 = 0))) → c.column19.off i 3 = 0)
structure rc16 (inp : input_data F) (pd : public_data F) (c : columns F) (ci : columns_inter F): Prop :=
(perm__init0 : ∀ i: nat, ((i = 0)) → (pd.rc16__perm__interaction_elm - c.column2.off i 0) * ci.column23_inter1.off i 0 + c.column0.off i 0 - pd.rc16__perm__interaction_elm = 0)
(perm__step0 : ∀ i: nat, (¬ (i = inp.trace_length - 1)) → (pd.rc16__perm__interaction_elm - c.column2.off i 1) * ci.column23_inter1.off i 1 - (pd.rc16__perm__interaction_elm - c.column0.off i 1) * ci.column23_inter1.off i 0 = 0)
(perm__last : ∀ i: nat, ((i = inp.trace_length - 1)) → ci.column23_inter1.off i 0 - pd.rc16__perm__public_memory_prod = 0)
(diff_is_bit : ∀ i: nat, (¬ (i = inp.trace_length - 1)) → (c.column2.off i 1 - c.column2.off i 0) * (c.column2.off i 1 - c.column2.off i 0) - (c.column2.off i 1 - c.column2.off i 0) = 0)
(minimum : ∀ i: nat, ((i = 0)) → c.column2.off i 0 - pd.rc_min = 0)
(maximum : ∀ i: nat, ((i = inp.trace_length - 1)) → c.column2.off i 0 - pd.rc_max = 0)
structure rc_builtin (inp : input_data F) (pd : public_data F) (c : columns F) : Prop :=
(value : ∀ i: nat, (((i % 128 = 0))) → ((((((c.column0.off i 12 * offset_size + c.column0.off i 28) * offset_size + c.column0.off i 44) * offset_size + c.column0.off i 60) * offset_size + c.column0.off i 76) * offset_size + c.column0.off i 92) * offset_size + c.column0.off i 108) * offset_size + c.column0.off i 124 - c.column19.off i 103 = 0)
(addr_step : ∀ i: nat, (((i % 128 = 0)) ∧ ¬ (i = 128 * (inp.trace_length / 128 - 1))) → c.column19.off i 230 - (c.column19.off i 102 + 1) = 0)
(init_addr : ∀ i: nat, ((i = 0)) → c.column19.off i 102 - pd.initial_rc_addr = 0)
structure pedersen (inp : input_data F) (pd : public_data F) (c : columns F) : Prop :=
(pedersen__hash0__ec_subset_sum__booleanity_test : ∀ i: nat, (¬ ((i % 256 = 255))) → (c.column6.off i 0 - (c.column6.off i 1 + c.column6.off i 1)) * (c.column6.off i 0 - (c.column6.off i 1 + c.column6.off i 1) - 1) = 0)
(pedersen__hash0__ec_subset_sum__bit_extraction_end : ∀ i: nat, (((i % 256 = 252))) → c.column6.off i 0 = 0)
(pedersen__hash0__ec_subset_sum__zeros_tail : ∀ i: nat, (((i % 256 = 255))) → c.column6.off i 0 = 0)
(pedersen__hash0__ec_subset_sum__add_points__slope : ∀ i: nat, (¬ ((i % 256 = 255))) → (c.column6.off i 0 - (c.column6.off i 1 + c.column6.off i 1)) * (c.column4.off i 0 - pd.pedersen__points__y) - c.column5.off i 0 * (c.column3.off i 0 - pd.pedersen__points__x) = 0)
(pedersen__hash0__ec_subset_sum__add_points__x : ∀ i: nat, (¬ ((i % 256 = 255))) → c.column5.off i 0 * c.column5.off i 0 - (c.column6.off i 0 - (c.column6.off i 1 + c.column6.off i 1)) * (c.column3.off i 0 + pd.pedersen__points__x + c.column3.off i 1) = 0)
(pedersen__hash0__ec_subset_sum__add_points__y : ∀ i: nat, (¬ ((i % 256 = 255))) → (c.column6.off i 0 - (c.column6.off i 1 + c.column6.off i 1)) * (c.column4.off i 0 + c.column4.off i 1) - c.column5.off i 0 * (c.column3.off i 0 - c.column3.off i 1) = 0)
(pedersen__hash0__ec_subset_sum__copy_point__x : ∀ i: nat, (¬ ((i % 256 = 255))) → (1 - (c.column6.off i 0 - (c.column6.off i 1 + c.column6.off i 1))) * (c.column3.off i 1 - c.column3.off i 0) = 0)
(pedersen__hash0__ec_subset_sum__copy_point__y : ∀ i: nat, (¬ ((i % 256 = 255))) → (1 - (c.column6.off i 0 - (c.column6.off i 1 + c.column6.off i 1))) * (c.column4.off i 1 - c.column4.off i 0) = 0)
(pedersen__hash0__copy_point__x : ∀ i: nat, (((i % 256 = 0)) ∧ ¬ ((i % 512 = 256))) → c.column3.off i 256 - c.column3.off i 255 = 0)
(pedersen__hash0__copy_point__y : ∀ i: nat, (((i % 256 = 0)) ∧ ¬ ((i % 512 = 256))) → c.column4.off i 256 - c.column4.off i 255 = 0)
(pedersen__hash0__init__x : ∀ i: nat, (((i % 512 = 0))) → c.column3.off i 0 - pd.pedersen__shift_point_x = 0)
(pedersen__hash0__init__y : ∀ i: nat, (((i % 512 = 0))) → c.column4.off i 0 - pd.pedersen__shift_point_y = 0)
(pedersen__hash1__ec_subset_sum__booleanity_test : ∀ i: nat, (¬ ((i % 256 = 255))) → (c.column10.off i 0 - (c.column10.off i 1 + c.column10.off i 1)) * (c.column10.off i 0 - (c.column10.off i 1 + c.column10.off i 1) - 1) = 0)
(pedersen__hash1__ec_subset_sum__bit_extraction_end : ∀ i: nat, (((i % 256 = 252))) → c.column10.off i 0 = 0)
(pedersen__hash1__ec_subset_sum__zeros_tail : ∀ i: nat, (((i % 256 = 255))) → c.column10.off i 0 = 0)
(pedersen__hash1__ec_subset_sum__add_points__slope : ∀ i: nat, (¬ ((i % 256 = 255))) → (c.column10.off i 0 - (c.column10.off i 1 + c.column10.off i 1)) * (c.column8.off i 0 - pd.pedersen__points__y) - c.column9.off i 0 * (c.column7.off i 0 - pd.pedersen__points__x) = 0)
(pedersen__hash1__ec_subset_sum__add_points__x : ∀ i: nat, (¬ ((i % 256 = 255))) → c.column9.off i 0 * c.column9.off i 0 - (c.column10.off i 0 - (c.column10.off i 1 + c.column10.off i 1)) * (c.column7.off i 0 + pd.pedersen__points__x + c.column7.off i 1) = 0)
(pedersen__hash1__ec_subset_sum__add_points__y : ∀ i: nat, (¬ ((i % 256 = 255))) → (c.column10.off i 0 - (c.column10.off i 1 + c.column10.off i 1)) * (c.column8.off i 0 + c.column8.off i 1) - c.column9.off i 0 * (c.column7.off i 0 - c.column7.off i 1) = 0)
(pedersen__hash1__ec_subset_sum__copy_point__x : ∀ i: nat, (¬ ((i % 256 = 255))) → (1 - (c.column10.off i 0 - (c.column10.off i 1 + c.column10.off i 1))) * (c.column7.off i 1 - c.column7.off i 0) = 0)
(pedersen__hash1__ec_subset_sum__copy_point__y : ∀ i: nat, (¬ ((i % 256 = 255))) → (1 - (c.column10.off i 0 - (c.column10.off i 1 + c.column10.off i 1))) * (c.column8.off i 1 - c.column8.off i 0) = 0)
(pedersen__hash1__copy_point__x : ∀ i: nat, (((i % 256 = 0)) ∧ ¬ ((i % 512 = 256))) → c.column7.off i 256 - c.column7.off i 255 = 0)
(pedersen__hash1__copy_point__y : ∀ i: nat, (((i % 256 = 0)) ∧ ¬ ((i % 512 = 256))) → c.column8.off i 256 - c.column8.off i 255 = 0)
(pedersen__hash1__init__x : ∀ i: nat, (((i % 512 = 0))) → c.column7.off i 0 - pd.pedersen__shift_point_x = 0)
(pedersen__hash1__init__y : ∀ i: nat, (((i % 512 = 0))) → c.column8.off i 0 - pd.pedersen__shift_point_y = 0)
(pedersen__hash2__ec_subset_sum__booleanity_test : ∀ i: nat, (¬ ((i % 256 = 255))) → (c.column14.off i 0 - (c.column14.off i 1 + c.column14.off i 1)) * (c.column14.off i 0 - (c.column14.off i 1 + c.column14.off i 1) - 1) = 0)
(pedersen__hash2__ec_subset_sum__bit_extraction_end : ∀ i: nat, (((i % 256 = 252))) → c.column14.off i 0 = 0)
(pedersen__hash2__ec_subset_sum__zeros_tail : ∀ i: nat, (((i % 256 = 255))) → c.column14.off i 0 = 0)
(pedersen__hash2__ec_subset_sum__add_points__slope : ∀ i: nat, (¬ ((i % 256 = 255))) → (c.column14.off i 0 - (c.column14.off i 1 + c.column14.off i 1)) * (c.column12.off i 0 - pd.pedersen__points__y) - c.column13.off i 0 * (c.column11.off i 0 - pd.pedersen__points__x) = 0)
(pedersen__hash2__ec_subset_sum__add_points__x : ∀ i: nat, (¬ ((i % 256 = 255))) → c.column13.off i 0 * c.column13.off i 0 - (c.column14.off i 0 - (c.column14.off i 1 + c.column14.off i 1)) * (c.column11.off i 0 + pd.pedersen__points__x + c.column11.off i 1) = 0)
(pedersen__hash2__ec_subset_sum__add_points__y : ∀ i: nat, (¬ ((i % 256 = 255))) → (c.column14.off i 0 - (c.column14.off i 1 + c.column14.off i 1)) * (c.column12.off i 0 + c.column12.off i 1) - c.column13.off i 0 * (c.column11.off i 0 - c.column11.off i 1) = 0)
(pedersen__hash2__ec_subset_sum__copy_point__x : ∀ i: nat, (¬ ((i % 256 = 255))) → (1 - (c.column14.off i 0 - (c.column14.off i 1 + c.column14.off i 1))) * (c.column11.off i 1 - c.column11.off i 0) = 0)
(pedersen__hash2__ec_subset_sum__copy_point__y : ∀ i: nat, (¬ ((i % 256 = 255))) → (1 - (c.column14.off i 0 - (c.column14.off i 1 + c.column14.off i 1))) * (c.column12.off i 1 - c.column12.off i 0) = 0)
(pedersen__hash2__copy_point__x : ∀ i: nat, (((i % 256 = 0)) ∧ ¬ ((i % 512 = 256))) → c.column11.off i 256 - c.column11.off i 255 = 0)
(pedersen__hash2__copy_point__y : ∀ i: nat, (((i % 256 = 0)) ∧ ¬ ((i % 512 = 256))) → c.column12.off i 256 - c.column12.off i 255 = 0)
(pedersen__hash2__init__x : ∀ i: nat, (((i % 512 = 0))) → c.column11.off i 0 - pd.pedersen__shift_point_x = 0)
(pedersen__hash2__init__y : ∀ i: nat, (((i % 512 = 0))) → c.column12.off i 0 - pd.pedersen__shift_point_y = 0)
(pedersen__hash3__ec_subset_sum__booleanity_test : ∀ i: nat, (¬ ((i % 256 = 255))) → (c.column18.off i 0 - (c.column18.off i 1 + c.column18.off i 1)) * (c.column18.off i 0 - (c.column18.off i 1 + c.column18.off i 1) - 1) = 0)
(pedersen__hash3__ec_subset_sum__bit_extraction_end : ∀ i: nat, (((i % 256 = 252))) → c.column18.off i 0 = 0)
(pedersen__hash3__ec_subset_sum__zeros_tail : ∀ i: nat, (((i % 256 = 255))) → c.column18.off i 0 = 0)
(pedersen__hash3__ec_subset_sum__add_points__slope : ∀ i: nat, (¬ ((i % 256 = 255))) → (c.column18.off i 0 - (c.column18.off i 1 + c.column18.off i 1)) * (c.column16.off i 0 - pd.pedersen__points__y) - c.column17.off i 0 * (c.column15.off i 0 - pd.pedersen__points__x) = 0)
(pedersen__hash3__ec_subset_sum__add_points__x : ∀ i: nat, (¬ ((i % 256 = 255))) → c.column17.off i 0 * c.column17.off i 0 - (c.column18.off i 0 - (c.column18.off i 1 + c.column18.off i 1)) * (c.column15.off i 0 + pd.pedersen__points__x + c.column15.off i 1) = 0)
(pedersen__hash3__ec_subset_sum__add_points__y : ∀ i: nat, (¬ ((i % 256 = 255))) → (c.column18.off i 0 - (c.column18.off i 1 + c.column18.off i 1)) * (c.column16.off i 0 + c.column16.off i 1) - c.column17.off i 0 * (c.column15.off i 0 - c.column15.off i 1) = 0)
(pedersen__hash3__ec_subset_sum__copy_point__x : ∀ i: nat, (¬ ((i % 256 = 255))) → (1 - (c.column18.off i 0 - (c.column18.off i 1 + c.column18.off i 1))) * (c.column15.off i 1 - c.column15.off i 0) = 0)
(pedersen__hash3__ec_subset_sum__copy_point__y : ∀ i: nat, (¬ ((i % 256 = 255))) → (1 - (c.column18.off i 0 - (c.column18.off i 1 + c.column18.off i 1))) * (c.column16.off i 1 - c.column16.off i 0) = 0)
(pedersen__hash3__copy_point__x : ∀ i: nat, (((i % 256 = 0)) ∧ ¬ ((i % 512 = 256))) → c.column15.off i 256 - c.column15.off i 255 = 0)
(pedersen__hash3__copy_point__y : ∀ i: nat, (((i % 256 = 0)) ∧ ¬ ((i % 512 = 256))) → c.column16.off i 256 - c.column16.off i 255 = 0)
(pedersen__hash3__init__x : ∀ i: nat, (((i % 512 = 0))) → c.column15.off i 0 - pd.pedersen__shift_point_x = 0)
(pedersen__hash3__init__y : ∀ i: nat, (((i % 512 = 0))) → c.column16.off i 0 - pd.pedersen__shift_point_y = 0)
(pedersen__input0_value0 : ∀ i: nat, (((i % 512 = 0))) → c.column19.off i 7 - c.column6.off i 0 = 0)
(pedersen__input0_value1 : ∀ i: nat, (((i % 512 = 0))) → c.column19.off i 135 - c.column10.off i 0 = 0)
(pedersen__input0_value2 : ∀ i: nat, (((i % 512 = 0))) → c.column19.off i 263 - c.column14.off i 0 = 0)
(pedersen__input0_value3 : ∀ i: nat, (((i % 512 = 0))) → c.column19.off i 391 - c.column18.off i 0 = 0)
(pedersen__input0_addr : ∀ i: nat, (((i % 128 = 0)) ∧ ¬ (i = 128 * (inp.trace_length / 128 - 1))) → c.column19.off i 134 - (c.column19.off i 38 + 1) = 0)
(pedersen__init_addr : ∀ i: nat, ((i = 0)) → c.column19.off i 6 - pd.initial_pedersen_addr = 0)
(pedersen__input1_value0 : ∀ i: nat, (((i % 512 = 0))) → c.column19.off i 71 - c.column6.off i 256 = 0)
(pedersen__input1_value1 : ∀ i: nat, (((i % 512 = 0))) → c.column19.off i 199 - c.column10.off i 256 = 0)
(pedersen__input1_value2 : ∀ i: nat, (((i % 512 = 0))) → c.column19.off i 327 - c.column14.off i 256 = 0)
(pedersen__input1_value3 : ∀ i: nat, (((i % 512 = 0))) → c.column19.off i 455 - c.column18.off i 256 = 0)
(pedersen__input1_addr : ∀ i: nat, (((i % 128 = 0))) → c.column19.off i 70 - (c.column19.off i 6 + 1) = 0)
(pedersen__output_value0 : ∀ i: nat, (((i % 512 = 0))) → c.column19.off i 39 - c.column3.off i 511 = 0)
(pedersen__output_value1 : ∀ i: nat, (((i % 512 = 0))) → c.column19.off i 167 - c.column7.off i 511 = 0)
(pedersen__output_value2 : ∀ i: nat, (((i % 512 = 0))) → c.column19.off i 295 - c.column11.off i 511 = 0)
(pedersen__output_value3 : ∀ i: nat, (((i % 512 = 0))) → c.column19.off i 423 - c.column15.off i 511 = 0)
(pedersen__output_addr : ∀ i: nat, (((i % 128 = 0))) → c.column19.off i 38 - (c.column19.off i 70 + 1) = 0)
structure ecdsa (inp : input_data F) (pd : public_data F) (c : columns F) : Prop :=
(ecdsa__signature0__doubling_key__slope : ∀ i: nat, (((i % 16 = 0)) ∧ ¬ ((i % 4096 = 4080))) → c.column21.off i 6 * c.column21.off i 6 + c.column21.off i 6 * c.column21.off i 6 + c.column21.off i 6 * c.column21.off i 6 + pd.ecdsa__sig_config_alpha - (c.column21.off i 14 + c.column21.off i 14) * c.column21.off i 1 = 0)
(ecdsa__signature0__doubling_key__x : ∀ i: nat, (((i % 16 = 0)) ∧ ¬ ((i % 4096 = 4080))) → c.column21.off i 1 * c.column21.off i 1 - (c.column21.off i 6 + c.column21.off i 6 + c.column21.off i 22) = 0)
(ecdsa__signature0__doubling_key__y : ∀ i: nat, (((i % 16 = 0)) ∧ ¬ ((i % 4096 = 4080))) → c.column21.off i 14 + c.column21.off i 30 - c.column21.off i 1 * (c.column21.off i 6 - c.column21.off i 22) = 0)
(ecdsa__signature0__exponentiate_generator__booleanity_test : ∀ i: nat, (((i % 32 = 0)) ∧ ¬ ((i % 8192 = 8160))) → (c.column21.off i 31 - (c.column21.off i 63 + c.column21.off i 63)) * (c.column21.off i 31 - (c.column21.off i 63 + c.column21.off i 63) - 1) = 0)
(ecdsa__signature0__exponentiate_generator__bit_extraction_end : ∀ i: nat, (((i % 8192 = 8032))) → c.column21.off i 31 = 0)
(ecdsa__signature0__exponentiate_generator__zeros_tail : ∀ i: nat, (((i % 8192 = 8160))) → c.column21.off i 31 = 0)
(ecdsa__signature0__exponentiate_generator__add_points__slope : ∀ i: nat, (((i % 32 = 0)) ∧ ¬ ((i % 8192 = 8160))) → (c.column21.off i 31 - (c.column21.off i 63 + c.column21.off i 63)) * (c.column21.off i 23 - pd.ecdsa__generator_points__y) - c.column21.off i 15 * (c.column21.off i 7 - pd.ecdsa__generator_points__x) = 0)
(ecdsa__signature0__exponentiate_generator__add_points__x : ∀ i: nat, (((i % 32 = 0)) ∧ ¬ ((i % 8192 = 8160))) → c.column21.off i 15 * c.column21.off i 15 - (c.column21.off i 31 - (c.column21.off i 63 + c.column21.off i 63)) * (c.column21.off i 7 + pd.ecdsa__generator_points__x + c.column21.off i 39) = 0)
(ecdsa__signature0__exponentiate_generator__add_points__y : ∀ i: nat, (((i % 32 = 0)) ∧ ¬ ((i % 8192 = 8160))) → (c.column21.off i 31 - (c.column21.off i 63 + c.column21.off i 63)) * (c.column21.off i 23 + c.column21.off i 55) - c.column21.off i 15 * (c.column21.off i 7 - c.column21.off i 39) = 0)
(ecdsa__signature0__exponentiate_generator__add_points__x_diff_inv : ∀ i: nat, (((i % 32 = 0)) ∧ ¬ ((i % 8192 = 8160))) → c.column22.off i 0 * (c.column21.off i 7 - pd.ecdsa__generator_points__x) - 1 = 0)
(ecdsa__signature0__exponentiate_generator__copy_point__x : ∀ i: nat, (((i % 32 = 0)) ∧ ¬ ((i % 8192 = 8160))) → (1 - (c.column21.off i 31 - (c.column21.off i 63 + c.column21.off i 63))) * (c.column21.off i 39 - c.column21.off i 7) = 0)
(ecdsa__signature0__exponentiate_generator__copy_point__y : ∀ i: nat, (((i % 32 = 0)) ∧ ¬ ((i % 8192 = 8160))) → (1 - (c.column21.off i 31 - (c.column21.off i 63 + c.column21.off i 63))) * (c.column21.off i 55 - c.column21.off i 23) = 0)
(ecdsa__signature0__exponentiate_key__booleanity_test : ∀ i: nat, (((i % 16 = 0)) ∧ ¬ ((i % 4096 = 4080))) → (c.column21.off i 3 - (c.column21.off i 19 + c.column21.off i 19)) * (c.column21.off i 3 - (c.column21.off i 19 + c.column21.off i 19) - 1) = 0)
(ecdsa__signature0__exponentiate_key__bit_extraction_end : ∀ i: nat, (((i % 4096 = 4016))) → c.column21.off i 3 = 0)
(ecdsa__signature0__exponentiate_key__zeros_tail : ∀ i: nat, (((i % 4096 = 4080))) → c.column21.off i 3 = 0)
(ecdsa__signature0__exponentiate_key__add_points__slope : ∀ i: nat, (((i % 16 = 0)) ∧ ¬ ((i % 4096 = 4080))) → (c.column21.off i 3 - (c.column21.off i 19 + c.column21.off i 19)) * (c.column21.off i 5 - c.column21.off i 14) - c.column21.off i 13 * (c.column21.off i 9 - c.column21.off i 6) = 0)
(ecdsa__signature0__exponentiate_key__add_points__x : ∀ i: nat, (((i % 16 = 0)) ∧ ¬ ((i % 4096 = 4080))) → c.column21.off i 13 * c.column21.off i 13 - (c.column21.off i 3 - (c.column21.off i 19 + c.column21.off i 19)) * (c.column21.off i 9 + c.column21.off i 6 + c.column21.off i 25) = 0)
(ecdsa__signature0__exponentiate_key__add_points__y : ∀ i: nat, (((i % 16 = 0)) ∧ ¬ ((i % 4096 = 4080))) → (c.column21.off i 3 - (c.column21.off i 19 + c.column21.off i 19)) * (c.column21.off i 5 + c.column21.off i 21) - c.column21.off i 13 * (c.column21.off i 9 - c.column21.off i 25) = 0)
(ecdsa__signature0__exponentiate_key__add_points__x_diff_inv : ∀ i: nat, (((i % 16 = 0)) ∧ ¬ ((i % 4096 = 4080))) → c.column21.off i 11 * (c.column21.off i 9 - c.column21.off i 6) - 1 = 0)
(ecdsa__signature0__exponentiate_key__copy_point__x : ∀ i: nat, (((i % 16 = 0)) ∧ ¬ ((i % 4096 = 4080))) → (1 - (c.column21.off i 3 - (c.column21.off i 19 + c.column21.off i 19))) * (c.column21.off i 25 - c.column21.off i 9) = 0)
(ecdsa__signature0__exponentiate_key__copy_point__y : ∀ i: nat, (((i % 16 = 0)) ∧ ¬ ((i % 4096 = 4080))) → (1 - (c.column21.off i 3 - (c.column21.off i 19 + c.column21.off i 19))) * (c.column21.off i 21 - c.column21.off i 5) = 0)
(ecdsa__signature0__init_gen__x : ∀ i: nat, (((i % 8192 = 0))) → c.column21.off i 7 - pd.ecdsa__sig_config_shift_point_x = 0)
(ecdsa__signature0__init_gen__y : ∀ i: nat, (((i % 8192 = 0))) → c.column21.off i 23 + pd.ecdsa__sig_config_shift_point_y = 0)
(ecdsa__signature0__init_key__x : ∀ i: nat, (((i % 4096 = 0))) → c.column21.off i 9 - pd.ecdsa__sig_config_shift_point_x = 0)
(ecdsa__signature0__init_key__y : ∀ i: nat, (((i % 4096 = 0))) → c.column21.off i 5 - pd.ecdsa__sig_config_shift_point_y = 0)
(ecdsa__signature0__add_results__slope : ∀ i: nat, (((i % 8192 = 0))) → c.column21.off i 8183 - (c.column21.off i 4085 + c.column22.off i 8160 * (c.column21.off i 8167 - c.column21.off i 4089)) = 0)
(ecdsa__signature0__add_results__x : ∀ i: nat, (((i % 8192 = 0))) → c.column22.off i 8160 * c.column22.off i 8160 - (c.column21.off i 8167 + c.column21.off i 4089 + c.column21.off i 4102) = 0)
(ecdsa__signature0__add_results__y : ∀ i: nat, (((i % 8192 = 0))) → c.column21.off i 8183 + c.column21.off i 4110 - c.column22.off i 8160 * (c.column21.off i 8167 - c.column21.off i 4102) = 0)
(ecdsa__signature0__add_results__x_diff_inv : ∀ i: nat, (((i % 8192 = 0))) → c.column21.off i 8175 * (c.column21.off i 8167 - c.column21.off i 4089) - 1 = 0)
(ecdsa__signature0__extract_r__slope : ∀ i: nat, (((i % 8192 = 0))) → c.column21.off i 8181 + pd.ecdsa__sig_config_shift_point_y - c.column21.off i 4093 * (c.column21.off i 8185 - pd.ecdsa__sig_config_shift_point_x) = 0)
(ecdsa__signature0__extract_r__x : ∀ i: nat, (((i % 8192 = 0))) → c.column21.off i 4093 * c.column21.off i 4093 - (c.column21.off i 8185 + pd.ecdsa__sig_config_shift_point_x + c.column21.off i 3) = 0)
(ecdsa__signature0__extract_r__x_diff_inv : ∀ i: nat, (((i % 8192 = 0))) → c.column21.off i 8189 * (c.column21.off i 8185 - pd.ecdsa__sig_config_shift_point_x) - 1 = 0)
(ecdsa__signature0__z_nonzero : ∀ i: nat, (((i % 8192 = 0))) → c.column21.off i 31 * c.column21.off i 4081 - 1 = 0)
(ecdsa__signature0__r_and_w_nonzero : ∀ i: nat, (((i % 4096 = 0))) → c.column21.off i 3 * c.column21.off i 4091 - 1 = 0)
(ecdsa__signature0__q_on_curve__x_squared : ∀ i: nat, (((i % 8192 = 0))) → c.column21.off i 8177 - c.column21.off i 6 * c.column21.off i 6 = 0)
(ecdsa__signature0__q_on_curve__on_curve : ∀ i: nat, (((i % 8192 = 0))) → c.column21.off i 14 * c.column21.off i 14 - (c.column21.off i 6 * c.column21.off i 8177 + pd.ecdsa__sig_config_alpha * c.column21.off i 6 + pd.ecdsa__sig_config_beta) = 0)
(ecdsa__init_addr : ∀ i: nat, ((i = 0)) → c.column19.off i 22 - pd.initial_ecdsa_addr = 0)
(ecdsa__message_addr : ∀ i: nat, (((i % 8192 = 0))) → c.column19.off i 4118 - (c.column19.off i 22 + 1) = 0)
(ecdsa__pubkey_addr : ∀ i: nat, (((i % 8192 = 0)) ∧ ¬ (i = 8192 * (inp.trace_length / 8192 - 1))) → c.column19.off i 8214 - (c.column19.off i 4118 + 1) = 0)
(ecdsa__message_value0 : ∀ i: nat, (((i % 8192 = 0))) → c.column19.off i 4119 - c.column21.off i 31 = 0)
(ecdsa__pubkey_value0 : ∀ i: nat, (((i % 8192 = 0))) → c.column19.off i 23 - c.column21.off i 6 = 0)
structure checkpoints (c : columns F) (inp : input_data F) (pd : public_data F) : Prop :=
(checkpoints__req_pc_init_addr : ∀ i: nat, ((i = 0)) → c.column19.off i 150 - pd.initial_checkpoints_addr = 0)
(checkpoints__req_pc_final_addr : ∀ i: nat, ((i = 256 * (inp.trace_length / 256 - 1))) → c.column19.off i 150 - pd.final_checkpoints_addr = 0)
(checkpoints__required_fp_addr : ∀ i: nat, (((i % 256 = 0))) → c.column19.off i 86 - (c.column19.off i 150 + 1) = 0)
(checkpoints__required_pc_next_addr : ∀ i: nat, (((i % 256 = 0)) ∧ ¬ (i = 256 * (inp.trace_length / 256 - 1))) → (c.column19.off i 406 - c.column19.off i 150) * (c.column19.off i 406 - (c.column19.off i 150 + 2)) = 0)
(checkpoints__req_pc : ∀ i: nat, (((i % 256 = 0)) ∧ ¬ (i = 256 * (inp.trace_length / 256 - 1))) → (c.column19.off i 406 - c.column19.off i 150) * (c.column19.off i 151 - c.column19.off i 0) = 0)
(checkpoints__req_fp : ∀ i: nat, (((i % 256 = 0)) ∧ ¬ (i = 256 * (inp.trace_length / 256 - 1))) → (c.column19.off i 406 - c.column19.off i 150) * (c.column19.off i 87 - c.column21.off i 8) = 0)
|
91c28892583ca0e29f7f11ababd8ec6e6b6763e2
|
c777c32c8e484e195053731103c5e52af26a25d1
|
/src/ring_theory/jacobson_ideal.lean
|
0e1f0e5efbbcb4be5fd8d080c889a5b93e052061
|
[
"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
| 14,785
|
lean
|
/-
Copyright (c) 2020 Devon Tuma. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Devon Tuma
-/
import ring_theory.ideal.quotient
import ring_theory.polynomial.quotient
/-!
# Jacobson radical
The Jacobson radical of a ring `R` is defined to be the intersection of all maximal ideals of `R`.
This is similar to how the nilradical is equal to the intersection of all prime ideals of `R`.
We can extend the idea of the nilradical to ideals of `R`,
by letting the radical of an ideal `I` be the intersection of prime ideals containing `I`.
Under this extension, the original nilradical is the radical of the zero ideal `⊥`.
Here we define the Jacobson radical of an ideal `I` in a similar way,
as the intersection of maximal ideals containing `I`.
## Main definitions
Let `R` be a commutative ring, and `I` be an ideal of `R`
* `jacobson I` is the jacobson radical, i.e. the infimum of all maximal ideals containing I.
* `is_local I` is the proposition that the jacobson radical of `I` is itself a maximal ideal
## Main statements
* `mem_jacobson_iff` gives a characterization of members of the jacobson of I
* `is_local_of_is_maximal_radical`: if the radical of I is maximal then so is the jacobson radical
## Tags
Jacobson, Jacobson radical, Local Ideal
-/
universes u v
namespace ideal
variables {R : Type u} {S : Type v}
open_locale polynomial
section jacobson
section ring
variables [ring R] [ring S] {I : ideal R}
/-- The Jacobson radical of `I` is the infimum of all maximal (left) ideals containing `I`. -/
def jacobson (I : ideal R) : ideal R :=
Inf {J : ideal R | I ≤ J ∧ is_maximal J}
lemma le_jacobson : I ≤ jacobson I :=
λ x hx, mem_Inf.mpr (λ J hJ, hJ.left hx)
@[simp] lemma jacobson_idem : jacobson (jacobson I) = jacobson I :=
le_antisymm (Inf_le_Inf (λ J hJ, ⟨Inf_le hJ, hJ.2⟩)) le_jacobson
@[simp] lemma jacobson_top : jacobson (⊤ : ideal R) = ⊤ :=
eq_top_iff.2 le_jacobson
@[simp] theorem jacobson_eq_top_iff : jacobson I = ⊤ ↔ I = ⊤ :=
⟨λ H, classical.by_contradiction $ λ hi, let ⟨M, hm, him⟩ := exists_le_maximal I hi in
lt_top_iff_ne_top.1
(lt_of_le_of_lt (show jacobson I ≤ M, from Inf_le ⟨him, hm⟩) $
lt_top_iff_ne_top.2 hm.ne_top) H,
λ H, eq_top_iff.2 $ le_Inf $ λ J ⟨hij, hj⟩, H ▸ hij⟩
lemma jacobson_eq_bot : jacobson I = ⊥ → I = ⊥ :=
λ h, eq_bot_iff.mpr (h ▸ le_jacobson)
lemma jacobson_eq_self_of_is_maximal [H : is_maximal I] : I.jacobson = I :=
le_antisymm (Inf_le ⟨le_of_eq rfl, H⟩) le_jacobson
@[priority 100]
instance jacobson.is_maximal [H : is_maximal I] : is_maximal (jacobson I) :=
⟨⟨λ htop, H.1.1 (jacobson_eq_top_iff.1 htop),
λ J hJ, H.1.2 _ (lt_of_le_of_lt le_jacobson hJ)⟩⟩
theorem mem_jacobson_iff {x : R} : x ∈ jacobson I ↔ ∀ y, ∃ z, z * y * x + z - 1 ∈ I :=
⟨λ hx y, classical.by_cases
(assume hxy : I ⊔ span {y * x + 1} = ⊤,
let ⟨p, hpi, q, hq, hpq⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 hxy) in
let ⟨r, hr⟩ := mem_span_singleton'.1 hq in
⟨r, by rw [mul_assoc, ←mul_add_one, hr, ← hpq, ← neg_sub, add_sub_cancel]; exact I.neg_mem hpi⟩)
(assume hxy : I ⊔ span {y * x + 1} ≠ ⊤,
let ⟨M, hm1, hm2⟩ := exists_le_maximal _ hxy in
suffices x ∉ M, from (this $ mem_Inf.1 hx ⟨le_trans le_sup_left hm2, hm1⟩).elim,
λ hxm, hm1.1.1 $ (eq_top_iff_one _).2 $ add_sub_cancel' (y * x) 1 ▸ M.sub_mem
(le_sup_right.trans hm2 $ subset_span rfl)
(M.mul_mem_left _ hxm)),
λ hx, mem_Inf.2 $ λ M ⟨him, hm⟩, classical.by_contradiction $ λ hxm,
let ⟨y, i, hi, df⟩ := hm.exists_inv hxm, ⟨z, hz⟩ := hx (-y) in
hm.1.1 $ (eq_top_iff_one _).2 $ sub_sub_cancel (z * -y * x + z) 1 ▸ M.sub_mem
(by { rw [mul_assoc, ←mul_add_one, neg_mul, ← (sub_eq_iff_eq_add.mpr df.symm), neg_sub,
sub_add_cancel],
exact M.mul_mem_left _ hi }) (him hz)⟩
lemma exists_mul_sub_mem_of_sub_one_mem_jacobson {I : ideal R} (r : R)
(h : r - 1 ∈ jacobson I) : ∃ s, s * r - 1 ∈ I :=
begin
cases mem_jacobson_iff.1 h 1 with s hs,
use s,
simpa [mul_sub] using hs
end
/-- An ideal equals its Jacobson radical iff it is the intersection of a set of maximal ideals.
Allowing the set to include ⊤ is equivalent, and is included only to simplify some proofs. -/
theorem eq_jacobson_iff_Inf_maximal :
I.jacobson = I ↔ ∃ M : set (ideal R), (∀ J ∈ M, is_maximal J ∨ J = ⊤) ∧ I = Inf M :=
begin
use λ hI, ⟨{J : ideal R | I ≤ J ∧ J.is_maximal}, ⟨λ _ hJ, or.inl hJ.right, hI.symm⟩⟩,
rintros ⟨M, hM, hInf⟩,
refine le_antisymm (λ x hx, _) le_jacobson,
rw [hInf, mem_Inf],
intros I hI,
cases hM I hI with is_max is_top,
{ exact (mem_Inf.1 hx) ⟨le_Inf_iff.1 (le_of_eq hInf) I hI, is_max⟩ },
{ exact is_top.symm ▸ submodule.mem_top }
end
theorem eq_jacobson_iff_Inf_maximal' :
I.jacobson = I ↔ ∃ M : set (ideal R), (∀ (J ∈ M) (K : ideal R), J < K → K = ⊤) ∧ I = Inf M :=
eq_jacobson_iff_Inf_maximal.trans
⟨λ h, let ⟨M, hM⟩ := h in ⟨M, ⟨λ J hJ K hK, or.rec_on (hM.1 J hJ) (λ h, h.1.2 K hK)
(λ h, eq_top_iff.2 (le_of_lt (h ▸ hK))), hM.2⟩⟩,
λ h, let ⟨M, hM⟩ := h in ⟨M, ⟨λ J hJ, or.rec_on (classical.em (J = ⊤)) (λ h, or.inr h)
(λ h, or.inl ⟨⟨h, hM.1 J hJ⟩⟩), hM.2⟩⟩⟩
/-- An ideal `I` equals its Jacobson radical if and only if every element outside `I`
also lies outside of a maximal ideal containing `I`. -/
lemma eq_jacobson_iff_not_mem :
I.jacobson = I ↔ ∀ x ∉ I, ∃ M : ideal R, (I ≤ M ∧ M.is_maximal) ∧ x ∉ M :=
begin
split,
{ intros h x hx,
erw [← h, mem_Inf] at hx,
push_neg at hx,
exact hx },
{ refine λ h, le_antisymm (λ x hx, _) le_jacobson,
contrapose hx,
erw mem_Inf,
push_neg,
exact h x hx }
end
theorem map_jacobson_of_surjective {f : R →+* S} (hf : function.surjective f) :
ring_hom.ker f ≤ I → map f (I.jacobson) = (map f I).jacobson :=
begin
intro h,
unfold ideal.jacobson,
have : ∀ J ∈ {J : ideal R | I ≤ J ∧ J.is_maximal}, f.ker ≤ J := λ J hJ, le_trans h hJ.left,
refine trans (map_Inf hf this) (le_antisymm _ _),
{ refine Inf_le_Inf (λ J hJ, ⟨comap f J, ⟨⟨le_comap_of_map_le hJ.1, _⟩,
map_comap_of_surjective f hf J⟩⟩),
haveI : J.is_maximal := hJ.right,
exact comap_is_maximal_of_surjective f hf },
{ refine Inf_le_Inf_of_subset_insert_top (λ j hj, hj.rec_on (λ J hJ, _)),
rw ← hJ.2,
cases map_eq_top_or_is_maximal_of_surjective f hf hJ.left.right with htop hmax,
{ exact htop.symm ▸ set.mem_insert ⊤ _ },
{ exact set.mem_insert_of_mem ⊤ ⟨map_mono hJ.1.1, hmax⟩ } },
end
lemma map_jacobson_of_bijective {f : R →+* S} (hf : function.bijective f) :
map f (I.jacobson) = (map f I).jacobson :=
map_jacobson_of_surjective hf.right
(le_trans (le_of_eq (f.injective_iff_ker_eq_bot.1 hf.left)) bot_le)
lemma comap_jacobson {f : R →+* S} {K : ideal S} :
comap f (K.jacobson) = Inf (comap f '' {J : ideal S | K ≤ J ∧ J.is_maximal}) :=
trans (comap_Inf' f _) (Inf_eq_infi).symm
theorem comap_jacobson_of_surjective {f : R →+* S} (hf : function.surjective f) {K : ideal S} :
comap f (K.jacobson) = (comap f K).jacobson :=
begin
unfold ideal.jacobson,
refine le_antisymm _ _,
{ refine le_trans (comap_mono (le_of_eq (trans top_inf_eq.symm Inf_insert.symm))) _,
rw [comap_Inf', Inf_eq_infi],
refine infi_le_infi_of_subset (λ J hJ, _),
have : comap f (map f J) = J := trans (comap_map_of_surjective f hf J)
(le_antisymm (sup_le_iff.2 ⟨le_of_eq rfl, le_trans (comap_mono bot_le) hJ.left⟩) le_sup_left),
cases map_eq_top_or_is_maximal_of_surjective _ hf hJ.right with htop hmax,
{ refine ⟨⊤, ⟨set.mem_insert ⊤ _, htop ▸ this⟩⟩ },
{ refine ⟨map f J, ⟨set.mem_insert_of_mem _
⟨le_map_of_comap_le_of_surjective f hf hJ.1, hmax⟩, this⟩⟩ } },
{ rw comap_Inf,
refine le_infi_iff.2 (λ J, (le_infi_iff.2 (λ hJ, _))),
haveI : J.is_maximal := hJ.right,
refine Inf_le ⟨comap_mono hJ.left, comap_is_maximal_of_surjective _ hf⟩ }
end
@[mono] lemma jacobson_mono {I J : ideal R} : I ≤ J → I.jacobson ≤ J.jacobson :=
begin
intros h x hx,
erw mem_Inf at ⊢ hx,
exact λ K ⟨hK, hK_max⟩, hx ⟨trans h hK, hK_max⟩
end
end ring
section comm_ring
variables [comm_ring R] [comm_ring S] {I : ideal R}
lemma radical_le_jacobson : radical I ≤ jacobson I :=
le_Inf (λ J hJ, (radical_eq_Inf I).symm ▸ Inf_le ⟨hJ.left, is_maximal.is_prime hJ.right⟩)
lemma is_radical_of_eq_jacobson (h : jacobson I = I) : I.is_radical :=
radical_le_jacobson.trans h.le
lemma is_unit_of_sub_one_mem_jacobson_bot (r : R)
(h : r - 1 ∈ jacobson (⊥ : ideal R)) : is_unit r :=
begin
cases exists_mul_sub_mem_of_sub_one_mem_jacobson r h with s hs,
rw [mem_bot, sub_eq_zero, mul_comm] at hs,
exact is_unit_of_mul_eq_one _ _ hs
end
lemma mem_jacobson_bot {x : R} : x ∈ jacobson (⊥ : ideal R) ↔ ∀ y, is_unit (x * y + 1) :=
⟨λ hx y, let ⟨z, hz⟩ := (mem_jacobson_iff.1 hx) y in
is_unit_iff_exists_inv.2 ⟨z, by rwa [add_mul, one_mul, ← sub_eq_zero, mul_right_comm,
mul_comm _ z, mul_right_comm]⟩,
λ h, mem_jacobson_iff.mpr (λ y, (let ⟨b, hb⟩ := is_unit_iff_exists_inv.1 (h y) in
⟨b, (submodule.mem_bot R).2 (hb ▸ (by ring))⟩))⟩
/-- An ideal `I` of `R` is equal to its Jacobson radical if and only if
the Jacobson radical of the quotient ring `R/I` is the zero ideal -/
theorem jacobson_eq_iff_jacobson_quotient_eq_bot :
I.jacobson = I ↔ jacobson (⊥ : ideal (R ⧸ I)) = ⊥ :=
begin
have hf : function.surjective (quotient.mk I) := submodule.quotient.mk_surjective I,
split,
{ intro h,
replace h := congr_arg (map (quotient.mk I)) h,
rw map_jacobson_of_surjective hf (le_of_eq mk_ker) at h,
simpa using h },
{ intro h,
replace h := congr_arg (comap (quotient.mk I)) h,
rw [comap_jacobson_of_surjective hf, ← (quotient.mk I).ker_eq_comap_bot] at h,
simpa using h }
end
/-- The standard radical and Jacobson radical of an ideal `I` of `R` are equal if and only if
the nilradical and Jacobson radical of the quotient ring `R/I` coincide -/
theorem radical_eq_jacobson_iff_radical_quotient_eq_jacobson_bot :
I.radical = I.jacobson ↔ radical (⊥ : ideal (R ⧸ I)) = jacobson ⊥ :=
begin
have hf : function.surjective (quotient.mk I) := submodule.quotient.mk_surjective I,
split,
{ intro h,
have := congr_arg (map (quotient.mk I)) h,
rw [map_radical_of_surjective hf (le_of_eq mk_ker),
map_jacobson_of_surjective hf (le_of_eq mk_ker)] at this,
simpa using this },
{ intro h,
have := congr_arg (comap (quotient.mk I)) h,
rw [comap_radical, comap_jacobson_of_surjective hf, ← (quotient.mk I).ker_eq_comap_bot] at this,
simpa using this }
end
lemma jacobson_radical_eq_jacobson :
I.radical.jacobson = I.jacobson :=
le_antisymm (le_trans (le_of_eq (congr_arg jacobson (radical_eq_Inf I)))
(Inf_le_Inf (λ J hJ, ⟨Inf_le ⟨hJ.1, hJ.2.is_prime⟩, hJ.2⟩))) (jacobson_mono le_radical)
end comm_ring
end jacobson
section polynomial
open polynomial
variables [comm_ring R]
lemma jacobson_bot_polynomial_le_Inf_map_maximal :
jacobson (⊥ : ideal R[X]) ≤ Inf (map (C : R →+* R[X]) '' {J : ideal R | J.is_maximal}) :=
begin
refine le_Inf (λ J, exists_imp_distrib.2 (λ j hj, _)),
haveI : j.is_maximal := hj.1,
refine trans (jacobson_mono bot_le) (le_of_eq _ : J.jacobson ≤ J),
suffices : (⊥ : ideal (polynomial (R ⧸ j))).jacobson = ⊥,
{ rw [← hj.2, jacobson_eq_iff_jacobson_quotient_eq_bot],
replace this :=
congr_arg (map (polynomial_quotient_equiv_quotient_polynomial j).to_ring_hom) this,
rwa [map_jacobson_of_bijective _, map_bot] at this,
exact (ring_equiv.bijective (polynomial_quotient_equiv_quotient_polynomial j)) },
refine eq_bot_iff.2 (λ f hf, _),
simpa [(λ hX, by simpa using congr_arg (λ f, coeff f 1) hX : (X : (R ⧸ j)[X]) ≠ 0)]
using eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit ((mem_jacobson_bot.1 hf) X)),
end
lemma jacobson_bot_polynomial_of_jacobson_bot (h : jacobson (⊥ : ideal R) = ⊥) :
jacobson (⊥ : ideal R[X]) = ⊥ :=
begin
refine eq_bot_iff.2 (le_trans jacobson_bot_polynomial_le_Inf_map_maximal _),
refine (λ f hf, ((submodule.mem_bot _).2 (polynomial.ext (λ n, trans _ (coeff_zero n).symm)))),
suffices : f.coeff n ∈ ideal.jacobson ⊥, by rwa [h, submodule.mem_bot] at this,
exact mem_Inf.2 (λ j hj, (mem_map_C_iff.1 ((mem_Inf.1 hf) ⟨j, ⟨hj.2, rfl⟩⟩)) n),
end
end polynomial
section is_local
variables [comm_ring R]
/-- An ideal `I` is local iff its Jacobson radical is maximal. -/
class is_local (I : ideal R) : Prop := (out : is_maximal (jacobson I))
theorem is_local_iff {I : ideal R} : is_local I ↔ is_maximal (jacobson I) :=
⟨λ h, h.1, λ h, ⟨h⟩⟩
theorem is_local_of_is_maximal_radical {I : ideal R} (hi : is_maximal (radical I)) : is_local I :=
⟨have radical I = jacobson I,
from le_antisymm (le_Inf $ λ M ⟨him, hm⟩, hm.is_prime.radical_le_iff.2 him)
(Inf_le ⟨le_radical, hi⟩),
show is_maximal (jacobson I), from this ▸ hi⟩
theorem is_local.le_jacobson {I J : ideal R} (hi : is_local I) (hij : I ≤ J) (hj : J ≠ ⊤) :
J ≤ jacobson I :=
let ⟨M, hm, hjm⟩ := exists_le_maximal J hj in
le_trans hjm $ le_of_eq $ eq.symm $ hi.1.eq_of_le hm.1.1 $ Inf_le ⟨le_trans hij hjm, hm⟩
theorem is_local.mem_jacobson_or_exists_inv {I : ideal R} (hi : is_local I) (x : R) :
x ∈ jacobson I ∨ ∃ y, y * x - 1 ∈ I :=
classical.by_cases
(assume h : I ⊔ span {x} = ⊤,
let ⟨p, hpi, q, hq, hpq⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in
let ⟨r, hr⟩ := mem_span_singleton.1 hq in
or.inr ⟨r, by rw [← hpq, mul_comm, ← hr, ← neg_sub, add_sub_cancel]; exact I.neg_mem hpi⟩)
(assume h : I ⊔ span {x} ≠ ⊤,
or.inl $ le_trans le_sup_right (hi.le_jacobson le_sup_left h) $ mem_span_singleton.2 $
dvd_refl x)
end is_local
theorem is_primary_of_is_maximal_radical [comm_ring R] {I : ideal R} (hi : is_maximal (radical I)) :
is_primary I :=
have radical I = jacobson I,
from le_antisymm (le_Inf $ λ M ⟨him, hm⟩, hm.is_prime.radical_le_iff.2 him)
(Inf_le ⟨le_radical, hi⟩),
⟨ne_top_of_lt $ lt_of_le_of_lt le_radical (lt_top_iff_ne_top.2 hi.1.1),
λ x y hxy, ((is_local_of_is_maximal_radical hi).mem_jacobson_or_exists_inv y).symm.imp
(λ ⟨z, hz⟩, by rw [← mul_one x, ← sub_sub_cancel (z * y) 1, mul_sub, mul_left_comm]; exact
I.sub_mem (I.mul_mem_left _ hxy) (I.mul_mem_left _ hz))
(this ▸ id)⟩
end ideal
|
372df345e317de924c17998fca84aec058431a4c
|
618003631150032a5676f229d13a079ac875ff77
|
/test/convert.lean
|
544310ab36ea45c260e5b8d9015921251cbcfb18
|
[
"Apache-2.0"
] |
permissive
|
awainverse/mathlib
|
939b68c8486df66cfda64d327ad3d9165248c777
|
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
|
refs/heads/master
| 1,659,592,962,036
| 1,590,987,592,000
| 1,590,987,592,000
| 268,436,019
| 1
| 0
|
Apache-2.0
| 1,590,990,500,000
| 1,590,990,500,000
| null |
UTF-8
|
Lean
| false
| false
| 594
|
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 data.set.basic
import tactic.interactive
open set
variables {α β : Type}
@[simp] lemma singleton_inter_singleton_eq_empty {x y : α} :
({x} ∩ {y} = (∅ : set α)) ↔ x ≠ y :=
by simp [singleton_inter_eq_empty]
example {f : β → α} {x y : α} (h : x ≠ y) : f ⁻¹' {x} ∩ f ⁻¹' {y} = ∅ :=
begin
have : {x} ∩ {y} = (∅ : set α) := by simpa using h,
convert preimage_empty,
rw [←preimage_inter,this],
end
|
eeffa4b02909811c3dc399809ea0c75cc3bcfcc1
|
4727251e0cd73359b15b664c3170e5d754078599
|
/src/topology/category/UniformSpace.lean
|
4b5f920cf466fe0746e1a62b5eb58ab912936d44
|
[
"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,265
|
lean
|
/-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Patrick Massot, Scott Morrison
-/
import category_theory.adjunction.reflective
import category_theory.concrete_category.unbundled_hom
import category_theory.monad.limits
import category_theory.limits.has_limits
import topology.category.Top.basic
import topology.uniform_space.completion
/-!
# The category of uniform spaces
We construct the category of uniform spaces, show that the complete separated uniform spaces
form a reflective subcategory, and hence possess all limits that uniform spaces do.
TODO: show that uniform spaces actually have all limits!
-/
universes u
open category_theory
/-- A (bundled) uniform space. -/
def UniformSpace : Type (u+1) := bundled uniform_space
namespace UniformSpace
/-- The information required to build morphisms for `UniformSpace`. -/
instance : unbundled_hom @uniform_continuous :=
⟨@uniform_continuous_id, @uniform_continuous.comp⟩
attribute [derive [large_category, concrete_category]] UniformSpace
instance : has_coe_to_sort UniformSpace Type* := bundled.has_coe_to_sort
instance (x : UniformSpace) : uniform_space x := x.str
/-- Construct a bundled `UniformSpace` from the underlying type and the typeclass. -/
def of (α : Type u) [uniform_space α] : UniformSpace := ⟨α⟩
instance : inhabited UniformSpace := ⟨UniformSpace.of empty⟩
@[simp] lemma coe_of (X : Type u) [uniform_space X] : (of X : Type u) = X := rfl
instance (X Y : UniformSpace) : has_coe_to_fun (X ⟶ Y) (λ _, X → Y) :=
⟨category_theory.functor.map (forget UniformSpace)⟩
@[simp] lemma coe_comp {X Y Z : UniformSpace} (f : X ⟶ Y) (g : Y ⟶ Z) :
(f ≫ g : X → Z) = g ∘ f := rfl
@[simp] lemma coe_id (X : UniformSpace) : (𝟙 X : X → X) = id := rfl
@[simp] lemma coe_mk {X Y : UniformSpace} (f : X → Y) (hf : uniform_continuous f) :
((⟨f, hf⟩ : X ⟶ Y) : X → Y) = f := rfl
lemma hom_ext {X Y : UniformSpace} {f g : X ⟶ Y} : (f : X → Y) = g → f = g := subtype.eq
/-- The forgetful functor from uniform spaces to topological spaces. -/
instance has_forget_to_Top : has_forget₂ UniformSpace.{u} Top.{u} :=
{ forget₂ :=
{ obj := λ X, Top.of X,
map := λ X Y f, { to_fun := f,
continuous_to_fun := uniform_continuous.continuous f.property }, }, }
end UniformSpace
/-- A (bundled) complete separated uniform space. -/
structure CpltSepUniformSpace :=
(α : Type u)
[is_uniform_space : uniform_space α]
[is_complete_space : complete_space α]
[is_separated : separated_space α]
namespace CpltSepUniformSpace
instance : has_coe_to_sort CpltSepUniformSpace (Type u) := ⟨CpltSepUniformSpace.α⟩
attribute [instance] is_uniform_space is_complete_space is_separated
/-- The function forgetting that a complete separated uniform spaces is complete and separated. -/
def to_UniformSpace (X : CpltSepUniformSpace) : UniformSpace :=
UniformSpace.of X
instance complete_space (X : CpltSepUniformSpace) : complete_space ((to_UniformSpace X).α) :=
CpltSepUniformSpace.is_complete_space X
instance separated_space (X : CpltSepUniformSpace) : separated_space ((to_UniformSpace X).α) :=
CpltSepUniformSpace.is_separated X
/-- Construct a bundled `UniformSpace` from the underlying type and the appropriate typeclasses. -/
def of (X : Type u) [uniform_space X] [complete_space X] [separated_space X] :
CpltSepUniformSpace := ⟨X⟩
@[simp] lemma coe_of (X : Type u) [uniform_space X] [complete_space X] [separated_space X] :
(of X : Type u) = X := rfl
instance : inhabited CpltSepUniformSpace :=
begin
haveI : separated_space empty := separated_iff_t2.mpr (by apply_instance),
exact ⟨CpltSepUniformSpace.of empty⟩
end
/-- The category instance on `CpltSepUniformSpace`. -/
instance category : large_category CpltSepUniformSpace :=
induced_category.category to_UniformSpace
/-- The concrete category instance on `CpltSepUniformSpace`. -/
instance concrete_category : concrete_category CpltSepUniformSpace :=
induced_category.concrete_category to_UniformSpace
instance has_forget_to_UniformSpace : has_forget₂ CpltSepUniformSpace UniformSpace :=
induced_category.has_forget₂ to_UniformSpace
end CpltSepUniformSpace
namespace UniformSpace
open uniform_space
open CpltSepUniformSpace
/-- The functor turning uniform spaces into complete separated uniform spaces. -/
noncomputable def completion_functor : UniformSpace ⥤ CpltSepUniformSpace :=
{ obj := λ X, CpltSepUniformSpace.of (completion X),
map := λ X Y f, ⟨completion.map f.1, completion.uniform_continuous_map⟩,
map_id' := λ X, subtype.eq completion.map_id,
map_comp' := λ X Y Z f g, subtype.eq (completion.map_comp g.property f.property).symm, }.
/-- The inclusion of a uniform space into its completion. -/
def completion_hom (X : UniformSpace) :
X ⟶ (forget₂ CpltSepUniformSpace UniformSpace).obj (completion_functor.obj X) :=
{ val := (coe : X → completion X),
property := completion.uniform_continuous_coe X }
@[simp] lemma completion_hom_val (X : UniformSpace) (x) :
(completion_hom X) x = (x : completion X) := rfl
/-- The mate of a morphism from a `UniformSpace` to a `CpltSepUniformSpace`. -/
noncomputable def extension_hom {X : UniformSpace} {Y : CpltSepUniformSpace}
(f : X ⟶ (forget₂ CpltSepUniformSpace UniformSpace).obj Y) :
completion_functor.obj X ⟶ Y :=
{ val := completion.extension f,
property := completion.uniform_continuous_extension }
@[simp] lemma extension_hom_val {X : UniformSpace} {Y : CpltSepUniformSpace}
(f : X ⟶ (forget₂ _ _).obj Y) (x) :
(extension_hom f) x = completion.extension f x := rfl.
@[simp] lemma extension_comp_coe {X : UniformSpace} {Y : CpltSepUniformSpace}
(f : to_UniformSpace (CpltSepUniformSpace.of (completion X)) ⟶ to_UniformSpace Y) :
extension_hom (completion_hom X ≫ f) = f :=
by { apply subtype.eq, funext x, exact congr_fun (completion.extension_comp_coe f.property) x }
/-- The completion functor is left adjoint to the forgetful functor. -/
noncomputable def adj : completion_functor ⊣ forget₂ CpltSepUniformSpace UniformSpace :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ X Y,
{ to_fun := λ f, completion_hom X ≫ f,
inv_fun := λ f, extension_hom f,
left_inv := λ f, by { dsimp, erw extension_comp_coe },
right_inv := λ f,
begin
apply subtype.eq, funext x, cases f,
exact @completion.extension_coe _ _ _ _ _ (CpltSepUniformSpace.separated_space _) f_property _
end },
hom_equiv_naturality_left_symm' := λ X X' Y f g,
begin
apply hom_ext, funext x, dsimp,
erw [coe_comp, ←completion.extension_map],
refl, exact g.property, exact f.property,
end }
noncomputable instance : is_right_adjoint (forget₂ CpltSepUniformSpace UniformSpace) :=
⟨completion_functor, adj⟩
noncomputable instance : reflective (forget₂ CpltSepUniformSpace UniformSpace) := {}
open category_theory.limits
-- TODO Once someone defines `has_limits UniformSpace`, turn this into an instance.
example [has_limits.{u} UniformSpace.{u}] : has_limits.{u} CpltSepUniformSpace.{u} :=
has_limits_of_reflective $ forget₂ CpltSepUniformSpace UniformSpace.{u}
end UniformSpace
|
ef799d9291c79f91480b6620f4ead0ffc49897d3
|
a4673261e60b025e2c8c825dfa4ab9108246c32e
|
/src/Lean/Compiler/IR/RC.lean
|
a5ecab26591c7ed9e8c8cb59355f481d9a5867a7
|
[
"Apache-2.0"
] |
permissive
|
jcommelin/lean4
|
c02dec0cc32c4bccab009285475f265f17d73228
|
2909313475588cc20ac0436e55548a4502050d0a
|
refs/heads/master
| 1,674,129,550,893
| 1,606,415,348,000
| 1,606,415,348,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 12,738
|
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.Runtime
import Lean.Compiler.IR.CompilerM
import Lean.Compiler.IR.LiveVars
namespace Lean.IR.ExplicitRC
/- Insert explicit RC instructions. So, it assumes the input code does not contain `inc` nor `dec` instructions.
This transformation is applied before lower level optimizations
that introduce the instructions `release` and `set`
-/
structure VarInfo :=
(ref : Bool := true) -- true if the variable may be a reference (aka pointer) at runtime
(persistent : Bool := false) -- true if the variable is statically known to be marked a Persistent at runtime
(consume : Bool := false) -- true if the variable RC must be "consumed"
abbrev VarMap := Std.RBMap VarId VarInfo (fun x y => x.idx < y.idx)
structure Context :=
(env : Environment)
(decls : Array Decl)
(varMap : VarMap := {})
(jpLiveVarMap : JPLiveVarMap := {}) -- map: join point => live variables
(localCtx : LocalContext := {}) -- we use it to store the join point declarations
def getDecl (ctx : Context) (fid : FunId) : Decl :=
match findEnvDecl' ctx.env fid ctx.decls with
| some decl => decl
| none => arbitrary -- unreachable if well-formed
def getVarInfo (ctx : Context) (x : VarId) : VarInfo :=
match ctx.varMap.find? x with
| some info => info
| none => {} -- unreachable in well-formed code
def getJPParams (ctx : Context) (j : JoinPointId) : Array Param :=
match ctx.localCtx.getJPParams j with
| some ps => ps
| none => #[] -- unreachable in well-formed code
def getJPLiveVars (ctx : Context) (j : JoinPointId) : LiveVarSet :=
match ctx.jpLiveVarMap.find? j with
| some s => s
| none => {}
def mustConsume (ctx : Context) (x : VarId) : Bool :=
let info := getVarInfo ctx x
info.ref && info.consume
@[inline] def addInc (ctx : Context) (x : VarId) (b : FnBody) (n := 1) : FnBody :=
let info := getVarInfo ctx x
if n == 0 then b else FnBody.inc x n true info.persistent b
@[inline] def addDec (ctx : Context) (x : VarId) (b : FnBody) : FnBody :=
let info := getVarInfo ctx x
FnBody.dec x 1 true info.persistent b
private def updateRefUsingCtorInfo (ctx : Context) (x : VarId) (c : CtorInfo) : Context :=
if c.isRef then
ctx
else
let m := ctx.varMap
{ ctx with
varMap := match m.find? x with
| some info => m.insert x { info with ref := false } -- I really want a Lenses library + notation
| none => m }
private def addDecForAlt (ctx : Context) (caseLiveVars altLiveVars : LiveVarSet) (b : FnBody) : FnBody :=
caseLiveVars.fold (init := b) fun b x =>
if !altLiveVars.contains x && mustConsume ctx x then addDec ctx x b else b
/- `isFirstOcc xs x i = true` if `xs[i]` is the first occurrence of `xs[i]` in `xs` -/
private def isFirstOcc (xs : Array Arg) (i : Nat) : Bool :=
let x := xs[i]
i.all fun j => xs[j] != x
/- Return true if `x` also occurs in `ys` in a position that is not consumed.
That is, it is also passed as a borrow reference. -/
@[specialize]
private def isBorrowParamAux (x : VarId) (ys : Array Arg) (consumeParamPred : Nat → Bool) : Bool :=
ys.size.any fun i =>
let y := ys[i]
match y with
| Arg.irrelevant => false
| Arg.var y => x == y && !consumeParamPred i
private def isBorrowParam (x : VarId) (ys : Array Arg) (ps : Array Param) : Bool :=
isBorrowParamAux x ys fun i => not ps[i].borrow
/-
Return `n`, the number of times `x` is consumed.
- `ys` is a sequence of instruction parameters where we search for `x`.
- `consumeParamPred i = true` if parameter `i` is consumed.
-/
@[specialize]
private def getNumConsumptions (x : VarId) (ys : Array Arg) (consumeParamPred : Nat → Bool) : Nat :=
ys.size.fold (init := 0) fun i n =>
let y := ys[i]
match y with
| Arg.irrelevant => n
| Arg.var y => if x == y && consumeParamPred i then n+1 else n
@[specialize]
private def addIncBeforeAux (ctx : Context) (xs : Array Arg) (consumeParamPred : Nat → Bool) (b : FnBody) (liveVarsAfter : LiveVarSet) : FnBody :=
xs.size.fold (init := b) fun i b =>
let x := xs[i]
match x with
| Arg.irrelevant => b
| Arg.var x =>
let info := getVarInfo ctx x
if !info.ref || !isFirstOcc xs i then b
else
let numConsuptions := getNumConsumptions x xs consumeParamPred -- number of times the argument is
let numIncs :=
if !info.consume || -- `x` is not a variable that must be consumed by the current procedure
liveVarsAfter.contains x || -- `x` is live after executing instruction
isBorrowParamAux x xs consumeParamPred -- `x` is used in a position that is passed as a borrow reference
then numConsuptions
else numConsuptions - 1
-- dbgTrace ("addInc " ++ toString x ++ " nconsumptions: " ++ toString numConsuptions ++ " incs: " ++ toString numIncs
-- ++ " consume: " ++ toString info.consume ++ " live: " ++ toString (liveVarsAfter.contains x)
-- ++ " borrowParam : " ++ toString (isBorrowParamAux x xs consumeParamPred)) $ fun _ =>
addInc ctx x b numIncs
private def addIncBefore (ctx : Context) (xs : Array Arg) (ps : Array Param) (b : FnBody) (liveVarsAfter : LiveVarSet) : FnBody :=
addIncBeforeAux ctx xs (fun i => not ps[i].borrow) b liveVarsAfter
/- See `addIncBeforeAux`/`addIncBefore` for the procedure that inserts `inc` operations before an application. -/
private def addDecAfterFullApp (ctx : Context) (xs : Array Arg) (ps : Array Param) (b : FnBody) (bLiveVars : LiveVarSet) : FnBody :=
xs.size.fold (init := b) fun i b =>
match xs[i] with
| Arg.irrelevant => b
| Arg.var x =>
/- We must add a `dec` if `x` must be consumed, it is alive after the application,
and it has been borrowed by the application.
Remark: `x` may occur multiple times in the application (e.g., `f x y x`).
This is why we check whether it is the first occurrence. -/
if mustConsume ctx x && isFirstOcc xs i && isBorrowParam x xs ps && !bLiveVars.contains x then
addDec ctx x b
else b
private def addIncBeforeConsumeAll (ctx : Context) (xs : Array Arg) (b : FnBody) (liveVarsAfter : LiveVarSet) : FnBody :=
addIncBeforeAux ctx xs (fun i => true) b liveVarsAfter
/- Add `dec` instructions for parameters that are references, are not alive in `b`, and are not borrow.
That is, we must make sure these parameters are consumed. -/
private def addDecForDeadParams (ctx : Context) (ps : Array Param) (b : FnBody) (bLiveVars : LiveVarSet) : FnBody :=
ps.foldl (init := b) fun b p =>
if !p.borrow && p.ty.isObj && !bLiveVars.contains p.x then addDec ctx p.x b else b
private def isPersistent : Expr → Bool
| Expr.fap c xs => xs.isEmpty -- all global constants are persistent objects
| _ => false
/- We do not need to consume the projection of a variable that is not consumed -/
private def consumeExpr (m : VarMap) : Expr → Bool
| Expr.proj i x => match m.find? x with
| some info => info.consume
| none => true
| other => true
/- Return true iff `v` at runtime is a scalar value stored in a tagged pointer.
We do not need RC operations for this kind of value. -/
private def isScalarBoxedInTaggedPtr (v : Expr) : Bool :=
match v with
| Expr.ctor c ys => c.size == 0 && c.ssize == 0 && c.usize == 0
| Expr.lit (LitVal.num n) => n ≤ maxSmallNat
| _ => false
private def updateVarInfo (ctx : Context) (x : VarId) (t : IRType) (v : Expr) : Context :=
{ ctx with
varMap := ctx.varMap.insert x {
ref := t.isObj && !isScalarBoxedInTaggedPtr v,
persistent := isPersistent v,
consume := consumeExpr ctx.varMap v
}
}
private def addDecIfNeeded (ctx : Context) (x : VarId) (b : FnBody) (bLiveVars : LiveVarSet) : FnBody :=
if mustConsume ctx x && !bLiveVars.contains x then addDec ctx x b else b
private def processVDecl (ctx : Context) (z : VarId) (t : IRType) (v : Expr) (b : FnBody) (bLiveVars : LiveVarSet) : FnBody × LiveVarSet :=
let b := match v with
| (Expr.ctor _ ys) => addIncBeforeConsumeAll ctx ys (FnBody.vdecl z t v b) bLiveVars
| (Expr.reuse _ _ _ ys) => addIncBeforeConsumeAll ctx ys (FnBody.vdecl z t v b) bLiveVars
| (Expr.proj _ x) =>
let b := addDecIfNeeded ctx x b bLiveVars
let b := if (getVarInfo ctx x).consume then addInc ctx z b else b
(FnBody.vdecl z t v b)
| (Expr.uproj _ x) => FnBody.vdecl z t v (addDecIfNeeded ctx x b bLiveVars)
| (Expr.sproj _ _ x) => FnBody.vdecl z t v (addDecIfNeeded ctx x b bLiveVars)
| (Expr.fap f ys) =>
-- dbgTrace ("processVDecl " ++ toString v) $ fun _ =>
let ps := (getDecl ctx f).params
let b := addDecAfterFullApp ctx ys ps b bLiveVars
let b := FnBody.vdecl z t v b
addIncBefore ctx ys ps b bLiveVars
| (Expr.pap _ ys) => addIncBeforeConsumeAll ctx ys (FnBody.vdecl z t v b) bLiveVars
| (Expr.ap x ys) =>
let ysx := ys.push (Arg.var x) -- TODO: avoid temporary array allocation
addIncBeforeConsumeAll ctx ysx (FnBody.vdecl z t v b) bLiveVars
| (Expr.unbox x) => FnBody.vdecl z t v (addDecIfNeeded ctx x b bLiveVars)
| other => FnBody.vdecl z t v b -- Expr.reset, Expr.box, Expr.lit are handled here
let liveVars := updateLiveVars v bLiveVars
let liveVars := liveVars.erase z
(b, liveVars)
def updateVarInfoWithParams (ctx : Context) (ps : Array Param) : Context :=
let m := ps.foldl (init := ctx.varMap) fun m p =>
m.insert p.x { ref := p.ty.isObj, consume := !p.borrow }
{ ctx with varMap := m }
partial def visitFnBody : FnBody → Context → (FnBody × LiveVarSet)
| FnBody.vdecl x t v b, ctx =>
let ctx := updateVarInfo ctx x t v
let (b, bLiveVars) := visitFnBody b ctx
processVDecl ctx x t v b bLiveVars
| FnBody.jdecl j xs v b, ctx =>
let (v, vLiveVars) := visitFnBody v (updateVarInfoWithParams ctx xs)
let v := addDecForDeadParams ctx xs v vLiveVars
let ctx := { ctx with jpLiveVarMap := updateJPLiveVarMap j xs v ctx.jpLiveVarMap }
let (b, bLiveVars) := visitFnBody b ctx
(FnBody.jdecl j xs v b, bLiveVars)
| FnBody.uset x i y b, ctx =>
let (b, s) := visitFnBody b ctx
-- We don't need to insert `y` since we only need to track live variables that are references at runtime
let s := s.insert x
(FnBody.uset x i y b, s)
| FnBody.sset x i o y t b, ctx =>
let (b, s) := visitFnBody b ctx
-- We don't need to insert `y` since we only need to track live variables that are references at runtime
let s := s.insert x
(FnBody.sset x i o y t b, s)
| FnBody.mdata m b, ctx =>
let (b, s) := visitFnBody b ctx
(FnBody.mdata m b, s)
| b@(FnBody.case tid x xType alts), ctx =>
let caseLiveVars := collectLiveVars b ctx.jpLiveVarMap
let alts := alts.map $ fun alt => match alt with
| Alt.ctor c b =>
let ctx := updateRefUsingCtorInfo ctx x c
let (b, altLiveVars) := visitFnBody b ctx
let b := addDecForAlt ctx caseLiveVars altLiveVars b
Alt.ctor c b
| Alt.default b =>
let (b, altLiveVars) := visitFnBody b ctx
let b := addDecForAlt ctx caseLiveVars altLiveVars b
Alt.default b
(FnBody.case tid x xType alts, caseLiveVars)
| b@(FnBody.ret x), ctx =>
match x with
| Arg.var x =>
let info := getVarInfo ctx x
if info.ref && !info.consume then (addInc ctx x b, mkLiveVarSet x) else (b, mkLiveVarSet x)
| _ => (b, {})
| b@(FnBody.jmp j xs), ctx =>
let jLiveVars := getJPLiveVars ctx j
let ps := getJPParams ctx j
let b := addIncBefore ctx xs ps b jLiveVars
let bLiveVars := collectLiveVars b ctx.jpLiveVarMap
(b, bLiveVars)
| FnBody.unreachable, _ => (FnBody.unreachable, {})
| other, ctx => (other, {}) -- unreachable if well-formed
partial def visitDecl (env : Environment) (decls : Array Decl) : Decl → Decl
| Decl.fdecl f xs t b =>
let ctx : Context := { env := env, decls := decls }
let ctx := updateVarInfoWithParams ctx xs
let (b, bLiveVars) := visitFnBody b ctx
let b := addDecForDeadParams ctx xs b bLiveVars
Decl.fdecl f xs t b
| other => other
end ExplicitRC
def explicitRC (decls : Array Decl) : CompilerM (Array Decl) := do
let env ← getEnv
pure $ decls.map (ExplicitRC.visitDecl env decls)
end Lean.IR
|
456d9a477c2b889aea9bdb04342f4f141a61682d
|
d406927ab5617694ec9ea7001f101b7c9e3d9702
|
/src/data/fintype/card_embedding.lean
|
9992b97aef63c983924d49071eb8086a6f3ddcf2
|
[
"Apache-2.0"
] |
permissive
|
alreadydone/mathlib
|
dc0be621c6c8208c581f5170a8216c5ba6721927
|
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
|
refs/heads/master
| 1,685,523,275,196
| 1,670,184,141,000
| 1,670,184,141,000
| 287,574,545
| 0
| 0
|
Apache-2.0
| 1,670,290,714,000
| 1,597,421,623,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 1,909
|
lean
|
/-
Copyright (c) 2021 Eric Rodriguez. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Rodriguez
-/
import data.fintype.big_operators
import logic.equiv.embedding
/-!
# Number of embeddings
This file establishes the cardinality of `α ↪ β` in full generality.
-/
local notation (name := finset.card) `|` x `|` := finset.card x
local notation (name := fintype.card) `‖` x `‖` := fintype.card x
open function
open_locale nat big_operators
namespace fintype
lemma card_embedding_eq_of_unique {α β : Type*} [unique α] [fintype β] [fintype (α ↪ β)] :
‖α ↪ β‖ = ‖β‖ := card_congr equiv.unique_embedding_equiv_result
/- Establishes the cardinality of the type of all injections between two finite types. -/
@[simp] theorem card_embedding_eq {α β} [fintype α] [fintype β] [fintype (α ↪ β)] :
‖α ↪ β‖ = (‖β‖.desc_factorial ‖α‖) :=
begin
classical,
unfreezingI { induction ‹fintype α› using fintype.induction_empty_option
with α₁ α₂ h₂ e ih α h ih },
{ letI := fintype.of_equiv _ e.symm,
rw [← card_congr (equiv.embedding_congr e (equiv.refl β)), ih, card_congr e] },
{ rw [card_pempty, nat.desc_factorial_zero, card_eq_one_iff],
exact ⟨embedding.of_is_empty, λ x, fun_like.ext _ _ is_empty_elim⟩ },
{ rw [card_option, nat.desc_factorial_succ, card_congr (embedding.option_embedding_equiv α β),
card_sigma, ← ih],
simp only [fintype.card_compl_set, fintype.card_range, finset.sum_const, finset.card_univ,
smul_eq_mul, mul_comm] },
end
/- The cardinality of embeddings from an infinite type to a finite type is zero.
This is a re-statement of the pigeonhole principle. -/
@[simp] lemma card_embedding_eq_of_infinite {α β : Type*} [infinite α] [fintype β]
[fintype (α ↪ β)] :
‖α ↪ β‖ = 0 :=
card_eq_zero
end fintype
|
0676c6eeacdc7dd3ea8972b5ccaa9ab854e3efa2
|
d9d511f37a523cd7659d6f573f990e2a0af93c6f
|
/src/analysis/calculus/fderiv_symmetric.lean
|
4058f9e17c09e855152e42e7e5c627eb06444304
|
[
"Apache-2.0"
] |
permissive
|
hikari0108/mathlib
|
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
|
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
|
refs/heads/master
| 1,690,483,608,260
| 1,631,541,580,000
| 1,631,541,580,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 19,560
|
lean
|
/-
Copyright (c) 2021 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.calculus.deriv
import analysis.calculus.mean_value
import analysis.convex.topology
/-!
# Symmetry of the second derivative
We show that, over the reals, the second derivative is symmetric.
The most precise result is `convex.second_derivative_within_at_symmetric`. It asserts that,
if a function is differentiable inside a convex set `s` with nonempty interior, and has a second
derivative within `s` at a point `x`, then this second derivative at `x` is symmetric. Note that
this result does not require continuity of the first derivative.
The following particular cases of this statement are especially relevant:
`second_derivative_symmetric_of_eventually` asserts that, if a function is differentiable on a
neighborhood of `x`, and has a second derivative at `x`, then this second derivative is symmetric.
`second_derivative_symmetric` asserts that, if a function is differentiable, and has a second
derivative at `x`, then this second derivative is symmetric.
## Implementation note
For the proof, we obtain an asymptotic expansion to order two of `f (x + v + w) - f (x + v)`, by
using the mean value inequality applied to a suitable function along the
segment `[x + v, x + v + w]`. This expansion involves `f'' ⬝ w` as we move along a segment directed
by `w` (see `convex.taylor_approx_two_segment`).
Consider the alternate sum `f (x + v + w) + f x - f (x + v) - f (x + w)`, corresponding to the
values of `f` along a rectangle based at `x` with sides `v` and `w`. One can write it using the two
sides directed by `w`, as `(f (x + v + w) - f (x + v)) - (f (x + w) - f x)`. Together with the
previous asymptotic expansion, one deduces that it equals `f'' v w + o(1)` when `v, w` tends to `0`.
Exchanging the roles of `v` and `w`, one instead gets an asymptotic expansion `f'' w v`, from which
the equality `f'' v w = f'' w v` follows.
In our most general statement, we only assume that `f` is differentiable inside a convex set `s`, so
a few modifications have to be made. Since we don't assume continuity of `f` at `x`, we consider
instead the rectangle based at `x + v + w` with sides `v` and `w`,
in `convex.is_o_alternate_sum_square`, but the argument is essentially the same. It only works
when `v` and `w` both point towards the interior of `s`, to make sure that all the sides of the
rectangle are contained in `s` by convexity. The general case follows by linearity, though.
-/
open asymptotics set
open_locale topological_space
variables {E F : Type*} [normed_group E] [normed_space ℝ E]
[normed_group F] [normed_space ℝ F]
{s : set E} (s_conv : convex s)
{f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)}
(hf : ∀ x ∈ interior s, has_fderiv_at f (f' x) x)
{x : E} (xs : x ∈ s) (hx : has_fderiv_within_at f' f'' (interior s) x)
include s_conv xs hx hf
/-- Assume that `f` is differentiable inside a convex set `s`, and that its derivative `f'` is
differentiable at a point `x`. Then, given two vectors `v` and `w` pointing inside `s`, one can
Taylor-expand to order two the function `f` on the segment `[x + h v, x + h (v + w)]`, giving a
bilinear estimate for `f (x + hv + hw) - f (x + hv)` in terms of `f' w` and of `f'' ⬝ w`, up to
`o(h^2)`.
This is a technical statement used to show that the second derivative is symmetric.
-/
lemma convex.taylor_approx_two_segment
{v w : E} (hv : x + v ∈ interior s) (hw : x + v + w ∈ interior s) :
is_o (λ (h : ℝ), f (x + h • v + h • w) - f (x + h • v) - h • f' x w
- h^2 • f'' v w - (h^2/2) • f'' w w) (λ h, h^2) (𝓝[Ioi (0 : ℝ)] 0) :=
begin
-- it suffices to check that the expression is bounded by `ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2` for
-- small enough `h`, for any positive `ε`.
apply is_o.trans_is_O (is_o_iff.2 (λ ε εpos, _)) (is_O_const_mul_self ((∥v∥ + ∥w∥) * ∥w∥) _ _),
-- consider a ball of radius `δ` around `x` in which the Taylor approximation for `f''` is
-- good up to `δ`.
rw [has_fderiv_within_at, has_fderiv_at_filter, is_o_iff] at hx,
rcases metric.mem_nhds_within_iff.1 (hx εpos) with ⟨δ, δpos, sδ⟩,
have E1 : ∀ᶠ h in 𝓝[Ioi (0:ℝ)] 0, h * (∥v∥ + ∥w∥) < δ,
{ have : filter.tendsto (λ h, h * (∥v∥ + ∥w∥)) (𝓝[Ioi (0:ℝ)] 0) (𝓝 (0 * (∥v∥ + ∥w∥))) :=
(continuous_id.mul continuous_const).continuous_within_at,
apply (tendsto_order.1 this).2 δ,
simpa only [zero_mul] using δpos },
have E2 : ∀ᶠ h in 𝓝[Ioi (0:ℝ)] 0, (h : ℝ) < 1 :=
mem_nhds_within_Ioi_iff_exists_Ioo_subset.2
⟨(1 : ℝ), by simp only [mem_Ioi, zero_lt_one], λ x hx, hx.2⟩,
filter_upwards [E1, E2, self_mem_nhds_within],
-- we consider `h` small enough that all points under consideration belong to this ball,
-- and also with `0 < h < 1`.
assume h hδ h_lt_1 hpos,
replace hpos : 0 < h := hpos,
have xt_mem : ∀ t ∈ Icc (0 : ℝ) 1, x + h • v + (t * h) • w ∈ interior s,
{ assume t ht,
have : x + h • v ∈ interior s :=
s_conv.add_smul_mem_interior xs hv ⟨hpos, h_lt_1.le⟩,
rw [← smul_smul],
apply s_conv.interior.add_smul_mem this _ ht,
rw add_assoc at hw,
convert s_conv.add_smul_mem_interior xs hw ⟨hpos, h_lt_1.le⟩ using 1,
simp only [add_assoc, smul_add] },
-- define a function `g` on `[0,1]` (identified with `[v, v + w]`) such that `g 1 - g 0` is the
-- quantity to be estimated. We will check that its derivative is given by an explicit
-- expression `g'`, that we can bound. Then the desired bound for `g 1 - g 0` follows from the
-- mean value inequality.
let g := λ t, f (x + h • v + (t * h) • w) - (t * h) • f' x w - (t * h^2) • f'' v w
- ((t * h)^2/2) • f'' w w,
set g' := λ t, f' (x + h • v + (t * h) • w) (h • w) - h • f' x w
- h^2 • f'' v w - (t * h^2) • f'' w w with hg',
-- check that `g'` is the derivative of `g`, by a straightforward computation
have g_deriv : ∀ t ∈ Icc (0 : ℝ) 1, has_deriv_within_at g (g' t) (Icc 0 1) t,
{ assume t ht,
apply_rules [has_deriv_within_at.sub, has_deriv_within_at.add],
{ refine (hf _ _).comp_has_deriv_within_at _ _,
{ exact xt_mem t ht },
apply has_deriv_at.has_deriv_within_at,
suffices : has_deriv_at (λ u, x + h • v + (u * h) • w) (0 + 0 + (1 * h) • w) t,
by simpa only [one_mul, zero_add],
apply_rules [has_deriv_at.add, has_deriv_at_const, has_deriv_at.smul_const,
has_deriv_at_id'] },
{ suffices : has_deriv_within_at (λ u, (u * h) • f' x w) ((1 * h) • f' x w) (Icc 0 1) t,
by simpa only [one_mul],
apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.smul_const, has_deriv_at_id'] },
{ suffices : has_deriv_within_at (λ u, (u * h ^ 2) • f'' v w) ((1 * h^2) • f'' v w) (Icc 0 1) t,
by simpa only [one_mul],
apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.smul_const, has_deriv_at_id'] },
{ suffices H : has_deriv_within_at (λ u, ((u * h) ^ 2 / 2) • f'' w w)
(((((2 : ℕ) : ℝ) * (t * h) ^ (2 - 1) * (1 * h))/2) • f'' w w) (Icc 0 1) t,
{ convert H using 2,
simp only [one_mul, nat.cast_bit0, pow_one, nat.cast_one],
ring },
apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.smul_const, has_deriv_at_id',
has_deriv_at.pow] } },
-- check that `g'` is uniformly bounded, with a suitable bound `ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2`.
have g'_bound : ∀ t ∈ Ico (0 : ℝ) 1, ∥g' t∥ ≤ ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2,
{ assume t ht,
have I : ∥h • v + (t * h) • w∥ ≤ h * (∥v∥ + ∥w∥) := calc
∥h • v + (t * h) • w∥ ≤ ∥h • v∥ + ∥(t * h) • w∥ : norm_add_le _ _
... = h * ∥v∥ + t * (h * ∥w∥) :
by simp only [norm_smul, real.norm_eq_abs, hpos.le, abs_of_nonneg, abs_mul, ht.left,
mul_assoc]
... ≤ h * ∥v∥ + 1 * (h * ∥w∥) :
add_le_add (le_refl _) (mul_le_mul_of_nonneg_right ht.2.le
(mul_nonneg hpos.le (norm_nonneg _)))
... = h * (∥v∥ + ∥w∥) : by ring,
calc ∥g' t∥ = ∥(f' (x + h • v + (t * h) • w) - f' x - f'' (h • v + (t * h) • w)) (h • w)∥ :
begin
rw hg',
have : h * (t * h) = t * (h * h), by ring,
simp only [continuous_linear_map.coe_sub', continuous_linear_map.map_add, pow_two,
continuous_linear_map.add_apply, pi.smul_apply, smul_sub, smul_add, smul_smul, ← sub_sub,
continuous_linear_map.coe_smul', pi.sub_apply, continuous_linear_map.map_smul, this]
end
... ≤ ∥f' (x + h • v + (t * h) • w) - f' x - f'' (h • v + (t * h) • w)∥ * ∥h • w∥ :
continuous_linear_map.le_op_norm _ _
... ≤ (ε * ∥h • v + (t * h) • w∥) * (∥h • w∥) :
begin
apply mul_le_mul_of_nonneg_right _ (norm_nonneg _),
have H : x + h • v + (t * h) • w ∈ metric.ball x δ ∩ interior s,
{ refine ⟨_, xt_mem t ⟨ht.1, ht.2.le⟩⟩,
rw [add_assoc, add_mem_ball_iff_norm],
exact I.trans_lt hδ },
have := sδ H,
simp only [mem_set_of_eq] at this,
convert this;
abel
end
... ≤ (ε * (∥h • v∥ + ∥h • w∥)) * (∥h • w∥) :
begin
apply mul_le_mul_of_nonneg_right _ (norm_nonneg _),
apply mul_le_mul_of_nonneg_left _ (εpos.le),
apply (norm_add_le _ _).trans,
refine add_le_add (le_refl _) _,
simp only [norm_smul, real.norm_eq_abs, abs_mul, abs_of_nonneg, ht.1, hpos.le, mul_assoc],
exact mul_le_of_le_one_left (mul_nonneg hpos.le (norm_nonneg _)) ht.2.le,
end
... = ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2 :
by { simp only [norm_smul, real.norm_eq_abs, abs_mul, abs_of_nonneg, hpos.le], ring } },
-- conclude using the mean value inequality
have I : ∥g 1 - g 0∥ ≤ ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2, by simpa only [mul_one, sub_zero] using
norm_image_sub_le_of_norm_deriv_le_segment' g_deriv g'_bound 1 (right_mem_Icc.2 zero_le_one),
convert I using 1,
{ congr' 1,
dsimp only [g],
simp only [nat.one_ne_zero, add_zero, one_mul, zero_div, zero_mul, sub_zero, zero_smul,
ne.def, not_false_iff, bit0_eq_zero, zero_pow'],
abel },
{ simp only [real.norm_eq_abs, abs_mul, add_nonneg (norm_nonneg v) (norm_nonneg w),
abs_of_nonneg, mul_assoc, pow_bit0_abs, norm_nonneg, abs_pow] }
end
/-- One can get `f'' v w` as the limit of `h ^ (-2)` times the alternate sum of the values of `f`
along the vertices of a quadrilateral with sides `h v` and `h w` based at `x`.
In a setting where `f` is not guaranteed to be continuous at `f`, we can still
get this if we use a quadrilateral based at `h v + h w`. -/
lemma convex.is_o_alternate_sum_square
{v w : E} (h4v : x + (4 : ℝ) • v ∈ interior s) (h4w : x + (4 : ℝ) • w ∈ interior s) :
is_o (λ (h : ℝ), f (x + h • (2 • v + 2 • w)) + f (x + h • (v + w))
- f (x + h • (2 • v + w)) - f (x + h • (v + 2 • w)) - h^2 • f'' v w)
(λ h, h^2) (𝓝[Ioi (0 : ℝ)] 0) :=
begin
have A : (1 : ℝ)/2 ∈ Ioc (0 : ℝ) 1 := ⟨by norm_num, by norm_num⟩,
have B : (1 : ℝ)/2 ∈ Icc (0 : ℝ) 1 := ⟨by norm_num, by norm_num⟩,
have C : ∀ (w : E), (2 : ℝ) • w = 2 • w := λ w, by simp only [two_smul],
have h2v2w : x + (2 : ℝ) • v + (2 : ℝ) • w ∈ interior s,
{ convert s_conv.interior.add_smul_sub_mem h4v h4w B using 1,
simp only [smul_sub, smul_smul, one_div, add_sub_add_left_eq_sub, mul_add, add_smul],
norm_num,
simp only [show (4 : ℝ) = (2 : ℝ) + (2 : ℝ), by norm_num, add_smul],
abel },
have h2vww : x + (2 • v + w) + w ∈ interior s,
{ convert h2v2w using 1,
simp only [two_smul],
abel },
have h2v : x + (2 : ℝ) • v ∈ interior s,
{ convert s_conv.add_smul_sub_mem_interior xs h4v A using 1,
simp only [smul_smul, one_div, add_sub_cancel', add_right_inj],
norm_num },
have h2w : x + (2 : ℝ) • w ∈ interior s,
{ convert s_conv.add_smul_sub_mem_interior xs h4w A using 1,
simp only [smul_smul, one_div, add_sub_cancel', add_right_inj],
norm_num },
have hvw : x + (v + w) ∈ interior s,
{ convert s_conv.add_smul_sub_mem_interior xs h2v2w A using 1,
simp only [smul_smul, one_div, add_sub_cancel', add_right_inj, smul_add, smul_sub],
norm_num,
abel },
have h2vw : x + (2 • v + w) ∈ interior s,
{ convert s_conv.interior.add_smul_sub_mem h2v h2v2w B using 1,
simp only [smul_add, smul_sub, smul_smul, ← C],
norm_num,
abel },
have hvww : x + (v + w) + w ∈ interior s,
{ convert s_conv.interior.add_smul_sub_mem h2w h2v2w B using 1,
simp only [one_div, add_sub_cancel', inv_smul_smul', add_sub_add_right_eq_sub, ne.def,
not_false_iff, bit0_eq_zero, one_ne_zero],
rw two_smul,
abel },
have TA1 := s_conv.taylor_approx_two_segment hf xs hx h2vw h2vww,
have TA2 := s_conv.taylor_approx_two_segment hf xs hx hvw hvww,
convert TA1.sub TA2,
ext h,
simp only [two_smul, smul_add, ← add_assoc, continuous_linear_map.map_add,
continuous_linear_map.add_apply, pi.smul_apply,
continuous_linear_map.coe_smul', continuous_linear_map.map_smul],
abel,
end
/-- Assume that `f` is differentiable inside a convex set `s`, and that its derivative `f'` is
differentiable at a point `x`. Then, given two vectors `v` and `w` pointing inside `s`, one
has `f'' v w = f'' w v`. Superseded by `convex.second_derivative_within_at_symmetric`, which
removes the assumption that `v` and `w` point inside `s`.
-/
lemma convex.second_derivative_within_at_symmetric_of_mem_interior
{v w : E} (h4v : x + (4 : ℝ) • v ∈ interior s) (h4w : x + (4 : ℝ) • w ∈ interior s) :
f'' w v = f'' v w :=
begin
have A : is_o (λ (h : ℝ), h^2 • (f'' w v- f'' v w)) (λ h, h^2) (𝓝[Ioi (0 : ℝ)] 0),
{ convert (s_conv.is_o_alternate_sum_square hf xs hx h4v h4w).sub
(s_conv.is_o_alternate_sum_square hf xs hx h4w h4v),
ext h,
simp only [add_comm, smul_add, smul_sub],
abel },
have B : is_o (λ (h : ℝ), f'' w v - f'' v w) (λ h, (1 : ℝ)) (𝓝[Ioi (0 : ℝ)] 0),
{ have : is_O (λ (h : ℝ), 1/h^2) (λ h, 1/h^2) (𝓝[Ioi (0 : ℝ)] 0) := is_O_refl _ _,
have C := this.smul_is_o A,
apply C.congr' _ _,
{ filter_upwards [self_mem_nhds_within],
assume h hpos,
rw [← one_smul ℝ (f'' w v - f'' v w), smul_smul, smul_smul],
congr' 1,
field_simp [has_lt.lt.ne' hpos] },
{ filter_upwards [self_mem_nhds_within],
assume h hpos,
field_simp [has_lt.lt.ne' hpos, has_scalar.smul] } },
simpa only [sub_eq_zero] using (is_o_const_const_iff (@one_ne_zero ℝ _ _)).1 B,
end
omit s_conv xs hx hf
/-- If a function is differentiable inside a convex set with nonempty interior, and has a second
derivative at a point of this convex set, then this second derivative is symmetric. -/
theorem convex.second_derivative_within_at_symmetric
{s : set E} (s_conv : convex s) (hne : (interior s).nonempty)
{f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)}
(hf : ∀ x ∈ interior s, has_fderiv_at f (f' x) x)
{x : E} (xs : x ∈ s) (hx : has_fderiv_within_at f' f'' (interior s) x) (v w : E) :
f'' v w = f'' w v :=
begin
/- we work around a point `x + 4 z` in the interior of `s`. For any vector `m`,
then `x + 4 (z + t m)` also belongs to the interior of `s` for small enough `t`. This means that
we will be able to apply `second_derivative_within_at_symmetric_of_mem_interior` to show
that `f''` is symmetric, after cancelling all the contributions due to `z`. -/
rcases hne with ⟨y, hy⟩,
obtain ⟨z, hz⟩ : ∃ z, z = ((1:ℝ) / 4) • (y - x) := ⟨((1:ℝ) / 4) • (y - x), rfl⟩,
have A : ∀ (m : E), filter.tendsto (λ (t : ℝ), x + (4 : ℝ) • (z + t • m)) (𝓝 0) (𝓝 y),
{ assume m,
have : x + (4 : ℝ) • (z + (0 : ℝ) • m) = y, by simp [hz],
rw ← this,
refine tendsto_const_nhds.add _,
refine tendsto_const_nhds.smul _,
refine tendsto_const_nhds.add _,
exact continuous_at_id.smul continuous_at_const },
have B : ∀ (m : E), ∀ᶠ t in 𝓝[Ioi (0 : ℝ)] (0 : ℝ), x + (4 : ℝ) • (z + t • m) ∈ interior s,
{ assume m,
apply nhds_within_le_nhds,
apply A m,
rw [mem_interior_iff_mem_nhds] at hy,
exact interior_mem_nhds.2 hy },
-- we choose `t m > 0` such that `x + 4 (z + (t m) m)` belongs to the interior of `s`, for any
-- vector `m`.
choose t ts tpos using λ m, ((B m).and self_mem_nhds_within).exists,
-- applying `second_derivative_within_at_symmetric_of_mem_interior` to the vectors `z`
-- and `z + (t m) m`, we deduce that `f'' m z = f'' z m` for all `m`.
have C : ∀ (m : E), f'' m z = f'' z m,
{ assume m,
have : f'' (z + t m • m) (z + t 0 • 0) = f'' (z + t 0 • 0) (z + t m • m) :=
s_conv.second_derivative_within_at_symmetric_of_mem_interior hf xs hx (ts 0) (ts m),
simp only [continuous_linear_map.map_add, continuous_linear_map.map_smul, add_right_inj,
continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul', add_zero,
continuous_linear_map.zero_apply, smul_zero, continuous_linear_map.map_zero] at this,
exact smul_right_injective F (tpos m).ne' this },
-- applying `second_derivative_within_at_symmetric_of_mem_interior` to the vectors `z + (t v) v`
-- and `z + (t w) w`, we deduce that `f'' v w = f'' w v`. Cross terms involving `z` can be
-- eliminated thanks to the fact proved above that `f'' m z = f'' z m`.
have : f'' (z + t v • v) (z + t w • w) = f'' (z + t w • w) (z + t v • v) :=
s_conv.second_derivative_within_at_symmetric_of_mem_interior hf xs hx (ts w) (ts v),
simp only [continuous_linear_map.map_add, continuous_linear_map.map_smul, smul_add, smul_smul,
continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul', C] at this,
rw ← sub_eq_zero at this,
abel at this,
simp only [one_gsmul, neg_smul, sub_eq_zero, mul_comm, ← sub_eq_add_neg] at this,
apply smul_right_injective F _ this,
simp [(tpos v).ne', (tpos w).ne']
end
/-- If a function is differentiable around `x`, and has two derivatives at `x`, then the second
derivative is symmetric. -/
theorem second_derivative_symmetric_of_eventually
{f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)}
(hf : ∀ᶠ y in 𝓝 x, has_fderiv_at f (f' y) y)
(hx : has_fderiv_at f' f'' x) (v w : E) :
f'' v w = f'' w v :=
begin
rcases metric.mem_nhds_iff.1 hf with ⟨ε, εpos, hε⟩,
have A : (interior (metric.ball x ε)).nonempty,
by rwa [metric.is_open_ball.interior_eq, metric.nonempty_ball],
exact convex.second_derivative_within_at_symmetric (convex_ball x ε) A
(λ y hy, hε (interior_subset hy)) (metric.mem_ball_self εpos) hx.has_fderiv_within_at v w,
end
/-- If a function is differentiable, and has two derivatives at `x`, then the second
derivative is symmetric. -/
theorem second_derivative_symmetric
{f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)}
(hf : ∀ y, has_fderiv_at f (f' y) y)
(hx : has_fderiv_at f' f'' x) (v w : E) :
f'' v w = f'' w v :=
second_derivative_symmetric_of_eventually (filter.eventually_of_forall hf) hx v w
|
bc5c61f70f4075efeef4efb6091a955a49205988
|
626e312b5c1cb2d88fca108f5933076012633192
|
/src/measure_theory/measure/regular.lean
|
02d4f189d66c18c8dd990f0452b1bdc5d00a9a4f
|
[
"Apache-2.0"
] |
permissive
|
Bioye97/mathlib
|
9db2f9ee54418d29dd06996279ba9dc874fd6beb
|
782a20a27ee83b523f801ff34efb1a9557085019
|
refs/heads/master
| 1,690,305,956,488
| 1,631,067,774,000
| 1,631,067,774,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 37,443
|
lean
|
/-
Copyright (c) 2021 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris Van Doorn
-/
import measure_theory.constructions.borel_space
/-!
# Regular measures
A measure is `regular` if it satisfies the following properties:
* it is finite on compact sets;
* it is outer regular for measurable sets with respect to open sets: the measure of any measurable
set `A` is the infimum of `μ U` over all open sets `U` containing `A`;
* it is inner regular for open sets with respect to compacts sets: the measure of any open set `U`
is the supremum of `μ K` over all compact sets `K` contained in `U`.
A measure is `weakly_regular` if it satisfies the following properties:
* it is outer regular for measurable sets with respect to open sets: the measure of any measurable
set `A` is the infimum of `μ U` over all open sets `U` containing `A`;
* it is inner regular for open sets with respect to closed sets: the measure of any open set `U`
is the supremum of `μ F` over all compact sets `F` contained in `U`.
Regularity implies weak regularity. Both these conditions are registered as typeclasses for a
measure `μ`, and this implication is recorded as an instance.
These conditions imply inner regularity for all measurable sets of finite measure (with respect to
compact sets or closed sets respectively), but in general not for all sets. For a counterexample,
consider the group `ℝ × ℝ` where the first factor has the discrete topology and the second one the
usual topology. It is a locally compact Hausdorff topological group, with Haar measure equal to
Lebesgue measure on each vertical fiber. The set `ℝ × {0}` has infinite measure (by outer
regularity), but any compact set it contains has zero measure (as it is finite).
Several authors require as a definition of regularity that all measurable sets are inner regular.
We have opted for the slightly weaker definition above as it holds for all Haar measures, it is
enough for essentially all applications, and it is equivalent to the other definition when the
measure is finite.
The interest of the notion of weak regularity is that it is enough for many applications, and it
is automatically satisfied by any finite measure on a metric space.
## Main definitions and results
* `regular μ`: a typeclass registering that a measure `μ` on a topological space is regular.
* `measurable_set.measure_eq_infi_is_open'` asserts that, when `μ` is regular, the measure of a
measurable set is the infimum of the measure of open sets containing it. The unprimed version
is reserved for weakly regular measures, as it should apply most of the time. Such open sets
with suitable measures can be constructed with `measurable_set.exists_is_open_lt_of_lt'`.
* `is_open.measure_eq_supr_is_compact` asserts that the measure of an open set is the supremum of
the measure of compact sets it contains. Such a compact set with suitable measure can be
constructed with `is_open.exists_lt_is_compact`.
* `measurable_set.measure_eq_supr_is_compact_of_lt_top` asserts that the measure of a measurable set
of finite measure is the supremum of the measure of compact sets it contains. Such a compact set
with suitable measure can be constructed with `measurable_set.exists_lt_is_compact_of_lt_top` or
`measurable_set.exists_lt_is_compact_of_lt_top_of_pos`.
* `regular.of_sigma_compact_space_of_is_locally_finite_measure` is an instance registering that a
locally finite measure on a locally compact metric space is regular (in fact, an emetric space
is enough).
* `weakly_regular μ`: a typeclass registering that a measure `μ` on a topological space is
weakly regular.
* `measurable_set.measure_eq_infi_is_open`, `measurable_set.exists_is_open_lt_of_lt`,
`is_open.measure_eq_supr_is_closed`, `is_open.exists_lt_is_closed`,
`measurable_set.measure_eq_supr_is_closed_of_lt_top`,
`measurable_set.exists_lt_is_closed_of_lt_top` and
`measurable_set.exists_lt_is_closed_of_lt_top_of_pos`
state the corresponding properties for weakly regular measures.
* `weakly_regular.of_pseudo_emetric_space_of_is_finite_measure` is an instance registering that a
finite measure on a metric space is weakly regular (in fact, a pseudo emetric space is enough).
## Implementation notes
The main nontrivial statement is `weakly_regular.exists_closed_subset_self_subset_open`, expressing
that in a finite measure space, if every open set can be approximated from inside by closed sets,
then any measurable set can be approximated from inside by closed sets and from outside by open
sets. This statement is proved by measurable induction, starting from open sets and checking that
it is stable by taking complements (this is the point of this condition, being symmetrical between
inside and outside) and countable disjoint unions.
Once this statement is proved, one deduces results for general measures from this statement, by
restricting them to finite measure sets (and proving that this restriction is weakly regular,
using again the same statement).
## References
[Halmos, Measure Theory, §52][halmos1950measure]. Note that Halmos uses an unusual definition of
Borel sets (for him, they are elements of the `σ`-algebra generated by compact sets!), so his
proofs or statements do not apply directly.
[Billingsley, Convergence of Probability Measures][billingsley1999]
-/
open set filter
open_locale ennreal topological_space nnreal big_operators
namespace measure_theory
namespace measure
variables {α β : Type*} [measurable_space α] [topological_space α] {μ : measure α}
/-- A measure `μ` is regular if
- it is finite on all compact sets;
- it is outer regular: `μ(A) = inf {μ(U) | A ⊆ U open}` for `A` measurable;
- it is inner regular for open sets, using compact sets:
`μ(U) = sup {μ(K) | K ⊆ U compact}` for `U` open. -/
class regular (μ : measure α) : Prop :=
(lt_top_of_is_compact : ∀ ⦃K : set α⦄, is_compact K → μ K < ∞)
(outer_regular : ∀ ⦃A : set α⦄, measurable_set A →
(⨅ (U : set α) (h : is_open U) (h2 : A ⊆ U), μ U) ≤ μ A)
(inner_regular : ∀ ⦃U : set α⦄, is_open U →
μ U ≤ ⨆ (K : set α) (h : is_compact K) (h2 : K ⊆ U), μ K)
/-- A measure `μ` is weakly regular if
- it is outer regular: `μ(A) = inf { μ(U) | A ⊆ U open }` for `A` measurable;
- it is inner regular for open sets, using closed sets:
`μ(U) = sup {μ(F) | F ⊆ U compact}` for `U` open. -/
class weakly_regular (μ : measure α) : Prop :=
(outer_regular : ∀ ⦃A : set α⦄, measurable_set A →
(⨅ (U : set α) (h : is_open U) (h2 : A ⊆ U), μ U) ≤ μ A)
(inner_regular : ∀ ⦃U : set α⦄, is_open U →
μ U ≤ ⨆ (F : set α) (h : is_closed F) (h2 : F ⊆ U), μ F)
/-- A regular measure is weakly regular. -/
@[priority 100] -- see Note [lower instance priority]
instance regular.weakly_regular [t2_space α] [regular μ] : weakly_regular μ :=
{ outer_regular := regular.outer_regular,
inner_regular := λ U hU, calc
μ U ≤ ⨆ (K : set α) (h : is_compact K) (h2 : K ⊆ U), μ K : regular.inner_regular hU
... ≤ ⨆ (F : set α) (h : is_closed F) (h2 : F ⊆ U), μ F :
by { simp only [supr_and'], exact bsupr_le_bsupr' (λ i hi, ⟨hi.1.is_closed, hi.2⟩) } }
namespace regular
/-- The measure of a measurable set is the infimum of the measures of open sets containing it.
The unprimed version is reserved for weakly regular measures, as regular measures are automatically
weakly regular most of the time. -/
lemma _root_.measurable_set.measure_eq_infi_is_open' ⦃A : set α⦄ (hA : measurable_set A)
(μ : measure α) [regular μ] :
μ A = (⨅ (U : set α) (h : is_open U) (h2 : A ⊆ U), μ U) :=
le_antisymm (le_infi $ λ s, le_infi $ λ hs, le_infi $ λ h2s, μ.mono h2s) (regular.outer_regular hA)
/-- Given `r` larger than the measure of a measurable set `A`, there exists an open superset of `A`
with measure `< r`. The unprimed version is reserved for weakly regular measures, as regular
measures are automatically weakly regular most of the time. -/
lemma _root_.measurable_set.exists_is_open_lt_of_lt'
[regular μ] ⦃A : set α⦄ (hA : measurable_set A) (r : ℝ≥0∞) (hr : μ A < r) :
∃ U, is_open U ∧ A ⊆ U ∧ μ U < r :=
begin
rw hA.measure_eq_infi_is_open' μ at hr,
simpa only [infi_lt_iff, exists_prop] using hr
end
/-- The measure of an open set is the supremum of the measures of compact sets it contains. -/
lemma _root_.is_open.measure_eq_supr_is_compact ⦃U : set α⦄ (hU : is_open U)
(μ : measure α) [regular μ] :
μ U = (⨆ (K : set α) (h : is_compact K) (h2 : K ⊆ U), μ K) :=
le_antisymm (regular.inner_regular hU) (supr_le $ λ s, supr_le $ λ hs, supr_le $ λ h2s, μ.mono h2s)
lemma _root_.is_open.exists_lt_is_compact [regular μ] ⦃U : set α⦄ (hU : is_open U)
{r : ℝ≥0∞} (hr : r < μ U) :
∃ K, is_compact K ∧ K ⊆ U ∧ r < μ K :=
begin
rw hU.measure_eq_supr_is_compact at hr,
simpa only [lt_supr_iff, exists_prop] using hr,
end
lemma exists_compact_not_null [regular μ] : (∃ K, is_compact K ∧ μ K ≠ 0) ↔ μ ≠ 0 :=
by simp_rw [ne.def, ← measure_univ_eq_zero, is_open_univ.measure_eq_supr_is_compact,
ennreal.supr_eq_zero, not_forall, exists_prop, subset_univ, true_and]
protected lemma map [opens_measurable_space α] [measurable_space β] [topological_space β]
[t2_space β] [borel_space β] [regular μ] (f : α ≃ₜ β) :
(measure.map f μ).regular :=
begin
have hf := f.measurable,
have h2f := f.to_equiv.injective.preimage_surjective,
have h3f := f.to_equiv.surjective,
split,
{ intros K hK, rw [map_apply hf hK.measurable_set],
apply regular.lt_top_of_is_compact,
rwa f.compact_preimage },
{ intros A hA,
rw [map_apply hf hA, (hf hA).measure_eq_infi_is_open'],
refine le_of_eq _,
apply infi_congr (preimage f) h2f,
intro U,
apply infi_congr_Prop f.is_open_preimage,
intro hU,
apply infi_congr_Prop h3f.preimage_subset_preimage_iff,
intro h2U,
rw [map_apply hf hU.measurable_set], },
{ intros U hU,
rw [map_apply hf hU.measurable_set, (hU.preimage f.continuous).measure_eq_supr_is_compact],
refine ge_of_eq _,
apply supr_congr (preimage f) h2f,
intro K,
apply supr_congr_Prop f.compact_preimage,
intro hK,
apply supr_congr_Prop h3f.preimage_subset_preimage_iff,
intro h2U,
rw [map_apply hf hK.measurable_set] }
end
protected lemma smul [regular μ] {x : ℝ≥0∞} (hx : x < ∞) :
(x • μ).regular :=
begin
split,
{ intros K hK, exact ennreal.mul_lt_top hx (regular.lt_top_of_is_compact hK) },
{ intros A hA, rw [coe_smul],
refine le_trans _ (ennreal.mul_left_mono $ regular.outer_regular hA),
simp only [infi_and'], simp only [infi_subtype'],
haveI : nonempty {s : set α // is_open s ∧ A ⊆ s} := ⟨⟨set.univ, is_open_univ, subset_univ _⟩⟩,
rw [ennreal.mul_infi], refl', exact ne_of_lt hx },
{ intros U hU,
rw [coe_smul],
refine le_trans (ennreal.mul_left_mono $ regular.inner_regular hU) _,
simp only [supr_and'],
simp only [supr_subtype'],
rw [ennreal.mul_supr], refl' }
end
/-- A regular measure in a σ-compact space is σ-finite. -/
@[priority 100] -- see Note [lower instance priority]
instance sigma_finite [opens_measurable_space α] [t2_space α] [sigma_compact_space α]
[regular μ] : sigma_finite μ :=
⟨⟨{ set := compact_covering α,
set_mem := λ n, (is_compact_compact_covering α n).measurable_set,
finite := λ n, regular.lt_top_of_is_compact $ is_compact_compact_covering α n,
spanning := Union_compact_covering α }⟩⟩
end regular
namespace weakly_regular
lemma _root_.measurable_set.measure_eq_infi_is_open ⦃A : set α⦄ (hA : measurable_set A)
(μ : measure α) [weakly_regular μ] :
μ A = (⨅ (U : set α) (h : is_open U) (h2 : A ⊆ U), μ U) :=
le_antisymm (le_infi $ λ s, le_infi $ λ hs, le_infi $ λ h2s, μ.mono h2s)
(weakly_regular.outer_regular hA)
lemma _root_.measurable_set.exists_is_open_lt_of_lt
[weakly_regular μ] ⦃A : set α⦄ (hA : measurable_set A) (r : ℝ≥0∞) (hr : μ A < r) :
∃ U, is_open U ∧ A ⊆ U ∧ μ U < r :=
begin
rw hA.measure_eq_infi_is_open μ at hr,
simpa only [infi_lt_iff, exists_prop] using hr
end
lemma _root_.is_open.measure_eq_supr_is_closed ⦃U : set α⦄ (hU : is_open U)
(μ : measure α) [weakly_regular μ] :
μ U = (⨆ (F : set α) (h : is_closed F) (h2 : F ⊆ U), μ F) :=
le_antisymm (weakly_regular.inner_regular hU)
(supr_le $ λ s, supr_le $ λ hs, supr_le $ λ h2s, μ.mono h2s)
lemma _root_.is_open.exists_lt_is_closed_of_gt
[weakly_regular μ] ⦃U : set α⦄ (hU : is_open U) (r : ℝ≥0∞) (hr : r < μ U) :
∃ F, is_closed F ∧ F ⊆ U ∧ r < μ F :=
begin
rw hU.measure_eq_supr_is_closed at hr,
simpa only [lt_supr_iff, exists_prop] using hr,
end
/-- Given a weakly regular measure, any finite measure set is contained in a finite measure open
set.-/
lemma exists_subset_is_open_measure_lt_top [weakly_regular μ] {A : set α} (h'A : μ A < ∞) :
∃ U, is_open U ∧ A ⊆ U ∧ μ U < ∞ :=
begin
rcases exists_measurable_superset μ A with ⟨B, AB, B_meas, μB⟩,
rw ← μB at h'A,
have : (⨅ (U : set α) (h : is_open U) (h2 : B ⊆ U), μ U) < μ B + 1,
{ refine lt_of_le_of_lt (weakly_regular.outer_regular B_meas) _,
simpa only [add_zero] using (ennreal.add_lt_add_iff_left h'A).mpr ennreal.zero_lt_one },
simp only [infi_lt_iff] at this,
rcases this with ⟨U, U_open, BU, hU⟩,
exact ⟨U, U_open, subset.trans AB BU, hU.trans (ennreal.add_lt_top.2 ⟨h'A, ennreal.one_lt_top⟩)⟩
end
/-- In a finite measure space, assume that any open set can be approximated from inside by closed
sets. Then any measurable set can be approximated from inside by closed sets, and from outside
by open sets. -/
lemma exists_closed_subset_self_subset_open_of_pos [borel_space α]
(μ : measure α) [is_finite_measure μ]
(h0 : ∀ (U : set α), is_open U → μ U ≤ ⨆ (F : set α) (hF : is_closed F) (FU : F ⊆ U), μ F) :
∀ ⦃s : set α⦄ (hs : measurable_set s),
∀ ε > 0, (∃ (U : set α), is_open U ∧ s ⊆ U ∧ μ U ≤ μ s + ε)
∧ (∃ (F : set α), is_closed F ∧ F ⊆ s ∧ μ s ≤ μ F + ε) :=
begin
refine measurable_space.induction_on_inter borel_space.measurable_eq is_pi_system_is_open _ _ _ _,
/- The proof is by measurable induction: we should check that the property is true for the empty
set, for open sets, and is stable by taking the complement and by taking countable disjoint
unions. The point of the property we are proving is that it is stable by taking complements
(exchanging the roles of closed and open sets and thanks to the finiteness of the measure). -/
-- check for empty set
{ assume ε hε,
exact ⟨⟨∅, is_open_empty, subset.refl _, by simp only [measure_empty, zero_le]⟩,
⟨∅, is_closed_empty, subset.refl _, by simp only [measure_empty, zero_le]⟩⟩ },
-- check for open sets. This is essentially our assumption `h0`.
{ assume U hU ε hε,
refine ⟨⟨U, hU, subset.refl _, le_self_add⟩, _⟩,
have : μ U + ε ≤ ⨆ (F : set α) (hF : is_closed F) (FU : F ⊆ U), (μ F + ε),
{ haveI : nonempty {i // is_closed i ∧ i ⊆ U} := ⟨⟨∅, is_closed_empty, empty_subset _⟩⟩,
simp_rw [supr_and', supr_subtype', ← ennreal.supr_add],
refine add_le_add _ (le_refl _),
convert h0 U hU using 1,
simp_rw [supr_and', supr_subtype'], },
have : μ U < (⨆ (F : set α) (hF : is_closed F) (FU : F ⊆ U), (μ F + ε)),
{ apply lt_of_lt_of_le _ this,
simpa using (ennreal.add_lt_add_iff_left (measure_lt_top μ U)).2 hε },
simp only [lt_supr_iff] at this,
rcases this with ⟨F, F_closed, FU, μF⟩,
exact ⟨F, F_closed, FU, μF.le⟩ },
-- check for complements
{ assume s hs h ε εpos,
rcases h ε εpos with ⟨⟨U, U_open, U_subset, nu_U⟩, ⟨F, F_closed, F_subset, nu_F⟩⟩,
refine ⟨⟨Fᶜ, is_open_compl_iff.2 F_closed, compl_subset_compl.2 F_subset, _⟩,
⟨Uᶜ, is_closed_compl_iff.2 U_open, compl_subset_compl.2 U_subset, _⟩⟩,
{ apply ennreal.le_of_add_le_add_left (measure_lt_top μ F),
calc
μ F + μ Fᶜ = μ s + μ sᶜ :
by rw [measure_add_measure_compl hs, measure_add_measure_compl F_closed.measurable_set]
... ≤ (μ F + ε) + μ sᶜ : add_le_add nu_F (le_refl _)
... = μ F + (μ sᶜ + ε) : by abel },
{ apply ennreal.le_of_add_le_add_left (measure_lt_top μ s),
calc
μ s + μ sᶜ = μ U + μ Uᶜ :
by rw [measure_add_measure_compl hs, measure_add_measure_compl U_open.measurable_set]
... ≤ (μ s + ε) + μ Uᶜ : add_le_add nu_U (le_refl _)
... = μ s + (μ Uᶜ + ε) : by abel } },
-- check for disjoint unions
{ assume s s_disj s_meas hs ε εpos,
split,
-- the approximating open set is constructed by taking for each `s n` an approximating open set
-- `U n` with measure at most `μ (s n) + δ n` for a summable `δ`, and taking the union of these.
{ rcases ennreal.exists_pos_sum_of_encodable' εpos ℕ with ⟨δ, δpos, hδ⟩,
have : ∀ n, ∃ (U : set α), is_open U ∧ s n ⊆ U ∧ μ U ≤ μ (s n) + δ n :=
λ n, (hs n _ (δpos n).gt).1,
choose U hU using this,
refine ⟨(⋃ n, U n), is_open_Union (λ n, (hU n).1), Union_subset_Union (λ n, (hU n).2.1), _⟩,
calc
μ (⋃ (n : ℕ), U n)
≤ ∑' n, μ (U n) : measure_Union_le _
... ≤ ∑' n, (μ (s n) + δ n) : ennreal.tsum_le_tsum (λ n, (hU n).2.2)
... ≤ μ (⋃ (i : ℕ), s i) + ε :
begin
rw [ennreal.tsum_add],
refine add_le_add (le_of_eq _) hδ.le,
exact (measure_Union s_disj s_meas).symm,
end },
-- the approximating closed set is constructed by considering finitely many sets `s i`, which
-- cover all the measure up to `ε/2`, approximating each of these by a closed set `F i`, and
-- taking the union of these (finitely many) `F i`.
{ set δ := ε / 2 with hδ,
have δpos : 0 < δ := ennreal.half_pos εpos,
have L : tendsto (λ n, ∑ i in finset.range n, μ (s i) + δ) at_top (𝓝 (μ (⋃ i, s i) + δ)),
{ rw measure_Union s_disj s_meas,
refine tendsto.add (ennreal.tendsto_nat_tsum _) tendsto_const_nhds },
have nu_lt : μ (⋃ i, s i) < μ (⋃ i, s i) + δ,
by simpa only [add_zero] using (ennreal.add_lt_add_iff_left (measure_lt_top μ _)).mpr δpos,
obtain ⟨n, hn, npos⟩ :
∃ n, (μ (⋃ (i : ℕ), s i) < ∑ (i : ℕ) in finset.range n, μ (s i) + δ) ∧ (0 < n) :=
(((tendsto_order.1 L).1 _ nu_lt).and (eventually_gt_at_top 0)).exists,
have : ∀ i, ∃ (F : set α), is_closed F ∧ F ⊆ s i ∧ μ (s i) ≤ μ F + δ / n :=
λ i, (hs i _ (ennreal.div_pos_iff.2 ⟨ne_of_gt δpos, ennreal.nat_ne_top n⟩)).2,
choose F hF using this,
have F_disj: pairwise (disjoint on F) :=
s_disj.mono (λ i j hij, disjoint.mono (hF i).2.1 (hF j).2.1 hij),
refine ⟨⋃ i ∈ finset.range n, F i, _, _, _⟩,
{ exact is_closed_bUnion (by simpa using finite_lt_nat n) (λ i hi, (hF i).1) },
{ assume x hx,
simp only [exists_prop, mem_Union, finset.mem_range] at hx,
rcases hx with ⟨i, i_lt, hi⟩,
simp only [mem_Union],
exact ⟨i, (hF i).2.1 hi⟩ },
{ calc
μ (⋃ (i : ℕ), s i)
≤ ∑ (i : ℕ) in finset.range n, μ (s i) + δ : hn.le
... ≤ (∑ (i : ℕ) in finset.range n, (μ (F i) + δ / n)) + δ :
add_le_add (finset.sum_le_sum (λ i hi, (hF i).2.2)) (le_refl _)
... = μ (⋃ i ∈ finset.range n, F i) + ε :
begin
simp only [finset.sum_add_distrib, finset.sum_const, nsmul_eq_mul, finset.card_range],
rw [ennreal.mul_div_cancel' _ (ennreal.nat_ne_top n),
measure_bUnion_finset (F_disj.pairwise_on _) (λ i hi, (hF i).1.measurable_set),
hδ, add_assoc, ennreal.add_halves],
simpa only [ne.def, nat.cast_eq_zero] using ne_of_gt npos
end } } }
end
/-- In a finite measure space, if every open set can be approximated from inside by closed sets,
then the measure is weakly regular -/
theorem weakly_regular_of_inner_regular_of_is_finite_measure [borel_space α]
(μ : measure α) [is_finite_measure μ]
(h0 : ∀ (U : set α), is_open U → μ U ≤ ⨆ (F : set α) (hF : is_closed F) (FU : F ⊆ U), μ F) :
weakly_regular μ :=
{ outer_regular := begin
assume s hs,
apply ennreal.le_of_forall_pos_le_add (λ ε εpos h, le_of_lt _),
rcases exists_between (ennreal.coe_lt_coe.2 εpos) with ⟨δ, δpos, δε⟩,
simp only [infi_lt_iff],
rcases (exists_closed_subset_self_subset_open_of_pos μ h0 hs δ δpos).1
with ⟨U, U_open, sU, μU⟩,
refine ⟨U, U_open, sU, μU.trans_lt _⟩,
rwa ennreal.add_lt_add_iff_left (measure_lt_top μ s),
end,
inner_regular := h0 }
/-- The restriction of a weakly regular measure to an open set of finite measure is
weakly regular. Superseded by `restrict_of_measurable_set`, proving the same statement for
measurable sets instead of open sets. -/
lemma restrict_of_is_open [borel_space α] [weakly_regular μ]
(U : set α) (hU : is_open U) (h'U : μ U < ∞) : weakly_regular (μ.restrict U) :=
begin
haveI : fact (μ U < ∞) := ⟨h'U⟩,
refine weakly_regular_of_inner_regular_of_is_finite_measure _ (λ V V_open, _),
simp only [restrict_apply' hU.measurable_set],
refine le_trans (weakly_regular.inner_regular (V_open.inter hU)) _,
simp only [and_imp, supr_le_iff, subset_inter_iff],
assume F F_closed FV FU,
have : F = F ∩ U :=
subset.antisymm (by simp [subset.refl, FU]) (inter_subset_left _ _),
conv_lhs {rw this},
simp_rw [supr_and', supr_subtype'],
exact le_supr (λ s : {s // is_closed s ∧ s ⊆ V}, μ (s ∩ U)) ⟨F, F_closed, FV⟩,
end
/-- Given a weakly regular measure of finite mass, any measurable set can be approximated from
inside by closed sets. -/
lemma _root_.measurable_set.measure_eq_supr_is_closed_of_is_finite_measure
[borel_space α] (μ : measure α) [is_finite_measure μ] [weakly_regular μ]
⦃A : set α⦄ (hA : measurable_set A) :
μ A = (⨆ (F : set α) (h : is_closed F) (h2 : F ⊆ A), μ F) :=
begin
refine le_antisymm _ (supr_le $ λ s, supr_le $ λ hs, supr_le $ λ h2s, μ.mono h2s),
apply ennreal.le_of_forall_pos_le_add (λ ε εpos h, le_of_lt _),
rcases exists_between (ennreal.coe_lt_coe.2 εpos) with ⟨δ, δpos, δε⟩,
haveI : nonempty {F // is_closed F ∧ F ⊆ A} := ⟨⟨∅, is_closed_empty, empty_subset _⟩⟩,
simp_rw [supr_and', supr_subtype', ennreal.supr_add],
simp only [lt_supr_iff],
rcases (exists_closed_subset_self_subset_open_of_pos μ
weakly_regular.inner_regular hA δ δpos).2 with ⟨F, F_closed, sF, μF⟩,
refine ⟨⟨F, F_closed, sF⟩, μF.trans_lt _⟩,
exact (ennreal.add_lt_add_iff_left (measure_lt_top μ F)).2 δε,
end
/-- Given a weakly regular measure, any measurable set of finite mass can be approximated from
inside by closed sets. -/
lemma _root_.measurable_set.measure_eq_supr_is_closed_of_lt_top [borel_space α] [weakly_regular μ]
⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A < ∞) :
μ A = (⨆ (F : set α) (h : is_closed F) (h2 : F ⊆ A), μ F) :=
begin
-- this is proved by restricting the measure to an open set of finite measure containing `A`
-- (which exists by outer regularity) and using the result for finite measures applied to this
-- restriction, as it is weakly regular thanks to `restrict_of_is_open`.
refine le_antisymm _ (supr_le $ λ s, supr_le $ λ hs, supr_le $ λ h2s, μ.mono h2s),
obtain ⟨U, U_open, AU, μU⟩ : ∃ U, is_open U ∧ A ⊆ U ∧ μ U < ∞ :=
exists_subset_is_open_measure_lt_top h'A,
haveI : fact (μ U < ∞) := ⟨μU⟩,
haveI : weakly_regular (μ.restrict U) := restrict_of_is_open U U_open μU,
calc μ A = (μ.restrict U) A :
begin
rw restrict_apply' U_open.measurable_set,
congr' 1,
exact subset.antisymm (subset_inter (subset.refl _) AU) (inter_subset_left _ _)
end
... = (⨆ (F : set α) (h : is_closed F) (h2 : F ⊆ A), (μ.restrict U) F) :
hA.measure_eq_supr_is_closed_of_is_finite_measure _
... ≤ ⨆ (F : set α) (h : is_closed F) (h2 : F ⊆ A), μ F :
begin
refine supr_le_supr (λ F, _),
refine supr_le_supr (λ F_closed, _),
refine supr_le_supr (λ FA, _),
rw restrict_apply' U_open.measurable_set,
apply measure_mono (inter_subset_left _ _),
end
end
lemma _root_.measurable_set.exists_lt_is_closed_of_lt_top [borel_space α] [weakly_regular μ]
⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A < ∞) {r : ℝ≥0∞} (hr : r < μ A) :
∃ F, is_closed F ∧ F ⊆ A ∧ r < μ F :=
begin
rw hA.measure_eq_supr_is_closed_of_lt_top h'A at hr,
simpa only [lt_supr_iff, exists_prop] using hr,
end
lemma _root_.measurable_set.exists_lt_is_closed_of_lt_top_of_pos [borel_space α] [weakly_regular μ]
⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A < ∞) {ε : ℝ≥0∞} (εpos : 0 < ε) :
∃ F, is_closed F ∧ F ⊆ A ∧ μ A < μ F + ε :=
begin
have : μ A < ⨆ (F : set α) (h : is_closed F) (h2 : F ⊆ A), (μ F + ε),
{ haveI : nonempty {F // is_closed F ∧ F ⊆ A} := ⟨⟨∅, is_closed_empty, empty_subset _⟩⟩,
simp_rw [hA.measure_eq_supr_is_closed_of_lt_top h'A, supr_and',
supr_subtype', ← ennreal.supr_add],
simpa only [add_zero, ennreal.coe_zero] using (ennreal.add_lt_add_iff_left _).mpr εpos,
convert h'A,
simp_rw [hA.measure_eq_supr_is_closed_of_lt_top h'A, supr_and', supr_subtype'] },
simpa only [lt_supr_iff, exists_prop],
end
/-- The restriction of a weakly regular measure to a measurable set of finite measure is
weakly regular. -/
lemma restrict_of_measurable_set [borel_space α] [weakly_regular μ]
(A : set α) (hA : measurable_set A) (h'A : μ A < ∞) : weakly_regular (μ.restrict A) :=
begin
haveI : fact (μ A < ∞) := ⟨h'A⟩,
refine weakly_regular_of_inner_regular_of_is_finite_measure _ (λ V V_open, _),
simp only [restrict_apply' hA],
rw (V_open.measurable_set.inter hA).measure_eq_supr_is_closed_of_lt_top,
{ simp only [and_imp, supr_le_iff, subset_inter_iff],
assume F F_closed FV FU,
have : F = F ∩ A :=
subset.antisymm (by simp [subset.refl, FU]) (inter_subset_left _ _),
conv_lhs {rw this},
simp_rw [supr_and', supr_subtype'],
exact le_supr (λ s : {s // is_closed s ∧ s ⊆ V}, μ (s ∩ A)) ⟨F, F_closed, FV⟩ },
{ exact lt_of_le_of_lt (measure_mono (inter_subset_right _ _)) h'A },
{ apply_instance }
end
/-- In a metric space (or even a pseudo emetric space), an open set can be approximated from inside
by closed sets. -/
lemma inner_regular_of_pseudo_emetric_space {X : Type*}
[pseudo_emetric_space X] [measurable_space X] [borel_space X] (μ : measure X)
(U : set X) (U_open : is_open U) :
μ U ≤ ⨆ (F : set X) (hF : is_closed F) (FU : F ⊆ U), μ F :=
begin
rcases U_open.exists_Union_is_closed with ⟨F, F_closed, F_subset, F_Union, F_mono⟩,
conv_lhs { rw ← F_Union },
rw measure_Union_eq_supr (λ n, (F_closed n).measurable_set) F_mono.directed_le,
simp only [supr_le_iff],
assume n,
simp_rw [supr_and', supr_subtype'],
exact le_supr (λ s : {s // is_closed s ∧ s ⊆ U}, μ s) ⟨F n, F_closed n, F_subset n⟩,
end
/-- Any finite measure on a metric space (or even a pseudo emetric space) is weakly regular. -/
@[priority 100] -- see Note [lower instance priority]
instance of_pseudo_emetric_space_of_is_finite_measure {X : Type*} [pseudo_emetric_space X]
[measurable_space X] [borel_space X] (μ : measure X) [is_finite_measure μ] :
weakly_regular μ :=
weakly_regular_of_inner_regular_of_is_finite_measure μ $ inner_regular_of_pseudo_emetric_space μ
end weakly_regular
namespace regular
/-- Any locally finite measure on a sigma compact locally compact metric space is regular. -/
@[priority 100] -- see Note [lower instance priority]
instance of_sigma_compact_space_of_is_locally_finite_measure {X : Type*}
[emetric_space X] [sigma_compact_space X] [locally_compact_space X]
[measurable_space X] [borel_space X] (μ : measure X)
[is_locally_finite_measure μ] : regular μ :=
{ lt_top_of_is_compact := λ K hK, hK.measure_lt_top,
inner_regular :=
begin
/- Given an open set, it can be approximated from inside by closed sets thanks to
`inner_regular_of_pseudo_emetric_space`. Each such closed set `F` can be approximated by a
compact set `B n ∩ F`, using a compact exhaustion `B n` of the space. -/
assume U U_open,
refine (weakly_regular.inner_regular_of_pseudo_emetric_space μ U U_open).trans _,
simp only [supr_le_iff],
assume F F_closed FU,
have B : compact_exhaustion X := default _,
have : F = ⋃ n, B n ∩ F, by rw [← Union_inter, B.Union_eq, univ_inter],
rw [this, measure_Union_eq_supr
(λ n, (B.is_compact n).measurable_set.inter F_closed.measurable_set)],
{ simp_rw [supr_le_iff, supr_and', supr_subtype'],
assume n,
exact le_supr (λ K : {K // is_compact K ∧ K ⊆ U}, μ K)
⟨B n ∩ F, is_compact.inter_right (B.is_compact n) F_closed,
subset.trans (inter_subset_right _ _) FU⟩ },
{ apply (monotone_nat_of_le_succ (λ n, _)).directed_le,
exact inter_subset_inter_left _ (B.subset_succ n) },
end,
outer_regular :=
begin
/- let `B n` be a compact exhaustion of the space, and let `C n = B n \ B (n-1)`. Consider a
measurable set `A`. Then `A ∩ C n` is a set of finite measure, that can be approximated by an
open set `U n` (by using the fact that the measure restricted to `B (n+1)` is finite, and
therefore weakly regular). The union of the `U n` is an open set containing `A`, with measure
arbitrarily close to that of `A`.
-/
assume A hA,
apply ennreal.le_of_forall_pos_le_add (λ ε εpos μA, le_of_lt _),
rcases ennreal.exists_pos_sum_of_encodable' (ennreal.coe_pos.2 εpos) ℕ with ⟨δ, δpos, hδ⟩,
have B : compact_exhaustion X := default _,
let C := disjointed (λ n, B n),
have C_meas : ∀ n, measurable_set (C n) :=
measurable_set.disjointed (λ n, (B.is_compact n).measurable_set),
have A_eq : A = (⋃ n, A ∩ C n),
by simp_rw [← inter_Union, C, Union_disjointed, compact_exhaustion.Union_eq, inter_univ],
have μA_eq : μ A = ∑' n, μ (A ∩ C n),
{ conv_lhs { rw A_eq },
rw measure_Union,
{ assume m n hmn,
exact disjoint.mono (inter_subset_right _ _) (inter_subset_right _ _)
(disjoint_disjointed _ m n hmn), },
{ exact (λ n, hA.inter (C_meas n)) } },
have : ∀ n, ∃ U, is_open U ∧ (A ∩ C n ⊆ U) ∧ (μ U ≤ μ (A ∩ C n) + δ n),
{ assume n,
set ν := μ.restrict (B (n+1)) with hν,
haveI : is_finite_measure ν :=
⟨begin
rw [restrict_apply measurable_set.univ, univ_inter],
exact is_compact.measure_lt_top (B.is_compact _),
end⟩,
have : (⨅ (U : set X) (h : is_open U) (h2 : A ∩ C n ⊆ U), ν U) < ν (A ∩ C n) + δ n :=
begin
refine (weakly_regular.outer_regular (hA.inter (C_meas n))).trans_lt _,
simpa only [add_zero] using (ennreal.add_lt_add_iff_left (measure_lt_top ν _)).mpr (δpos n),
end,
simp only [infi_lt_iff] at this,
rcases this with ⟨U, U_open, UA, νU⟩,
refine ⟨U ∩ interior (B (n+1)), U_open.inter is_open_interior, _, _⟩,
{ simp only [UA, true_and, subset_inter_iff],
refine (inter_subset_right _ _).trans _,
exact (disjointed_subset _ n).trans (B.subset_interior_succ _) },
{ simp only [hν, restrict_apply' (B.is_compact _).measurable_set] at νU,
calc μ (U ∩ interior (B (n + 1))) ≤ μ (U ∩ B (n + 1)) :
measure_mono (inter_subset_inter_right _ interior_subset)
... ≤ μ (A ∩ C n ∩ B (n + 1)) + δ n : νU.le
... ≤ μ (A ∩ C n) + δ n :
add_le_add (measure_mono (inter_subset_left _ _)) (le_refl _) } },
choose U hU using this,
simp_rw [infi_lt_iff],
refine ⟨⋃ n, U n, is_open_Union (λ n, (hU n).1), _, _⟩,
{ rw A_eq, exact Union_subset_Union (λ n, (hU n).2.1) },
{ calc μ (⋃ (n : ℕ), U n)
≤ ∑' n, μ (U n) : measure_Union_le _
... ≤ ∑' n, (μ (A ∩ C n) + δ n) : ennreal.tsum_le_tsum (λ n, (hU n).2.2)
... < μ A + ε :
by { rw [ennreal.tsum_add, μA_eq.symm], exact (ennreal.add_lt_add_iff_left μA).2 hδ } }
end }
/-- Given a regular measure, any measurable set of finite mass can be approximated from
inside by compact sets. -/
lemma _root_.measurable_set.measure_eq_supr_is_compact_of_lt_top
[borel_space α] [t2_space α] [regular μ]
⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A < ∞) :
μ A = (⨆ (K : set α) (h : is_compact K) (h2 : K ⊆ A), μ K) :=
begin
/- We approximate `A` from inside by a closed set `F` (using the fact that the result to be
proved is true for weakly regular measures), and we approximate `A` from the outside
by an open set `U`, and `U` from inside by a compact set `K`, by definition of regular
measures. Then `K ∩ F` is contained in `A`, it is compact, and its measure is close to that
of `A`. -/
refine le_antisymm _ (supr_le $ λ s, supr_le $ λ hs, supr_le $ λ h2s, μ.mono h2s),
apply ennreal.le_of_forall_pos_le_add (λ ε εpos H, _),
set δ := (ε : ℝ≥0∞) / 2 with hδ,
have δpos : 0 < δ := ennreal.half_pos (ennreal.coe_pos.2 εpos),
-- construct `U` approximating `A` from outside.
obtain ⟨U, U_open, AU, μU⟩ : ∃ (U : set α), is_open U ∧ A ⊆ U ∧ μ U < ∞ :=
weakly_regular.exists_subset_is_open_measure_lt_top h'A,
-- construct `K` approximating `U` from inside.
have : μ U < ⨆ (K : set α) (h : is_compact K) (h2 : K ⊆ U), (μ K + δ),
{ haveI : nonempty {K // is_compact K ∧ K ⊆ U} := ⟨⟨∅, is_compact_empty, empty_subset _⟩⟩,
simp_rw [U_open.measure_eq_supr_is_compact, supr_and', supr_subtype', ← ennreal.supr_add],
simpa only [add_zero, ennreal.coe_zero] using (ennreal.add_lt_add_iff_left _).mpr δpos,
convert μU.trans_le le_top,
simp_rw [U_open.measure_eq_supr_is_compact, supr_and', supr_subtype'] },
obtain ⟨K, K_compact, KU, μK⟩ : ∃ (K : set α) (_ : is_compact K) (_ : K ⊆ U), μ U < μ K + δ,
by simpa only [lt_supr_iff] using this,
-- construct `F` approximating `A` from inside.
obtain ⟨F, F_closed, FA, μF⟩ : ∃ (F : set α), is_closed F ∧ F ⊆ A ∧ μ A < μ F + δ :=
hA.exists_lt_is_closed_of_lt_top_of_pos h'A δpos,
-- show that `F ∩ K` approximates `A` from inside.
have : μ A ≤ μ (F ∩ K) + ε := calc
μ A ≤ μ F + δ : μF.le
... ≤ μ ((F ∩ K) ∪ (U \ K)) + δ :
begin
refine add_le_add (measure_mono _) (le_refl _),
conv_lhs { rw ← inter_union_diff F K },
apply union_subset_union (subset.refl _),
apply diff_subset_diff (subset.trans FA AU) (subset.refl _),
end
... ≤ μ (F ∩ K) + μ (U \ K) + δ : add_le_add (measure_union_le _ _) (le_refl _)
... ≤ μ (F ∩ K) + δ + δ :
begin
refine add_le_add (add_le_add (le_refl _) _) (le_refl _),
rw [measure_diff KU U_open.measurable_set K_compact.measurable_set
(lt_top_of_is_compact K_compact), ennreal.sub_le_iff_le_add'],
{ exact μK.le },
{ apply_instance }
end
... = μ (F ∩ K) + ε : by rw [add_assoc, hδ, ennreal.add_halves],
refine le_trans this (add_le_add _ (le_refl _)),
simp_rw [supr_and', supr_subtype'],
exact le_supr (λ s : {s // is_compact s ∧ s ⊆ A}, μ s)
⟨F ∩ K, K_compact.inter_left F_closed, subset.trans (inter_subset_left _ _) FA⟩,
end
lemma _root_.measurable_set.exists_lt_is_compact_of_lt_top [borel_space α] [t2_space α] [regular μ]
⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A < ∞) {r : ℝ≥0∞} (hr : r < μ A) :
∃ K, is_compact K ∧ K ⊆ A ∧ r < μ K :=
begin
rw hA.measure_eq_supr_is_compact_of_lt_top h'A at hr,
simpa only [lt_supr_iff, exists_prop] using hr,
end
lemma _root_.measurable_set.exists_lt_is_compact_of_lt_top_of_pos
[borel_space α] [t2_space α] [regular μ]
⦃A : set α⦄ (hA : measurable_set A) (h'A : μ A < ∞) {ε : ℝ≥0∞} (εpos : 0 < ε) :
∃ K, is_compact K ∧ K ⊆ A ∧ μ A < μ K + ε :=
begin
have : μ A < ⨆ (K : set α) (h : is_compact K) (h2 : K ⊆ A), (μ K + ε),
{ haveI : nonempty {K // is_compact K ∧ K ⊆ A} := ⟨⟨∅, is_compact_empty, empty_subset _⟩⟩,
simp_rw [hA.measure_eq_supr_is_compact_of_lt_top h'A, supr_and',
supr_subtype', ← ennreal.supr_add],
simpa only [add_zero, ennreal.coe_zero] using (ennreal.add_lt_add_iff_left _).mpr εpos,
convert h'A,
simp_rw [hA.measure_eq_supr_is_compact_of_lt_top h'A, supr_and', supr_subtype'] },
simpa only [lt_supr_iff, exists_prop],
end
end regular
end measure
end measure_theory
|
0473b0643ad9e53da249a8f21bc11c4ba879c808
|
37da0369b6c03e380e057bf680d81e6c9fdf9219
|
/hott/types/equiv.hlean
|
e36a4181ace0a4037a7c85de737dd926af0218b6
|
[
"Apache-2.0"
] |
permissive
|
kodyvajjha/lean2
|
72b120d95c3a1d77f54433fa90c9810e14a931a4
|
227fcad22ab2bc27bb7471be7911075d101ba3f9
|
refs/heads/master
| 1,627,157,512,295
| 1,501,855,676,000
| 1,504,809,427,000
| 109,317,326
| 0
| 0
| null | 1,509,839,253,000
| 1,509,655,713,000
|
C++
|
UTF-8
|
Lean
| false
| false
| 12,659
|
hlean
|
/-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Ported from Coq HoTT
Theorems about the types equiv and is_equiv
-/
import .fiber .arrow arity ..prop_trunc cubical.square .pointed
open eq is_trunc sigma sigma.ops pi fiber function equiv
namespace is_equiv
variables {A B : Type} (f : A → B) [H : is_equiv f]
include H
/- is_equiv f is a mere proposition -/
definition is_contr_fiber_of_is_equiv [instance] (b : B) : is_contr (fiber f b) :=
is_contr.mk
(fiber.mk (f⁻¹ b) (right_inv f b))
(λz, fiber.rec_on z (λa p,
fiber_eq ((ap f⁻¹ p)⁻¹ ⬝ left_inv f a) (calc
right_inv f b = (ap (f ∘ f⁻¹) p)⁻¹ ⬝ ((ap (f ∘ f⁻¹) p) ⬝ right_inv f b)
: by rewrite inv_con_cancel_left
... = (ap (f ∘ f⁻¹) p)⁻¹ ⬝ (right_inv f (f a) ⬝ p) : by rewrite ap_con_eq_con
... = (ap (f ∘ f⁻¹) p)⁻¹ ⬝ (ap f (left_inv f a) ⬝ p) : by rewrite [adj f]
... = (ap (f ∘ f⁻¹) p)⁻¹ ⬝ ap f (left_inv f a) ⬝ p : by rewrite con.assoc
... = (ap f (ap f⁻¹ p))⁻¹ ⬝ ap f (left_inv f a) ⬝ p : by rewrite ap_compose
... = ap f (ap f⁻¹ p)⁻¹ ⬝ ap f (left_inv f a) ⬝ p : by rewrite ap_inv
... = ap f ((ap f⁻¹ p)⁻¹ ⬝ left_inv f a) ⬝ p : by rewrite ap_con)))
definition is_contr_right_inverse : is_contr (Σ(g : B → A), f ∘ g ~ id) :=
begin
fapply is_trunc_equiv_closed,
{apply sigma_equiv_sigma_right, intro g, apply eq_equiv_homotopy},
fapply is_trunc_equiv_closed,
{apply fiber.sigma_char},
fapply is_contr_fiber_of_is_equiv,
apply (to_is_equiv (arrow_equiv_arrow_right B (equiv.mk f H))),
end
definition is_contr_right_coherence (u : Σ(g : B → A), f ∘ g ~ id)
: is_contr (Σ(η : u.1 ∘ f ~ id), Π(a : A), u.2 (f a) = ap f (η a)) :=
begin
fapply is_trunc_equiv_closed,
{apply equiv.symm, apply sigma_pi_equiv_pi_sigma},
fapply is_trunc_equiv_closed,
{apply pi_equiv_pi_right, intro a,
apply (fiber_eq_equiv (fiber.mk (u.1 (f a)) (u.2 (f a))) (fiber.mk a idp))},
end
omit H
protected definition sigma_char : (is_equiv f) ≃
(Σ(g : B → A) (ε : f ∘ g ~ id) (η : g ∘ f ~ id), Π(a : A), ε (f a) = ap f (η a)) :=
equiv.MK (λH, ⟨inv f, right_inv f, left_inv f, adj f⟩)
(λp, is_equiv.mk f p.1 p.2.1 p.2.2.1 p.2.2.2)
(λp, begin
induction p with p1 p2,
induction p2 with p21 p22,
induction p22 with p221 p222,
reflexivity
end)
(λH, by induction H; reflexivity)
protected definition sigma_char' : (is_equiv f) ≃
(Σ(u : Σ(g : B → A), f ∘ g ~ id) (η : u.1 ∘ f ~ id), Π(a : A), u.2 (f a) = ap f (η a)) :=
calc
(is_equiv f) ≃
(Σ(g : B → A) (ε : f ∘ g ~ id) (η : g ∘ f ~ id), Π(a : A), ε (f a) = ap f (η a))
: is_equiv.sigma_char
... ≃ (Σ(u : Σ(g : B → A), f ∘ g ~ id), Σ(η : u.1 ∘ f ~ id), Π(a : A), u.2 (f a) = ap f (η a))
: sigma_assoc_equiv (λu, Σ(η : u.1 ∘ f ~ id), Π(a : A), u.2 (f a) = ap f (η a))
local attribute is_contr_right_inverse [instance] [priority 1600]
local attribute is_contr_right_coherence [instance] [priority 1600]
theorem is_prop_is_equiv [instance] : is_prop (is_equiv f) :=
is_prop_of_imp_is_contr
(λ(H : is_equiv f), is_trunc_equiv_closed -2 (equiv.symm !is_equiv.sigma_char'))
definition inv_eq_inv {A B : Type} {f f' : A → B} {Hf : is_equiv f} {Hf' : is_equiv f'}
(p : f = f') : f⁻¹ = f'⁻¹ :=
apd011 inv p !is_prop.elimo
/- contractible fibers -/
definition is_contr_fun_of_is_equiv [H : is_equiv f] : is_contr_fun f :=
is_contr_fiber_of_is_equiv f
definition is_prop_is_contr_fun (f : A → B) : is_prop (is_contr_fun f) := _
definition is_equiv_of_is_contr_fun [H : is_contr_fun f] : is_equiv f :=
adjointify _ (λb, point (center (fiber f b)))
(λb, point_eq (center (fiber f b)))
(λa, ap point (center_eq (fiber.mk a idp)))
definition is_equiv_of_imp_is_equiv (H : B → is_equiv f) : is_equiv f :=
@is_equiv_of_is_contr_fun _ _ f (λb, @is_contr_fiber_of_is_equiv _ _ _ (H b) _)
definition is_equiv_equiv_is_contr_fun : is_equiv f ≃ is_contr_fun f :=
equiv_of_is_prop _ (λH, !is_equiv_of_is_contr_fun)
theorem inv_commute'_fn {A : Type} {B C : A → Type} (f : Π{a}, B a → C a) [H : Πa, is_equiv (@f a)]
{g : A → A} (h : Π{a}, B a → B (g a)) (h' : Π{a}, C a → C (g a))
(p : Π⦃a : A⦄ (b : B a), f (h b) = h' (f b)) {a : A} (b : B a) :
inv_commute' @f @h @h' p (f b)
= (ap f⁻¹ (p b))⁻¹ ⬝ left_inv f (h b) ⬝ (ap h (left_inv f b))⁻¹ :=
begin
rewrite [↑[inv_commute',eq_of_fn_eq_fn'],+ap_con,-adj_inv f,+con.assoc,inv_con_cancel_left,
adj f,+ap_inv,-+ap_compose,
eq_bot_of_square (natural_square_tr (λb, (left_inv f (h b))⁻¹ ⬝ ap f⁻¹ (p b)) (left_inv f b))⁻¹ʰ,
con_inv,inv_inv,+con.assoc],
do 3 apply whisker_left,
rewrite [con_inv_cancel_left,con.left_inv]
end
end is_equiv
/- Moving equivalences around in homotopies -/
namespace is_equiv
variables {A B C : Type} (f : A → B) [Hf : is_equiv f]
include Hf
section pre_compose
variables (α : A → C) (β : B → C)
-- homotopy_inv_of_homotopy_pre is in init.equiv
protected definition inv_homotopy_of_homotopy_pre.is_equiv
: is_equiv (inv_homotopy_of_homotopy_pre f α β) :=
adjointify _ (homotopy_of_inv_homotopy_pre f α β)
abstract begin
intro q, apply eq_of_homotopy, intro b,
unfold inv_homotopy_of_homotopy_pre,
unfold homotopy_of_inv_homotopy_pre,
apply inverse, apply eq_bot_of_square,
apply eq_hconcat (ap02 α (adj_inv f b)),
apply eq_hconcat (ap_compose α f⁻¹ (right_inv f b))⁻¹,
apply natural_square q (right_inv f b)
end end
abstract begin
intro p, apply eq_of_homotopy, intro a,
unfold inv_homotopy_of_homotopy_pre,
unfold homotopy_of_inv_homotopy_pre,
apply trans (con.assoc
(ap α (left_inv f a))⁻¹
(p (f⁻¹ (f a)))
(ap β (right_inv f (f a))))⁻¹,
apply inverse, apply eq_bot_of_square,
refine hconcat_eq _ (ap02 β (adj f a))⁻¹,
refine hconcat_eq _ (ap_compose β f (left_inv f a)),
apply natural_square p (left_inv f a)
end end
end pre_compose
section post_compose
variables (α : C → A) (β : C → B)
-- homotopy_inv_of_homotopy_post is in init.equiv
protected definition inv_homotopy_of_homotopy_post.is_equiv
: is_equiv (inv_homotopy_of_homotopy_post f α β) :=
adjointify _ (homotopy_of_inv_homotopy_post f α β)
abstract begin
intro q, apply eq_of_homotopy, intro c,
unfold inv_homotopy_of_homotopy_post,
unfold homotopy_of_inv_homotopy_post,
apply trans (whisker_right (left_inv f (α c))
(ap_con f⁻¹ (right_inv f (β c))⁻¹ (ap f (q c))
⬝ whisker_right (ap f⁻¹ (ap f (q c)))
(ap_inv f⁻¹ (right_inv f (β c))))),
apply inverse, apply eq_bot_of_square,
apply eq_hconcat (adj_inv f (β c))⁻¹,
apply eq_vconcat (ap_compose f⁻¹ f (q c))⁻¹,
refine vconcat_eq _ (ap_id (q c)),
apply natural_square_tr (left_inv f) (q c)
end end
abstract begin
intro p, apply eq_of_homotopy, intro c,
unfold inv_homotopy_of_homotopy_post,
unfold homotopy_of_inv_homotopy_post,
apply trans (whisker_left (right_inv f (β c))⁻¹
(ap_con f (ap f⁻¹ (p c)) (left_inv f (α c)))),
apply trans (con.assoc (right_inv f (β c))⁻¹ (ap f (ap f⁻¹ (p c)))
(ap f (left_inv f (α c))))⁻¹,
apply inverse, apply eq_bot_of_square,
refine hconcat_eq _ (adj f (α c)),
apply eq_vconcat (ap_compose f f⁻¹ (p c))⁻¹,
refine vconcat_eq _ (ap_id (p c)),
apply natural_square_tr (right_inv f) (p c)
end end
end post_compose
end is_equiv
namespace is_equiv
/- Theorem 4.7.7 -/
variables {A : Type} {P Q : A → Type}
variable (f : Πa, P a → Q a)
definition is_fiberwise_equiv [reducible] := Πa, is_equiv (f a)
definition is_equiv_total_of_is_fiberwise_equiv [H : is_fiberwise_equiv f] : is_equiv (total f) :=
is_equiv_sigma_functor id f
definition is_fiberwise_equiv_of_is_equiv_total [H : is_equiv (total f)]
: is_fiberwise_equiv f :=
begin
intro a,
apply is_equiv_of_is_contr_fun, intro q,
apply @is_contr_equiv_closed _ _ (fiber_total_equiv f q)
end
end is_equiv
namespace equiv
open is_equiv
variables {A B C : Type}
definition equiv_mk_eq {f f' : A → B} [H : is_equiv f] [H' : is_equiv f'] (p : f = f')
: equiv.mk f H = equiv.mk f' H' :=
apd011 equiv.mk p !is_prop.elimo
definition equiv_eq' {f f' : A ≃ B} (p : to_fun f = to_fun f') : f = f' :=
by (cases f; cases f'; apply (equiv_mk_eq p))
definition equiv_eq {f f' : A ≃ B} (p : to_fun f ~ to_fun f') : f = f' :=
by apply equiv_eq'; apply eq_of_homotopy p
definition trans_symm (f : A ≃ B) (g : B ≃ C) : (f ⬝e g)⁻¹ᵉ = g⁻¹ᵉ ⬝e f⁻¹ᵉ :> (C ≃ A) :=
equiv_eq' idp
definition symm_symm (f : A ≃ B) : f⁻¹ᵉ⁻¹ᵉ = f :> (A ≃ B) :=
equiv_eq' idp
protected definition equiv.sigma_char [constructor]
(A B : Type) : (A ≃ B) ≃ Σ(f : A → B), is_equiv f :=
begin
fapply equiv.MK,
{intro F, exact ⟨to_fun F, to_is_equiv F⟩},
{intro p, cases p with f H, exact (equiv.mk f H)},
{intro p, cases p, exact idp},
{intro F, cases F, exact idp},
end
definition equiv_eq_char (f f' : A ≃ B) : (f = f') ≃ (to_fun f = to_fun f') :=
calc
(f = f') ≃ (to_fun !equiv.sigma_char f = to_fun !equiv.sigma_char f')
: eq_equiv_fn_eq (to_fun !equiv.sigma_char)
... ≃ ((to_fun !equiv.sigma_char f).1 = (to_fun !equiv.sigma_char f').1 ) : equiv_subtype
... ≃ (to_fun f = to_fun f') : equiv.rfl
definition is_equiv_ap_to_fun (f f' : A ≃ B)
: is_equiv (ap to_fun : f = f' → to_fun f = to_fun f') :=
begin
fapply adjointify,
{intro p, cases f with f H, cases f' with f' H', cases p, apply ap (mk f'), apply is_prop.elim},
{intro p, cases f with f H, cases f' with f' H', cases p,
apply @concat _ _ (ap to_fun (ap (equiv.mk f') (is_prop.elim H H'))), {apply idp},
generalize is_prop.elim H H', intro q, cases q, apply idp},
{intro p, cases p, cases f with f H, apply ap (ap (equiv.mk f)), apply is_set.elim}
end
definition equiv_pathover {A : Type} {a a' : A} (p : a = a')
{B : A → Type} {C : A → Type} (f : B a ≃ C a) (g : B a' ≃ C a')
(r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[p] g b') : f =[p] g :=
begin
fapply pathover_of_fn_pathover_fn,
{ intro a, apply equiv.sigma_char},
{ fapply sigma_pathover,
esimp, apply arrow_pathover, exact r,
apply is_prop.elimo}
end
definition is_contr_equiv (A B : Type) [HA : is_contr A] [HB : is_contr B] : is_contr (A ≃ B) :=
begin
apply @is_contr_of_inhabited_prop, apply is_prop.mk,
intro x y, cases x with fx Hx, cases y with fy Hy, generalize Hy,
apply (eq_of_homotopy (λ a, !eq_of_is_contr)) ▸ (λ Hy, !is_prop.elim ▸ rfl),
apply equiv_of_is_contr_of_is_contr
end
definition is_trunc_succ_equiv (n : trunc_index) (A B : Type)
[HA : is_trunc n.+1 A] [HB : is_trunc n.+1 B] : is_trunc n.+1 (A ≃ B) :=
@is_trunc_equiv_closed _ _ n.+1 (equiv.symm !equiv.sigma_char)
(@is_trunc_sigma _ _ _ _ (λ f, !is_trunc_succ_of_is_prop))
definition is_trunc_equiv (n : trunc_index) (A B : Type)
[HA : is_trunc n A] [HB : is_trunc n B] : is_trunc n (A ≃ B) :=
by cases n; apply !is_contr_equiv; apply !is_trunc_succ_equiv
definition eq_of_fn_eq_fn'_idp {A B : Type} (f : A → B) [is_equiv f] (x : A)
: eq_of_fn_eq_fn' f (idpath (f x)) = idpath x :=
!con.left_inv
definition eq_of_fn_eq_fn'_con {A B : Type} (f : A → B) [is_equiv f] {x y z : A}
(p : f x = f y) (q : f y = f z)
: eq_of_fn_eq_fn' f (p ⬝ q) = eq_of_fn_eq_fn' f p ⬝ eq_of_fn_eq_fn' f q :=
begin
unfold eq_of_fn_eq_fn',
refine _ ⬝ !con.assoc, apply whisker_right,
refine _ ⬝ !con.assoc⁻¹ ⬝ !con.assoc⁻¹, apply whisker_left,
refine !ap_con ⬝ _, apply whisker_left,
refine !con_inv_cancel_left⁻¹
end
end equiv
|
3c86164ca368312143c989add3c4bfca2db66180
|
41ebf3cb010344adfa84907b3304db00e02db0a6
|
/uexp/src/uexp/rules/removeSemiJoinRightWithFilter.lean
|
160ab88dd680c08e45796957e3c6f8d5f08ba746
|
[
"BSD-2-Clause"
] |
permissive
|
ReinierKoops/Cosette
|
e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb
|
eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29
|
refs/heads/master
| 1,686,483,953,198
| 1,624,293,498,000
| 1,624,293,498,000
| 378,997,885
| 0
| 0
|
BSD-2-Clause
| 1,624,293,485,000
| 1,624,293,484,000
| null |
UTF-8
|
Lean
| false
| false
| 1,787
|
lean
|
import ..sql
import ..tactics
import ..u_semiring
import ..extra_constants
import ..meta.ucongr
import ..meta.TDP
set_option profiler true
open Expr
open Proj
open Pred
open SQL
open tree
notation `int` := datatypes.int
constant str_foo_: const int.
theorem rule:
forall ( Γ scm_dept scm_emp: Schema) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp),
denoteSQL
((SELECT1 (right⋅left⋅emp_ename)
(FROM1 (product (table rel_emp) (product (table rel_dept) (table rel_emp)))
WHERE (and (and (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅left⋅dept_deptno))) (equal (uvariable (right⋅right⋅left⋅dept_deptno)) (uvariable (right⋅right⋅right⋅emp_deptno)))) (equal (uvariable (right⋅right⋅left⋅dept_name)) (constantExpr str_foo_))))) : SQL Γ _ ) =
denoteSQL
((SELECT1 (right⋅left⋅emp_ename)
(FROM1 (product (table rel_emp) (product ((SELECT * FROM1 (table rel_dept) WHERE (equal (uvariable (right⋅dept_name)) (constantExpr str_foo_)))) (table rel_emp)))
WHERE (and (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅left⋅dept_deptno))) (equal (uvariable (right⋅right⋅left⋅dept_deptno)) (uvariable (right⋅right⋅right⋅emp_deptno)))))) : SQL Γ _) :=
begin
intros,
unfold_all_denotations,
funext,
print_size,
simp,
print_size,
TDP' ucongr,
end
|
8ef41e5c37e5f4007070ab55e516d22c47dce9d9
|
4727251e0cd73359b15b664c3170e5d754078599
|
/src/ring_theory/fintype.lean
|
efdb548d3547dd75079b27a15d002c197926557f
|
[
"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
| 474
|
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 data.fintype.basic
/-!
# Some facts about finite rings
-/
open_locale classical
lemma card_units_lt (M₀ : Type*) [monoid_with_zero M₀] [nontrivial M₀] [fintype M₀] :
fintype.card M₀ˣ < fintype.card M₀ :=
fintype.card_lt_of_injective_of_not_mem (coe : M₀ˣ → M₀) units.ext not_is_unit_zero
|
ade2fece467247b5925b2a050cd268994607f6b3
|
4727251e0cd73359b15b664c3170e5d754078599
|
/src/topology/continuous_function/cocompact_map.lean
|
5ed716fb37a9bb1a2f6d0ce8c315c2983e2c66c8
|
[
"Apache-2.0"
] |
permissive
|
Vierkantor/mathlib
|
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
|
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
|
refs/heads/master
| 1,658,323,012,449
| 1,652,256,003,000
| 1,652,256,003,000
| 209,296,341
| 0
| 1
|
Apache-2.0
| 1,568,807,655,000
| 1,568,807,655,000
| null |
UTF-8
|
Lean
| false
| false
| 5,353
|
lean
|
/-
Copyright (c) 2022 Jireh Loreaux. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jireh Loreaux
-/
import topology.continuous_function.basic
/-!
# Cocompact continuous maps
The type of *cocompact continuous maps* are those which tend to the cocompact filter on the
codomain along the cocompact filter on the domain. When the domain and codomain are Hausdorff, this
is equivalent to many other conditions, including that preimages of compact sets are compact. -/
universes u v w
open filter set
/-! ### Cocompact continuous maps -/
/-- A *cocompact continuous map* is a continuous function between topological spaces which
tends to the cocompact filter along the cocompact filter. Functions for which preimages of compact
sets are compact always satisfy this property, and the converse holds for cocompact continuous maps
when the codomain is Hausdorff (see `cocompact_map.tendsto_of_forall_preimage` and
`cocompact_map.compact_preimage`) -/
structure cocompact_map (α : Type u) (β : Type v) [topological_space α] [topological_space β]
extends continuous_map α β : Type (max u v) :=
(cocompact_tendsto' : tendsto to_fun (cocompact α) (cocompact β))
/-- `cocompact_map_class F α β` states that `F` is a type of cocompact continuous maps.
You should also extend this typeclass when you extend `cocompact_map`. -/
class cocompact_map_class (F : Type*) (α β : out_param $ Type*) [topological_space α]
[topological_space β] extends continuous_map_class F α β :=
(cocompact_tendsto (f : F) : tendsto f (cocompact α) (cocompact β))
namespace cocompact_map_class
variables {F α β : Type*} [topological_space α] [topological_space β]
[cocompact_map_class F α β]
instance : has_coe_t F (cocompact_map α β) := ⟨λ f, ⟨f, cocompact_tendsto f⟩⟩
end cocompact_map_class
export cocompact_map_class (cocompact_tendsto)
namespace cocompact_map
section basics
variables {α β γ δ : Type*} [topological_space α] [topological_space β] [topological_space γ]
[topological_space δ]
instance : cocompact_map_class (cocompact_map α β) α β :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' },
map_continuous := λ f, f.continuous_to_fun,
cocompact_tendsto := λ f, f.cocompact_tendsto' }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun (cocompact_map α β) (λ _, α → β) := fun_like.has_coe_to_fun
@[simp] lemma coe_to_continuous_fun {f : cocompact_map α β} :
(f.to_continuous_map : α → β) = f := rfl
@[ext] lemma ext {f g : cocompact_map α β} (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h
/-- Copy of a `cocompact_map` with a new `to_fun` equal to the old one. Useful
to fix definitional equalities. -/
protected def copy (f : cocompact_map α β) (f' : α → β) (h : f' = f) : cocompact_map α β :=
{ to_fun := f',
continuous_to_fun := by {rw h, exact f.continuous_to_fun},
cocompact_tendsto' := by { simp_rw h, exact f.cocompact_tendsto' } }
@[simp] lemma coe_mk (f : C(α, β)) (h : tendsto f (cocompact α) (cocompact β)) :
⇑(⟨f, h⟩ : cocompact_map α β) = f := rfl
section
variable (α)
/-- The identity as a cocompact continuous map. -/
protected def id : cocompact_map α α := ⟨continuous_map.id _, tendsto_id⟩
@[simp] lemma coe_id : ⇑(cocompact_map.id α) = id := rfl
end
instance : inhabited (cocompact_map α α) := ⟨cocompact_map.id α⟩
/-- The composition of cocompact continuous maps, as a cocompact continuous map. -/
def comp (f : cocompact_map β γ) (g : cocompact_map α β) : cocompact_map α γ :=
⟨f.to_continuous_map.comp g, (cocompact_tendsto f).comp (cocompact_tendsto g)⟩
@[simp] lemma coe_comp (f : cocompact_map β γ) (g : cocompact_map α β) :
⇑(comp f g) = f ∘ g := rfl
@[simp] lemma comp_apply (f : cocompact_map β γ) (g : cocompact_map α β) (a : α) :
comp f g a = f (g a) := rfl
@[simp] lemma comp_assoc (f : cocompact_map γ δ) (g : cocompact_map β γ)
(h : cocompact_map α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl
@[simp] lemma id_comp (f : cocompact_map α β) : (cocompact_map.id _).comp f = f :=
ext $ λ _, rfl
@[simp] lemma comp_id (f : cocompact_map α β) : f.comp (cocompact_map.id _) = f :=
ext $ λ _, rfl
lemma tendsto_of_forall_preimage {f : α → β} (h : ∀ s, is_compact s → is_compact (f ⁻¹' s)) :
tendsto f (cocompact α) (cocompact β) :=
λ s hs, match mem_cocompact.mp hs with ⟨t, ht, hts⟩ :=
mem_map.mpr (mem_cocompact.mpr ⟨f ⁻¹' t, h t ht, by simpa using preimage_mono hts⟩) end
/-- If the codomain is Hausdorff, preimages of compact sets are compact under a cocompact
continuous map. -/
lemma compact_preimage [t2_space β] (f : cocompact_map α β) ⦃s : set β⦄ (hs : is_compact s) :
is_compact (f ⁻¹' s) :=
begin
obtain ⟨t, ht, hts⟩ := mem_cocompact'.mp (by simpa only [preimage_image_preimage, preimage_compl]
using mem_map.mp (cocompact_tendsto f $ mem_cocompact.mpr ⟨s, hs, compl_subset_compl.mpr
(image_preimage_subset f _)⟩)),
exact compact_of_is_closed_subset ht (hs.is_closed.preimage $ map_continuous f)
(by simpa using hts),
end
end basics
end cocompact_map
|
de39ed6480da7f4ace97de0a7d3004df3ab9f35b
|
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
|
/src/data/finset/interval.lean
|
e1c4a14f2f505ebec2e44f892f061165cda0bb6d
|
[
"Apache-2.0"
] |
permissive
|
dexmagic/mathlib
|
ff48eefc56e2412429b31d4fddd41a976eb287ce
|
7a5d15a955a92a90e1d398b2281916b9c41270b2
|
refs/heads/master
| 1,693,481,322,046
| 1,633,360,193,000
| 1,633,360,193,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 4,026
|
lean
|
/-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import order.locally_finite
/-!
# Intervals as finsets
This file provides basic results about all the `finset.Ixx`, which are defined in
`order.locally_finite`.
## TODO
Bring the lemmas about `finset.Ico` in `data.finset.intervals` here and in `data.nat.intervals`.
-/
namespace finset
variables {α : Type*}
section preorder
variables [preorder α] [locally_finite_order α] {a b : α}
@[simp] lemma nonempty_Icc : (Icc a b).nonempty ↔ a ≤ b :=
by rw [←coe_nonempty, coe_Icc, set.nonempty_Icc]
@[simp] lemma nonempty_Ioc : (Ioc a b).nonempty ↔ a < b :=
by rw [←coe_nonempty, coe_Ioc, set.nonempty_Ioc]
@[simp] lemma nonempty_Ioo [densely_ordered α] : (Ioo a b).nonempty ↔ a < b :=
by rw [←coe_nonempty, coe_Ioo, set.nonempty_Ioo]
@[simp] lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ ¬a ≤ b :=
by rw [←coe_eq_empty, coe_Icc, set.Icc_eq_empty_iff]
@[simp] lemma Ioc_eq_empty_iff : Ioc a b = ∅ ↔ ¬a < b :=
by rw [←coe_eq_empty, coe_Ioc, set.Ioc_eq_empty_iff]
@[simp] lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ ¬a < b :=
by rw [←coe_eq_empty, coe_Ioo, set.Ioo_eq_empty_iff]
alias Icc_eq_empty_iff ↔ _ finset.Icc_eq_empty
alias Ioc_eq_empty_iff ↔ _ finset.Ioc_eq_empty
@[simp] lemma Ioo_eq_empty (h : ¬a < b) : Ioo a b = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ x hx, h ((mem_Ioo.1 hx).1.trans (mem_Ioo.1 hx).2)
@[simp] lemma Icc_eq_empty_of_lt (h : b < a) : Icc a b = ∅ :=
Icc_eq_empty h.not_le
@[simp] lemma Ioc_eq_empty_of_le (h : b ≤ a) : Ioc a b = ∅ :=
Ioc_eq_empty h.not_lt
@[simp] lemma Ioo_eq_empty_of_le (h : b ≤ a) : Ioo a b = ∅ :=
Ioo_eq_empty h.not_lt
variables (a)
@[simp] lemma Ioc_self : Ioc a a = ∅ :=
by rw [←coe_eq_empty, coe_Ioc, set.Ioc_self]
@[simp] lemma Ioo_self : Ioo a a = ∅ :=
by rw [←coe_eq_empty, coe_Ioo, set.Ioo_self]
end preorder
section partial_order
variables [partial_order α] [locally_finite_order α] {a b : α}
@[simp] lemma Icc_self (a : α) : Icc a a = {a} :=
by rw [←coe_eq_singleton, coe_Icc, set.Icc_self]
end partial_order
section ordered_cancel_add_comm_monoid
variables [ordered_cancel_add_comm_monoid α] [has_exists_add_of_le α] [decidable_eq α]
[locally_finite_order α]
lemma image_add_const_Icc (a b c : α) : (Icc a b).image ((+) c) = Icc (a + c) (b + c) :=
begin
ext x,
rw [mem_image, mem_Icc],
split,
{ rintro ⟨y, hy, rfl⟩,
rw mem_Icc at hy,
rw add_comm c,
exact ⟨add_le_add_right hy.1 c, add_le_add_right hy.2 c⟩ },
{ intro hx,
obtain ⟨y, hy⟩ := exists_add_of_le hx.1,
rw [hy, add_right_comm] at hx,
rw [eq_comm, add_right_comm, add_comm] at hy,
exact ⟨a + y, mem_Icc.2 ⟨le_of_add_le_add_right hx.1, le_of_add_le_add_right hx.2⟩, hy⟩ }
end
lemma image_add_const_Ioc (a b c : α) : (Ioc a b).image ((+) c) = Ioc (a + c) (b + c) :=
begin
ext x,
rw [mem_image, mem_Ioc],
split,
{ rintro ⟨y, hy, rfl⟩,
rw mem_Ioc at hy,
rw add_comm c,
exact ⟨add_lt_add_right hy.1 c, add_le_add_right hy.2 c⟩ },
{ intro hx,
obtain ⟨y, hy⟩ := exists_add_of_le hx.1.le,
rw [hy, add_right_comm] at hx,
rw [eq_comm, add_right_comm, add_comm] at hy,
exact ⟨a + y, mem_Ioc.2 ⟨lt_of_add_lt_add_right hx.1, le_of_add_le_add_right hx.2⟩, hy⟩ }
end
lemma image_add_const_Ioo (a b c : α) : (Ioo a b).image ((+) c) = Ioo (a + c) (b + c) :=
begin
ext x,
rw [mem_image, mem_Ioo],
split,
{ rintro ⟨y, hy, rfl⟩,
rw mem_Ioo at hy,
rw add_comm c,
exact ⟨add_lt_add_right hy.1 c, add_lt_add_right hy.2 c⟩ },
{ intro hx,
obtain ⟨y, hy⟩ := exists_add_of_le hx.1.le,
rw [hy, add_right_comm] at hx,
rw [eq_comm, add_right_comm, add_comm] at hy,
exact ⟨a + y, mem_Ioo.2 ⟨lt_of_add_lt_add_right hx.1, lt_of_add_lt_add_right hx.2⟩, hy⟩ }
end
end ordered_cancel_add_comm_monoid
end finset
|
6cb3eb0b8e72a0a6f9b1b1df04f43e26f35585c9
|
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
|
/src/Lean/HeadIndex.lean
|
55b43b1b9c507e951e790ff249a128201ae270e7
|
[
"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
| 3,808
|
lean
|
/-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Lean.Expr
namespace Lean
/--
Datastructure for representing the "head symbol" of an expression.
It is the key of `KExprMap`.
Examples:
- The head of `f a` is `.const f`
- The head of `let x := 1; f x` is `.const f`
- The head of `fun x => fun` is `.lam`
`HeadIndex` is a very simple index, and is used in situations where
we want to find definitionally equal terms, but we want to minimize
the search by checking only pairs of terms that have the same
`HeadIndex`.
-/
inductive HeadIndex where
| fvar (fvarId : FVarId)
| mvar (mvarId : MVarId)
| const (constName : Name)
| proj (structName : Name) (idx : Nat)
| lit (litVal : Literal)
| sort
| lam
| forallE
deriving Inhabited, BEq, Repr
namespace HeadIndex
/-- Hash code for a `HeadIndex` value. -/
protected def HeadIndex.hash : HeadIndex → UInt64
| fvar fvarId => mixHash 11 <| hash fvarId
| mvar mvarId => mixHash 13 <| hash mvarId
| const constName => mixHash 17 <| hash constName
| proj structName idx => mixHash 19 <| mixHash (hash structName) (hash idx)
| lit litVal => mixHash 23 <| hash litVal
| sort => 29
| lam => 31
| forallE => 37
instance : Hashable HeadIndex := ⟨HeadIndex.hash⟩
end HeadIndex
namespace Expr
/-- Return the number of arguments in the given expression with respect to its `HeadIndex` -/
def headNumArgs (e : Expr) : Nat :=
go e 0
where
go : Expr → Nat → Nat
| app f _, n => go f (n + 1)
| letE _ _ _ b _, n => go b n
| mdata _ e, n => go e n
| _, n => n
/--
Quick version that may fail if it "hits" a loose bound variable.
This can happen, for example, if the input expression is of the form.
```
let f := fun x => x + 1;
f 0
```
-/
private def toHeadIndexQuick? : Expr → Option HeadIndex
| mvar mvarId => HeadIndex.mvar mvarId
| fvar fvarId => HeadIndex.fvar fvarId
| const constName _ => HeadIndex.const constName
| proj structName idx _ => HeadIndex.proj structName idx
| sort _ => HeadIndex.sort
| lam .. => HeadIndex.lam
| forallE .. => HeadIndex.forallE
| lit v => HeadIndex.lit v
| app f _ => toHeadIndexQuick? f
| letE _ _ _ b _ => toHeadIndexQuick? b
| mdata _ e => toHeadIndexQuick? e
| _ => none
/--
Slower version of `toHeadIndexQuick?` that "expands" let-declarations to make
sure we never hit a loose bound variable.
The performance of the `letE` alternative can be improved, but this function should not be in the hotpath
since `toHeadIndexQuick?` succeeds most of the time.
-/
private partial def toHeadIndexSlow : Expr → HeadIndex
| mvar mvarId => HeadIndex.mvar mvarId
| fvar fvarId => HeadIndex.fvar fvarId
| const constName _ => HeadIndex.const constName
| proj structName idx _ => HeadIndex.proj structName idx
| sort _ => HeadIndex.sort
| lam .. => HeadIndex.lam
| forallE .. => HeadIndex.forallE
| lit v => HeadIndex.lit v
| app f _ => toHeadIndexSlow f
| letE _ _ v b _ => toHeadIndexSlow (b.instantiate1 v)
| mdata _ e => toHeadIndexSlow e
| _ => panic! "unexpected expression kind"
/--
Convert the given expression into a `HeadIndex`.
-/
def toHeadIndex (e : Expr) : HeadIndex :=
match toHeadIndexQuick? e with
| some i => i
| none => toHeadIndexSlow e
end Expr
end Lean
|
02a5db6af52107993aed0babeb7474209ec18f84
|
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
|
/tests/elabissues/variable_universe_bug.lean
|
6077d9b108aced00dc3884398f084e3103b48b4e
|
[
"Apache-2.0"
] |
permissive
|
mhuisi/lean4
|
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
|
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
|
refs/heads/master
| 1,621,225,489,283
| 1,585,142,689,000
| 1,585,142,689,000
| 250,590,438
| 0
| 2
|
Apache-2.0
| 1,602,443,220,000
| 1,585,327,814,000
|
C
|
UTF-8
|
Lean
| false
| false
| 551
|
lean
|
/-
Courtesy of @rwbarton.
This is just a bug report, but since we are going to soon rewrite the entire module in Lean4,
we don't want to bother fixing the C++ bug, and we don't want to add a failing test either.
The issue is that collecting implicit locals does not collect additional universe parameters
the locals depend on.
-/
universes v u
class Category (C : Type u) :=
(Hom : ∀ (X Y : C), Type v)
variables {C : Type u} [Category.{v, u} C]
def End (X : C) := Category.Hom X X -- invalid reference to undefined universe level parameter 'v'
|
712d3a5264df3dd24fa92efb5e91f03598683e46
|
e0f9ba56b7fedc16ef8697f6caeef5898b435143
|
/src/tactic/localized.lean
|
ff8f7e39404daa8adf6177c0fff076d7f596feab
|
[
"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
| 5,229
|
lean
|
/-
Copyright (c) 2019 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import tactic.core
/-!
# Localized notation
This consists of two user-commands which allow you to declare notation and commands localized to a
namespace.
* Declare notation which is localized to a namespace using:
```lean
localized "infix ` ⊹ `:60 := my_add" in my.add
```
* After this command it will be available in the same section/namespace/file, just as if you wrote
`local infix ` ⊹ `:60 := my_add`
* You can open it in other places. The following command will declare the notation again as local
notation in that section/namespace/files:
```lean
open_locale my.add
```
* More generally, the following will declare all localized notation in the specified namespaces.
```lean
open_locale namespace1 namespace2 ...
```
* You can also declare other localized commands, like local attributes
```lean
localized "attribute [simp] le_refl" in le
```
The code is inspired by code from Gabriel Ebner from the
[hott3 repository](https://github.com/gebner/hott3).
-/
open lean lean.parser interactive tactic native
reserve notation `localized`
@[user_attribute]
meta def localized_attr : user_attribute (rb_lmap name string) unit := {
name := "_localized",
descr := "(interal) attribute that flags localized commands",
cache_cfg := ⟨λ ns, (do dcls ← ns.mmap (λ n, mk_const n >>= eval_expr (name × string)),
return $ rb_lmap.of_list dcls), []⟩
}
/-- Get all commands in the given notation namespace and return them as a list of strings -/
meta def get_localized (ns : list name) : tactic (list string) :=
do m ← localized_attr.get_cache,
return (ns.bind $ λ nm, m.find nm)
/-- Execute all commands in the given notation namespace -/
@[user_command] meta def open_locale_cmd (_ : parse $ tk "open_locale") : parser unit :=
do ns ← many ident,
cmds ← get_localized ns,
cmds.mmap' emit_code_here
/-- Add a new command to a notation namespace and execute it right now.
The new command is added as a declaration to the environment with name `_localized_decl.<number>`.
This declaration has attribute `_localized` and as value a name-string pair. -/
@[user_command] meta def localized_cmd (_ : parse $ tk "localized") : parser unit :=
do cmd ← parser.pexpr, cmd ← i_to_expr cmd, cmd ← eval_expr string cmd,
let cmd := "local " ++ cmd,
emit_code_here cmd,
tk "in",
nm ← ident,
env ← get_env,
let dummy_decl_name := mk_num_name `_localized_decl
((string.hash (cmd ++ nm.to_string) + env.fingerprint) % unsigned_sz),
add_decl (declaration.defn dummy_decl_name [] `(name × string)
(reflect (⟨nm, cmd⟩ : name × string)) (reducibility_hints.regular 1 tt) ff),
localized_attr.set dummy_decl_name unit.star tt
/--
This consists of two user-commands which allow you to declare notation and commands localized to a
namespace.
* Declare notation which is localized to a namespace using:
```lean
localized \"infix ` ⊹ `:60 := my_add\" in my.add
```
* After this command it will be available in the same section/namespace/file, just as if you wrote
`local infix ` ⊹ `:60 := my_add`
* You can open it in other places. The following command will declare the notation again as local
notation in that section/namespace/files:
```lean
open_locale my.add
```
* More generally, the following will declare all localized notation in the specified namespaces.
```lean
open_locale namespace1 namespace2 ...
```
* You can also declare other localized commands, like local attributes
```lean
localized \"attribute [simp] le_refl\" in le
```
* To see all localized commands in a given namespace, run:
```lean
run_cmd print_localized_commands [`my.add].
```
* To see a list of all namespaces with localized commands, run:
```lean
run_cmd do
m ← localized_attr.get_cache,
tactic.trace m.keys -- change to `tactic.trace m.to_list`
-- to list all the commands in each namespace
```
* Warning 1: as a limitation on user commands, you cannot put `open_locale` directly after your
imports. You have to write another command first (e.g. `open`, `namespace`, `universe variables`,
`noncomputable theory`, `run_cmd tactic.skip`, ...).
* Warning 2: You have to fully specify the names used in localized notation, so that the localized
notation also works when the appropriate namespaces are not opened.
-/
add_tactic_doc
{ name := "localized notation",
category := doc_category.cmd,
decl_names := [`localized_cmd, `open_locale_cmd],
tags := ["notation", "type classes"] }
/-- Print all commands in a given notation namespace -/
meta def print_localized_commands (ns : list name) : tactic unit :=
do cmds ← get_localized ns, cmds.mmap' trace
-- you can run `open_locale classical` to get the decidability of all propositions.
localized "attribute [instance, priority 9] classical.prop_decidable" in classical
localized "postfix `?`:9001 := optional" in parser
localized "postfix *:9001 := lean.parser.many" in parser
|
f6195151d38aa947d99fe15d3ca3ce6a14b770bf
|
7cef822f3b952965621309e88eadf618da0c8ae9
|
/src/order/basic.lean
|
6300dc09dd7499acd05c9d303397ded66cde6bd4
|
[
"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
| 26,779
|
lean
|
/-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Mario Carneiro
-/
import logic.basic data.sum data.set.basic algebra.order
open function
/- TODO: automatic construction of dual definitions / theorems -/
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop}
theorem ge_of_eq [preorder α] {a b : α} : a = b → a ≥ b :=
λ h, h ▸ le_refl a
theorem is_refl.swap (r) [is_refl α r] : is_refl α (swap r) := ⟨refl_of r⟩
theorem is_irrefl.swap (r) [is_irrefl α r] : is_irrefl α (swap r) := ⟨irrefl_of r⟩
theorem is_trans.swap (r) [is_trans α r] : is_trans α (swap r) :=
⟨λ a b c h₁ h₂, trans_of r h₂ h₁⟩
theorem is_antisymm.swap (r) [is_antisymm α r] : is_antisymm α (swap r) :=
⟨λ a b h₁ h₂, antisymm h₂ h₁⟩
theorem is_asymm.swap (r) [is_asymm α r] : is_asymm α (swap r) :=
⟨λ a b h₁ h₂, asymm_of r h₂ h₁⟩
theorem is_total.swap (r) [is_total α r] : is_total α (swap r) :=
⟨λ a b, (total_of r a b).swap⟩
theorem is_trichotomous.swap (r) [is_trichotomous α r] : is_trichotomous α (swap r) :=
⟨λ a b, by simpa [swap, or.comm, or.left_comm] using trichotomous_of r a b⟩
theorem is_preorder.swap (r) [is_preorder α r] : is_preorder α (swap r) :=
{..@is_refl.swap α r _, ..@is_trans.swap α r _}
theorem is_strict_order.swap (r) [is_strict_order α r] : is_strict_order α (swap r) :=
{..@is_irrefl.swap α r _, ..@is_trans.swap α r _}
theorem is_partial_order.swap (r) [is_partial_order α r] : is_partial_order α (swap r) :=
{..@is_preorder.swap α r _, ..@is_antisymm.swap α r _}
theorem is_total_preorder.swap (r) [is_total_preorder α r] : is_total_preorder α (swap r) :=
{..@is_preorder.swap α r _, ..@is_total.swap α r _}
theorem is_linear_order.swap (r) [is_linear_order α r] : is_linear_order α (swap r) :=
{..@is_partial_order.swap α r _, ..@is_total.swap α r _}
lemma antisymm_of_asymm (r) [is_asymm α r] : is_antisymm α r :=
⟨λ x y h₁ h₂, (asymm h₁ h₂).elim⟩
/- Convert algebraic structure style to explicit relation style typeclasses -/
instance [preorder α] : is_refl α (≤) := ⟨le_refl⟩
instance [preorder α] : is_refl α (≥) := is_refl.swap _
instance [preorder α] : is_trans α (≤) := ⟨@le_trans _ _⟩
instance [preorder α] : is_trans α (≥) := is_trans.swap _
instance [preorder α] : is_preorder α (≤) := {}
instance [preorder α] : is_preorder α (≥) := {}
instance [preorder α] : is_irrefl α (<) := ⟨lt_irrefl⟩
instance [preorder α] : is_irrefl α (>) := is_irrefl.swap _
instance [preorder α] : is_trans α (<) := ⟨@lt_trans _ _⟩
instance [preorder α] : is_trans α (>) := is_trans.swap _
instance [preorder α] : is_asymm α (<) := ⟨@lt_asymm _ _⟩
instance [preorder α] : is_asymm α (>) := is_asymm.swap _
instance [preorder α] : is_antisymm α (<) := antisymm_of_asymm _
instance [preorder α] : is_antisymm α (>) := antisymm_of_asymm _
instance [preorder α] : is_strict_order α (<) := {}
instance [preorder α] : is_strict_order α (>) := {}
instance preorder.is_total_preorder [preorder α] [is_total α (≤)] : is_total_preorder α (≤) := {}
instance [partial_order α] : is_antisymm α (≤) := ⟨@le_antisymm _ _⟩
instance [partial_order α] : is_antisymm α (≥) := is_antisymm.swap _
instance [partial_order α] : is_partial_order α (≤) := {}
instance [partial_order α] : is_partial_order α (≥) := {}
instance [linear_order α] : is_total α (≤) := ⟨le_total⟩
instance [linear_order α] : is_total α (≥) := is_total.swap _
instance linear_order.is_total_preorder [linear_order α] : is_total_preorder α (≤) := by apply_instance
instance [linear_order α] : is_total_preorder α (≥) := {}
instance [linear_order α] : is_linear_order α (≤) := {}
instance [linear_order α] : is_linear_order α (≥) := {}
instance [linear_order α] : is_trichotomous α (<) := ⟨lt_trichotomy⟩
instance [linear_order α] : is_trichotomous α (>) := is_trichotomous.swap _
theorem preorder.ext {α} {A B : preorder α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
resetI, cases A, cases B, congr,
{ funext x y, exact propext (H x y) },
{ funext x y,
dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le H,
simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, H] },
end
theorem partial_order.ext {α} {A B : partial_order α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
by haveI this := preorder.ext H;
cases A; cases B; injection this; congr'
theorem linear_order.ext {α} {A B : linear_order α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
by haveI this := partial_order.ext H;
cases A; cases B; injection this; congr'
/-- Given an order `R` on `β` and a function `f : α → β`,
the preimage order on `α` is defined by `x ≤ y ↔ f x ≤ f y`.
It is the unique order on `α` making `f` an order embedding
(assuming `f` is injective). -/
@[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y)
infix ` ⁻¹'o `:80 := order.preimage
section monotone
variables [preorder α] [preorder β] [preorder γ]
/-- A function between preorders is monotone if
`a ≤ b` implies `f a ≤ f b`. -/
def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b
theorem monotone_id : @monotone α α _ _ id := assume x y h, h
theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b
protected theorem monotone.comp {g : β → γ} {f : α → β} (m_g : monotone g) (m_f : monotone f) :
monotone (g ∘ f) :=
assume a b h, m_g (m_f h)
lemma monotone_of_monotone_nat {f : ℕ → α} (hf : ∀n, f n ≤ f (n + 1)) :
monotone f | n m h :=
begin
induction h,
{ refl },
{ transitivity, assumption, exact hf _ }
end
lemma reflect_lt {α β} [linear_order α] [preorder β] {f : α → β} (hf : monotone f)
{x x' : α} (h : f x < f x') : x < x' :=
by { rw [← not_le], intro h', apply not_le_of_lt h, exact hf h' }
end monotone
/-- Type tag for a set with dual order: `≤` means `≥` and `<` means `>`. -/
def order_dual (α : Type*) := α
namespace order_dual
instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩
instance (α : Type*) [has_lt α] : has_lt (order_dual α) := ⟨λx y:α, y < x⟩
instance (α : Type*) [preorder α] : preorder (order_dual α) :=
{ le_refl := le_refl,
le_trans := assume a b c hab hbc, le_trans hbc hab,
lt_iff_le_not_le := λ _ _, lt_iff_le_not_le,
.. order_dual.has_le α,
.. order_dual.has_lt α }
instance (α : Type*) [partial_order α] : partial_order (order_dual α) :=
{ le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α }
instance (α : Type*) [linear_order α] : linear_order (order_dual α) :=
{ le_total := assume a b:α, le_total b a, .. order_dual.partial_order α }
instance (α : Type*) [decidable_linear_order α] : decidable_linear_order (order_dual α) :=
{ decidable_le := show decidable_rel (λa b:α, b ≤ a), by apply_instance,
decidable_lt := show decidable_rel (λa b:α, b < a), by apply_instance,
.. order_dual.linear_order α }
instance : Π [inhabited α], inhabited (order_dual α) := id
end order_dual
/- order instances on the function space -/
instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) :=
{ le := λx y, ∀i, x i ≤ y i,
le_refl := assume a i, le_refl (a i),
le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) }
instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] : partial_order (Πi, α i) :=
{ le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)),
..pi.preorder }
theorem comp_le_comp_left_of_monotone [preorder α] [preorder β]
{f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) :=
assume x, m_f (le_gh x)
section monotone
variables [preorder α] [preorder γ]
theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f :=
assume a a' h b, m b h
theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) :=
assume a a' h, m h b
end monotone
def preorder.lift {α β} (f : α → β) (i : preorder β) : preorder α :=
by exactI
{ le := λx y, f x ≤ f y,
le_refl := λ a, le_refl _,
le_trans := λ a b c, le_trans,
lt := λx y, f x < f y,
lt_iff_le_not_le := λ a b, lt_iff_le_not_le }
def partial_order.lift {α β} (f : α → β) (inj : injective f) (i : partial_order β) :
partial_order α :=
by exactI
{ le_antisymm := λ a b h₁ h₂, inj (le_antisymm h₁ h₂), .. preorder.lift f (by apply_instance) }
def linear_order.lift {α β} (f : α → β) (inj : injective f) (i : linear_order β) :
linear_order α :=
by exactI
{ le_total := λx y, le_total (f x) (f y), .. partial_order.lift f inj (by apply_instance) }
def decidable_linear_order.lift {α β} (f : α → β) (inj : injective f)
(i : decidable_linear_order β) : decidable_linear_order α :=
by exactI
{ decidable_le := λ x y, show decidable (f x ≤ f y), by apply_instance,
decidable_lt := λ x y, show decidable (f x < f y), by apply_instance,
decidable_eq := λ x y, decidable_of_iff _ ⟨@inj x y, congr_arg f⟩,
.. linear_order.lift f inj (by apply_instance) }
instance subtype.preorder {α} [i : preorder α] (p : α → Prop) : preorder (subtype p) :=
preorder.lift subtype.val i
instance subtype.partial_order {α} [i : partial_order α] (p : α → Prop) : partial_order (subtype p) :=
partial_order.lift subtype.val subtype.val_injective i
instance subtype.linear_order {α} [i : linear_order α] (p : α → Prop) : linear_order (subtype p) :=
linear_order.lift subtype.val subtype.val_injective i
instance subtype.decidable_linear_order {α} [i : decidable_linear_order α] (p : α → Prop) :
decidable_linear_order (subtype p) :=
decidable_linear_order.lift subtype.val subtype.val_injective i
instance prod.has_le (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) :=
⟨λp q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩
instance prod.preorder (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) :=
{ le_refl := assume ⟨a, b⟩, ⟨le_refl a, le_refl b⟩,
le_trans := assume ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩,
⟨le_trans hac hce, le_trans hbd hdf⟩,
.. prod.has_le α β }
/-- The pointwise partial order on a product.
(The lexicographic ordering is defined in order/lexicographic.lean, and the instances are
available via the type synonym `lex α β = α × β`.) -/
instance prod.partial_order (α : Type u) (β : Type v) [partial_order α] [partial_order β] :
partial_order (α × β) :=
{ le_antisymm := assume ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩,
prod.ext (le_antisymm hac hca) (le_antisymm hbd hdb),
.. prod.preorder α β }
/- additional order classes -/
/-- order without a top element; somtimes called cofinal -/
class no_top_order (α : Type u) [preorder α] : Prop :=
(no_top : ∀a:α, ∃a', a < a')
lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' :=
no_top_order.no_top
/-- order without a bottom element; somtimes called coinitial or dense -/
class no_bot_order (α : Type u) [preorder α] : Prop :=
(no_bot : ∀a:α, ∃a', a' < a)
lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a :=
no_bot_order.no_bot
/-- An order is dense if there is an element between any pair of distinct elements. -/
class densely_ordered (α : Type u) [preorder α] : Prop :=
(dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂)
lemma dense [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ :=
densely_ordered.dense
lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃>a₂, a₁ ≤ a₃) :
a₁ ≤ a₂ :=
le_of_not_gt $ assume ha,
let ⟨a, ha₁, ha₂⟩ := dense ha in
lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›)
lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ :=
le_antisymm (le_of_forall_le_of_dense h₂) h₁
lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}(h : ∀a₃<a₁, a₂ ≥ a₃) :
a₁ ≤ a₂ :=
le_of_not_gt $ assume ha,
let ⟨a, ha₁, ha₂⟩ := dense ha in
lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a›
lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₂ ≥ a₃) : a₁ = a₂ :=
le_antisymm (le_of_forall_ge_of_dense h₂) h₁
lemma dense_or_discrete [linear_order α] (a₁ a₂ : α) :
(∃a, a₁ < a ∧ a < a₂) ∨ ((∀a>a₁, a ≥ a₂) ∧ (∀a<a₂, a ≤ a₁)) :=
classical.or_iff_not_imp_left.2 $ assume h,
⟨assume a ha₁, le_of_not_gt $ assume ha₂, h ⟨a, ha₁, ha₂⟩,
assume a ha₂, le_of_not_gt $ assume ha₁, h ⟨a, ha₁, ha₂⟩⟩
lemma trans_trichotomous_left [is_trans α r] [is_trichotomous α r] {a b c : α} :
¬r b a → r b c → r a c :=
begin
intros h₁ h₂, rcases trichotomous_of r a b with h₃|h₃|h₃,
exact trans h₃ h₂, rw h₃, exact h₂, exfalso, exact h₁ h₃
end
lemma trans_trichotomous_right [is_trans α r] [is_trichotomous α r] {a b c : α} :
r a b → ¬r c b → r a c :=
begin
intros h₁ h₂, rcases trichotomous_of r b c with h₃|h₃|h₃,
exact trans h₁ h₃, rw ←h₃, exact h₁, exfalso, exact h₂ h₃
end
variables {s : β → β → Prop} {t : γ → γ → Prop}
theorem is_irrefl_of_is_asymm [is_asymm α r] : is_irrefl α r :=
⟨λ a h, asymm h h⟩
/-- Construct a partial order from a `is_strict_order` relation -/
def partial_order_of_SO (r) [is_strict_order α r] : partial_order α :=
{ le := λ x y, x = y ∨ r x y,
lt := r,
le_refl := λ x, or.inl rfl,
le_trans := λ x y z h₁ h₂,
match y, z, h₁, h₂ with
| _, _, or.inl rfl, h₂ := h₂
| _, _, h₁, or.inl rfl := h₁
| _, _, or.inr h₁, or.inr h₂ := or.inr (trans h₁ h₂)
end,
le_antisymm := λ x y h₁ h₂,
match y, h₁, h₂ with
| _, or.inl rfl, h₂ := rfl
| _, h₁, or.inl rfl := rfl
| _, or.inr h₁, or.inr h₂ := (asymm h₁ h₂).elim
end,
lt_iff_le_not_le := λ x y,
⟨λ h, ⟨or.inr h, not_or
(λ e, by rw e at h; exact irrefl _ h)
(asymm h)⟩,
λ ⟨h₁, h₂⟩, h₁.resolve_left (λ e, h₂ $ e ▸ or.inl rfl)⟩ }
section prio
set_option default_priority 100 -- see Note [default priority]
/-- This is basically the same as `is_strict_total_order`, but that definition is
in Type (probably by mistake) and also has redundant assumptions. -/
@[algebra] class is_strict_total_order' (α : Type u) (lt : α → α → Prop) extends is_trichotomous α lt, is_strict_order α lt : Prop.
end prio
/-- Construct a linear order from a `is_strict_total_order'` relation -/
def linear_order_of_STO' (r) [is_strict_total_order' α r] : linear_order α :=
{ le_total := λ x y,
match y, trichotomous_of r x y with
| y, or.inl h := or.inl (or.inr h)
| _, or.inr (or.inl rfl) := or.inl (or.inl rfl)
| _, or.inr (or.inr h) := or.inr (or.inr h)
end,
..partial_order_of_SO r }
/-- Construct a decidable linear order from a `is_strict_total_order'` relation -/
def decidable_linear_order_of_STO' (r) [is_strict_total_order' α r] [decidable_rel r] : decidable_linear_order α :=
by letI LO := linear_order_of_STO' r; exact
{ decidable_le := λ x y, decidable_of_iff (¬ r y x) (@not_lt _ _ y x),
..LO }
noncomputable def classical.DLO (α) [LO : linear_order α] : decidable_linear_order α :=
{ decidable_le := classical.dec_rel _, ..LO }
theorem is_strict_total_order'.swap (r) [is_strict_total_order' α r] : is_strict_total_order' α (swap r) :=
{..is_trichotomous.swap r, ..is_strict_order.swap r}
instance [linear_order α] : is_strict_total_order' α (<) := {}
/-- A connected order is one satisfying the condition `a < c → a < b ∨ b < c`.
This is recognizable as an intuitionistic substitute for `a ≤ b ∨ b ≤ a` on
the constructive reals, and is also known as negative transitivity,
since the contrapositive asserts transitivity of the relation `¬ a < b`. -/
@[algebra] class is_order_connected (α : Type u) (lt : α → α → Prop) : Prop :=
(conn : ∀ a b c, lt a c → lt a b ∨ lt b c)
theorem is_order_connected.neg_trans {r : α → α → Prop} [is_order_connected α r]
{a b c} (h₁ : ¬ r a b) (h₂ : ¬ r b c) : ¬ r a c :=
mt (is_order_connected.conn a b c) $ by simp [h₁, h₂]
theorem is_strict_weak_order_of_is_order_connected [is_asymm α r]
[is_order_connected α r] : is_strict_weak_order α r :=
{ trans := λ a b c h₁ h₂, (is_order_connected.conn _ c _ h₁).resolve_right (asymm h₂),
incomp_trans := λ a b c ⟨h₁, h₂⟩ ⟨h₃, h₄⟩,
⟨is_order_connected.neg_trans h₁ h₃, is_order_connected.neg_trans h₄ h₂⟩,
..@is_irrefl_of_is_asymm α r _ }
@[priority 100] -- see Note [lower instance priority]
instance is_order_connected_of_is_strict_total_order'
[is_strict_total_order' α r] : is_order_connected α r :=
⟨λ a b c h, (trichotomous _ _).imp_right (λ o,
o.elim (λ e, e ▸ h) (λ h', trans h' h))⟩
@[priority 100] -- see Note [lower instance priority]
instance is_strict_total_order_of_is_strict_total_order'
[is_strict_total_order' α r] : is_strict_total_order α r :=
{..is_strict_weak_order_of_is_order_connected}
instance [linear_order α] : is_strict_total_order α (<) := by apply_instance
instance [linear_order α] : is_order_connected α (<) := by apply_instance
instance [linear_order α] : is_incomp_trans α (<) := by apply_instance
instance [linear_order α] : is_strict_weak_order α (<) := by apply_instance
/-- An extensional relation is one in which an element is determined by its set
of predecessors. It is named for the `x ∈ y` relation in set theory, whose
extensionality is one of the first axioms of ZFC. -/
@[algebra] class is_extensional (α : Type u) (r : α → α → Prop) : Prop :=
(ext : ∀ a b, (∀ x, r x a ↔ r x b) → a = b)
@[priority 100] -- see Note [lower instance priority]
instance is_extensional_of_is_strict_total_order'
[is_strict_total_order' α r] : is_extensional α r :=
⟨λ a b H, ((@trichotomous _ r _ a b)
.resolve_left $ mt (H _).2 (irrefl a))
.resolve_right $ mt (H _).1 (irrefl b)⟩
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A well order is a well-founded linear order. -/
@[algebra] class is_well_order (α : Type u) (r : α → α → Prop) extends is_strict_total_order' α r : Prop :=
(wf : well_founded r)
end prio
@[priority 100] -- see Note [lower instance priority]
instance is_well_order.is_strict_total_order {α} (r : α → α → Prop) [is_well_order α r] : is_strict_total_order α r := by apply_instance
@[priority 100] -- see Note [lower instance priority]
instance is_well_order.is_extensional {α} (r : α → α → Prop) [is_well_order α r] : is_extensional α r := by apply_instance
@[priority 100] -- see Note [lower instance priority]
instance is_well_order.is_trichotomous {α} (r : α → α → Prop) [is_well_order α r] : is_trichotomous α r := by apply_instance
@[priority 100] -- see Note [lower instance priority]
instance is_well_order.is_trans {α} (r : α → α → Prop) [is_well_order α r] : is_trans α r := by apply_instance
@[priority 100] -- see Note [lower instance priority]
instance is_well_order.is_irrefl {α} (r : α → α → Prop) [is_well_order α r] : is_irrefl α r := by apply_instance
@[priority 100] -- see Note [lower instance priority]
instance is_well_order.is_asymm {α} (r : α → α → Prop) [is_well_order α r] : is_asymm α r := by apply_instance
noncomputable def decidable_linear_order_of_is_well_order (r : α → α → Prop) [is_well_order α r] :
decidable_linear_order α :=
by { haveI := linear_order_of_STO' r, exact classical.DLO α }
instance empty_relation.is_well_order [subsingleton α] : is_well_order α empty_relation :=
{ trichotomous := λ a b, or.inr $ or.inl $ subsingleton.elim _ _,
irrefl := λ a, id,
trans := λ a b c, false.elim,
wf := ⟨λ a, ⟨_, λ y, false.elim⟩⟩ }
instance nat.lt.is_well_order : is_well_order ℕ (<) := ⟨nat.lt_wf⟩
instance sum.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α ⊕ β) (sum.lex r s) :=
{ trichotomous := λ a b, by cases a; cases b; simp; apply trichotomous,
irrefl := λ a, by cases a; simp; apply irrefl,
trans := λ a b c, by cases a; cases b; simp; cases c; simp; apply trans,
wf := sum.lex_wf (is_well_order.wf r) (is_well_order.wf s) }
instance prod.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α × β) (prod.lex r s) :=
{ trichotomous := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩,
match @trichotomous _ r _ a₁ b₁ with
| or.inl h₁ := or.inl $ prod.lex.left _ _ _ h₁
| or.inr (or.inr h₁) := or.inr $ or.inr $ prod.lex.left _ _ _ h₁
| or.inr (or.inl e) := e ▸ match @trichotomous _ s _ a₂ b₂ with
| or.inl h := or.inl $ prod.lex.right _ _ h
| or.inr (or.inr h) := or.inr $ or.inr $ prod.lex.right _ _ h
| or.inr (or.inl e) := e ▸ or.inr $ or.inl rfl
end
end,
irrefl := λ ⟨a₁, a₂⟩ h, by cases h with _ _ _ _ h _ _ _ h;
[exact irrefl _ h, exact irrefl _ h],
trans := λ a b c h₁ h₂, begin
cases h₁ with a₁ a₂ b₁ b₂ ab a₁ b₁ b₂ ab;
cases h₂ with _ _ c₁ c₂ bc _ _ c₂ bc,
{ exact prod.lex.left _ _ _ (trans ab bc) },
{ exact prod.lex.left _ _ _ ab },
{ exact prod.lex.left _ _ _ bc },
{ exact prod.lex.right _ _ (trans ab bc) }
end,
wf := prod.lex_wf (is_well_order.wf r) (is_well_order.wf s) }
/-- An unbounded or cofinal set -/
def unbounded (r : α → α → Prop) (s : set α) : Prop := ∀ a, ∃ b ∈ s, ¬ r b a
/-- A bounded or final set -/
def bounded (r : α → α → Prop) (s : set α) : Prop := ∃a, ∀ b ∈ s, r b a
@[simp] lemma not_bounded_iff {r : α → α → Prop} (s : set α) : ¬bounded r s ↔ unbounded r s :=
begin
classical,
simp only [bounded, unbounded, not_forall, not_exists, exists_prop, not_and, not_not]
end
@[simp] lemma not_unbounded_iff {r : α → α → Prop} (s : set α) : ¬unbounded r s ↔ bounded r s :=
by { classical, rw [not_iff_comm, not_bounded_iff] }
namespace well_founded
/-- If `r` is a well founded relation, then any nonempty set has a minimum element
with respect to `r`. -/
theorem has_min {α} {r : α → α → Prop} (H : well_founded r)
(s : set α) : s.nonempty → ∃ a ∈ s, ∀ x ∈ s, ¬ r x a
| ⟨a, ha⟩ := (acc.rec_on (H.apply a) $ λ x _ IH, classical.not_imp_not.1 $ λ hne hx, hne $
⟨x, hx, λ y hy hyx, hne $ IH y hyx hy⟩) ha
/-- The minimum element of a nonempty set in a well-founded order -/
noncomputable def min {α} {r : α → α → Prop} (H : well_founded r)
(p : set α) (h : p.nonempty) : α :=
classical.some (H.has_min p h)
theorem min_mem {α} {r : α → α → Prop} (H : well_founded r)
(p : set α) (h : p.nonempty) : H.min p h ∈ p :=
let ⟨h, _⟩ := classical.some_spec (H.has_min p h) in h
theorem not_lt_min {α} {r : α → α → Prop} (H : well_founded r)
(p : set α) (h : p.nonempty) {x} (xp : x ∈ p) : ¬ r x (H.min p h) :=
let ⟨_, h'⟩ := classical.some_spec (H.has_min p h) in h' _ xp
open set
protected noncomputable def sup {α} {r : α → α → Prop} (wf : well_founded r) (s : set α)
(h : bounded r s) : α :=
wf.min { x | ∀a ∈ s, r a x } h
protected lemma lt_sup {α} {r : α → α → Prop} (wf : well_founded r) {s : set α} (h : bounded r s)
{x} (hx : x ∈ s) : r x (wf.sup s h) :=
min_mem wf { x | ∀a ∈ s, r a x } h x hx
section
open_locale classical
protected noncomputable def succ {α} {r : α → α → Prop} (wf : well_founded r) (x : α) : α :=
if h : ∃y, r x y then wf.min { y | r x y } h else x
protected lemma lt_succ {α} {r : α → α → Prop} (wf : well_founded r) {x : α} (h : ∃y, r x y) :
r x (wf.succ x) :=
by { rw [well_founded.succ, dif_pos h], apply min_mem }
end
protected lemma lt_succ_iff {α} {r : α → α → Prop} [wo : is_well_order α r] {x : α} (h : ∃y, r x y)
(y : α) : r y (wo.wf.succ x) ↔ r y x ∨ y = x :=
begin
split,
{ intro h', have : ¬r x y,
{ intro hy, rw [well_founded.succ, dif_pos] at h',
exact wo.wf.not_lt_min _ h hy h' },
rcases trichotomous_of r x y with hy | hy | hy,
exfalso, exact this hy,
right, exact hy.symm,
left, exact hy },
rintro (hy | rfl), exact trans hy (wo.wf.lt_succ h), exact wo.wf.lt_succ h
end
end well_founded
variable (r)
local infix ` ≼ ` : 50 := r
/-- A family of elements of α is directed (with respect to a relation `≼` on α)
if there is a member of the family `≼`-above any pair in the family. -/
def directed {ι : Sort v} (f : ι → α) := ∀x y, ∃z, f x ≼ f z ∧ f y ≼ f z
/-- A subset of α is directed if there is an element of the set `≼`-above any
pair of elements in the set. -/
def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃z ∈ s, x ≼ z ∧ y ≼ z
theorem directed_on_iff_directed {s} : @directed_on α r s ↔ directed r (coe : s → α) :=
by simp [directed, directed_on]; refine ball_congr (λ x hx, by simp; refl)
theorem directed_comp {ι} (f : ι → β) (g : β → α) :
directed r (g ∘ f) ↔ directed (g ⁻¹'o r) f := iff.rfl
theorem directed_mono {s : α → α → Prop} {ι} (f : ι → α)
(H : ∀ a b, r a b → s a b) (h : directed r f) : directed s f :=
λ a b, let ⟨c, h₁, h₂⟩ := h a b in ⟨c, H _ _ h₁, H _ _ h₂⟩
/-- A monotone function on a linear order is directed. -/
lemma directed_of_mono {ι} [decidable_linear_order ι] (f : ι → α)
(H : ∀ i j, i ≤ j → f i ≼ f j) : directed (≼) f :=
λ a b, ⟨max a b, H _ _ (le_max_left _ _), H _ _ (le_max_right _ _)⟩
section prio
set_option default_priority 100 -- see Note [default priority]
class directed_order (α : Type u) extends preorder α :=
(directed : ∀ i j : α, ∃ k, i ≤ k ∧ j ≤ k)
end prio
|
a919e729093d84f3ef00a2e2de055e0dc10ac6dc
|
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
|
/library/init/meta/options.lean
|
4c4d06b9a69a07832d255aad2b953d42aa72f9e1
|
[
"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,388
|
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.name
universe variables u
meta_constant options : Type 1
meta_constant options.size : options → nat
meta_constant options.mk : options
meta_constant options.contains : options → name → bool
meta_constant options.set_bool : options → name → bool → options
meta_constant options.set_nat : options → name → nat → options
meta_constant options.set_string : options → name → string → options
meta_constant options.get_bool : options → name → bool → bool
meta_constant options.get_nat : options → name → nat → nat
meta_constant options.get_string : options → name → string → string
meta_constant options.join : options → options → options
meta_constant options.fold {A : Type u} : options → A → (name → A → A) → A
meta_constant options.has_decidable_eq : decidable_eq options
attribute [instance] options.has_decidable_eq
attribute [instance]
meta_definition options.has_add : has_add options :=
has_add.mk options.join
attribute [instance]
meta_definition options.is_inhabited : inhabited options :=
inhabited.mk options.mk
|
52ff76cc07082d197918b6dcaf41674e31447e68
|
8cae430f0a71442d02dbb1cbb14073b31048e4b0
|
/src/ring_theory/ring_hom_properties.lean
|
e83e147d9c865f92c204a0fc7a3fe1cb40a5452d
|
[
"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
| 6,696
|
lean
|
/-
Copyright (c) 2022 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import algebra.category.Ring.constructions
import algebra.category.Ring.colimits
import category_theory.isomorphism
import ring_theory.localization.away.basic
import ring_theory.is_tensor_product
/-!
# Properties of ring homomorphisms
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We provide the basic framework for talking about properties of ring homomorphisms.
The following meta-properties of predicates on ring homomorphisms are defined
* `ring_hom.respects_iso`: `P` respects isomorphisms if `P f → P (e ≫ f)` and
`P f → P (f ≫ e)`, where `e` is an isomorphism.
* `ring_hom.stable_under_composition`: `P` is stable under composition if `P f → P g → P (f ≫ g)`.
* `ring_hom.stable_under_base_change`: `P` is stable under base change if `P (S ⟶ Y)`
implies `P (X ⟶ X ⊗[S] Y)`.
-/
universe u
open category_theory opposite category_theory.limits
namespace ring_hom
variable (P : ∀ {R S : Type u} [comm_ring R] [comm_ring S] (f : by exactI R →+* S), Prop)
include P
section respects_iso
/-- A property `respects_iso` if it still holds when composed with an isomorphism -/
def respects_iso : Prop :=
(∀ {R S T : Type u} [comm_ring R] [comm_ring S] [comm_ring T], by exactI
∀ (f : R →+* S) (e : S ≃+* T) (hf : P f), P (e.to_ring_hom.comp f)) ∧
(∀ {R S T : Type u} [comm_ring R] [comm_ring S] [comm_ring T], by exactI
∀ (f : S →+* T) (e : R ≃+* S) (hf : P f), P (f.comp e.to_ring_hom))
variable {P}
lemma respects_iso.cancel_left_is_iso (hP : respects_iso @P) {R S T : CommRing}
(f : R ⟶ S) (g : S ⟶ T)
[is_iso f] : P (f ≫ g) ↔ P g :=
⟨λ H, by { convert hP.2 (f ≫ g) (as_iso f).symm.CommRing_iso_to_ring_equiv H,
exact (is_iso.inv_hom_id_assoc _ _).symm }, hP.2 g (as_iso f).CommRing_iso_to_ring_equiv⟩
lemma respects_iso.cancel_right_is_iso (hP : respects_iso @P) {R S T : CommRing}
(f : R ⟶ S) (g : S ⟶ T)
[is_iso g] : P (f ≫ g) ↔ P f :=
⟨λ H, by { convert hP.1 (f ≫ g) (as_iso g).symm.CommRing_iso_to_ring_equiv H,
change f = f ≫ g ≫ (inv g), simp }, hP.1 f (as_iso g).CommRing_iso_to_ring_equiv⟩
lemma respects_iso.is_localization_away_iff (hP : ring_hom.respects_iso @P) {R S : Type*}
(R' S' : Type*) [comm_ring R] [comm_ring S] [comm_ring R'] [comm_ring S'] [algebra R R']
[algebra S S'] (f : R →+* S) (r : R) [is_localization.away r R'] [is_localization.away (f r) S'] :
P (localization.away_map f r) ↔ P (is_localization.away.map R' S' f r) :=
begin
let e₁ : R' ≃+* localization.away r :=
(is_localization.alg_equiv (submonoid.powers r) _ _).to_ring_equiv,
let e₂ : localization.away (f r) ≃+* S' :=
(is_localization.alg_equiv (submonoid.powers (f r)) _ _).to_ring_equiv,
refine (hP.cancel_left_is_iso e₁.to_CommRing_iso.hom (CommRing.of_hom _)).symm.trans _,
refine (hP.cancel_right_is_iso (CommRing.of_hom _) e₂.to_CommRing_iso.hom).symm.trans _,
rw ← eq_iff_iff,
congr' 1,
dsimp [CommRing.of_hom, CommRing.of, bundled.of],
refine is_localization.ring_hom_ext (submonoid.powers r) _,
ext1,
revert e₁ e₂,
dsimp [ring_equiv.to_ring_hom, is_localization.away.map],
simp only [category_theory.comp_apply, ring_equiv.refl_apply, is_localization.alg_equiv_apply,
is_localization.ring_equiv_of_ring_equiv_apply, ring_hom.coe_mk, ring_equiv.to_fun_eq_coe,
is_localization.ring_equiv_of_ring_equiv_eq, is_localization.map_eq],
end
end respects_iso
section stable_under_composition
/-- A property is `stable_under_composition` if the composition of two such morphisms
still falls in the class. -/
def stable_under_composition : Prop :=
∀ ⦃R S T⦄ [comm_ring R] [comm_ring S] [comm_ring T],
by exactI ∀ (f : R →+* S) (g : S →+* T) (hf : P f) (hg : P g), P (g.comp f)
variable {P}
lemma stable_under_composition.respects_iso (hP : ring_hom.stable_under_composition @P)
(hP' : ∀ {R S : Type*} [comm_ring R] [comm_ring S] (e : by exactI R ≃+* S),
by exactI P e.to_ring_hom) : ring_hom.respects_iso @P :=
begin
split,
{ introv H, resetI, apply hP, exacts [H, hP' e] },
{ introv H, resetI, apply hP, exacts [hP' e, H] }
end
end stable_under_composition
section stable_under_base_change
/-- A morphism property `P` is `stable_under_base_change` if `P(S →+* A)` implies
`P(B →+* A ⊗[S] B)`. -/
def stable_under_base_change : Prop :=
∀ (R S R' S') [comm_ring R] [comm_ring S] [comm_ring R'] [comm_ring S'],
by exactI ∀ [algebra R S] [algebra R R'] [algebra R S'] [algebra S S'] [algebra R' S'],
by exactI ∀ [is_scalar_tower R S S'] [is_scalar_tower R R' S'],
by exactI ∀ [algebra.is_pushout R S R' S'], P (algebra_map R S) → P (algebra_map R' S')
lemma stable_under_base_change.mk
(h₁ : respects_iso @P)
(h₂ : ∀ ⦃R S T⦄ [comm_ring R] [comm_ring S] [comm_ring T],
by exactI ∀ [algebra R S] [algebra R T], by exactI (P (algebra_map R T) →
P (algebra.tensor_product.include_left.to_ring_hom : S →+* tensor_product R S T))) :
stable_under_base_change @P :=
begin
introv R h H,
resetI,
let e := h.symm.1.equiv,
let f' := algebra.tensor_product.product_map (is_scalar_tower.to_alg_hom R R' S')
(is_scalar_tower.to_alg_hom R S S'),
have : ∀ x, e x = f' x,
{ intro x,
change e.to_linear_map.restrict_scalars R x = f'.to_linear_map x,
congr' 1,
apply tensor_product.ext',
intros x y,
simp [is_base_change.equiv_tmul, algebra.smul_def] },
convert h₁.1 _ _ (h₂ H : P (_ : R' →+* _)),
swap,
{ refine { map_mul' := λ x y, _, ..e },
change e (x * y) = e x * e y,
simp_rw this,
exact map_mul f' _ _ },
{ ext,
change _ = e (x ⊗ₜ[R] 1),
dsimp only [e],
rw [h.symm.1.equiv_tmul, algebra.smul_def, alg_hom.to_linear_map_apply, map_one, mul_one] }
end
omit P
local attribute [instance] algebra.tensor_product.right_algebra
lemma stable_under_base_change.pushout_inl
(hP : ring_hom.stable_under_base_change @P) (hP' : ring_hom.respects_iso @P) {R S T : CommRing}
(f : R ⟶ S) (g : R ⟶ T) (H : P g) : P (pushout.inl : S ⟶ pushout f g) :=
begin
rw [← (show _ = pushout.inl, from colimit.iso_colimit_cocone_ι_inv
⟨_, CommRing.pushout_cocone_is_colimit f g⟩ walking_span.left), hP'.cancel_right_is_iso],
letI := f.to_algebra,
letI := g.to_algebra,
dsimp only [CommRing.pushout_cocone_inl, pushout_cocone.ι_app_left],
apply hP R T S (tensor_product R S T),
exact H,
end
end stable_under_base_change
end ring_hom
|
8679561b6ab86e95c3f59b6c9d29eb6f4579f777
|
54c9ed381c63410c9b6af3b0a1722c41152f037f
|
/Binport/OldRecursor.lean
|
22babff6f3738ed0ac41bb0d1d070b4a843c1491
|
[
"Apache-2.0"
] |
permissive
|
dselsam/binport
|
0233f1aa961a77c4fc96f0dccc780d958c5efc6c
|
aef374df0e169e2c3f1dc911de240c076315805c
|
refs/heads/master
| 1,687,453,448,108
| 1,627,483,296,000
| 1,627,483,296,000
| 333,825,622
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 2,129
|
lean
|
/-
Copyright (c) 2020 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import Binport.Util
import Lean
namespace Binport
open Lean Lean.Meta
def mkOldRecursor (indTy oldRecName : Name) : MetaM (Option Declaration) := do
let some (ConstantInfo.inductInfo indI) ← getConst? indTy | throwError (toString indTy)
let indTy' ← inferType (mkConst indI.name (indI.levelParams.map mkLevelParam))
let useDepElim ← forallTelescopeReducing indTy' $ fun _ indSort => do
let Expr.sort level _ ← pure indSort | throwError (toString indSort)
level.normalize != levelZero;
if useDepElim then return none
let some (ConstantInfo.recInfo recI) ← getConst? (indTy ++ "rec") | throwError (toString $ indTy ++ "rec")
let crec := mkConst recI.name (recI.levelParams.map mkLevelParam);
let recTy ← inferType crec;
forallTelescopeReducing recTy $ fun args _ => do
let (params, args) := args.splitAt recI.numParams;
let (motive, args) := args.splitAt 1;
let motive := motive.get! 0;
let motiveTy ← inferType motive;
forallTelescopeReducing motiveTy $ fun _ elimSort => do
let Expr.sort elimLevel _ ← pure elimSort | throwError (toString elimSort)
let (minorPremises, args) := args.splitAt recI.numMinors
let (indices, major) := args.splitAt recI.numIndices
let majorPremise := major.get! 0
let oldMotiveTy ← Meta.mkForallFVars indices (mkSort elimLevel)
withLocalDecl `C BinderInfo.implicit oldMotiveTy $ fun oldMotive => do
let newMotive ← Meta.mkLambdaFVars (indices.push majorPremise) (mkAppN oldMotive indices)
let val ← Meta.mkLambdaFVars ((params).push oldMotive) $ mkAppN crec ((params).push newMotive)
let ty ← inferType val
pure $ Declaration.defnDecl {
name := oldRecName,
levelParams := recI.levelParams,
type := ty,
value := val,
safety := DefinitionSafety.safe,
hints := ReducibilityHints.abbrev,
}
end Binport
|
25f80ede13220932ba11527f4a8072b21a451427
|
48f4f349e1bb919d14ab7e5921d0cfe825f4c423
|
/folklore/derivatives.lean
|
7b375fdfbca94bf862e3f7c9709075f3c05d82e2
|
[] |
no_license
|
thalesant/formalabstracts-2017
|
fdf4ff90d30ab1dcb6d4cf16a068a997ea5ecc80
|
c47181342c9e41954aa8d41f5049965b5f332bca
|
refs/heads/master
| 1,584,610,453,925
| 1,528,277,508,000
| 1,528,277,508,000
| 136,299,625
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 3,657
|
lean
|
/-
Frechet derivatives on Banach space
-/
import order.filter data.set meta_data data.list data.vector
.real_axiom algebra.module data.finset.basic .metric
.complex
noncomputable theory
namespace derivatives
open set filter classical nat int list vector real_axiom metric finset complex
local attribute [instance] prop_decidable
universes u v w
-- could do normed rings, non-multiplicative norms, as well.
-- variables { α :Type u} {β : Type v} ( x : α ) (y : β) [ring α] [topological_space α]
-- #check induced_space _ { x : α | x ≠ 0 }
-- #check product_topology
-- this must be somewhere already...
/-
def uncurry {α : Type u} {β : Type v} {γ : Type w} (f : α → β → γ ) (xy : α × β) :=
let (x,y) := xy in f x y
def curry {α : Type u} {β : Type v} {γ : Type w} (f : α × β → γ ) (x : α) (y : β) := f (x,y)
-/
class topological_ring (α : Type u) [rngtop : topological_space α] extends ring α :=
(minus_cont : continuous_map product_topology rngtop (λxy, xy.fst - xy.snd))
(time_cont : continuous_map product_topology rngtop (λxy, xy.fst * xy.snd))
class topological_field (α : Type u) [field α] [top : topological_space α] extends topological_ring α :=
(inv_cont : continuous_map (induced_space top { x : α | x ≠ 0 }) top (λx, x⁻¹))
variables {α : Type u} {β : Type v} (xy : α × β)
-- #check let (x,y) := xy in (x : α)
class multiplicative_normed_field (α : Type u) extends field α, metric_space α :=
(norm : α → ℝ)
(multiplicative : ∀ x y, norm(x*y) = norm x * norm y)
(norm_dist : ∀ x y, dist x y = norm (x - y))
--follows from metric
--(positivity : ∀ x, norm x ≥ 0)
--(norm0 : ∀ x, norm x = 0 ↔ x = 0)
--(triangle_inequality : ∀ x y, norm(x + y) ≤ norm x + norm y)
class topological_vector_space (α : Type u) (β : Type v) [field α] [X:topological_space β] extends vector_space α β :=
(closed_points : ∀ (x : β), is_closed X {x})
class normed_space (α : Type u) (β : Type v) [multiplicative_normed_field α] extends vector_space α β, metric_space β :=
(norm : β → ℝ := λ (v:β), dist v 0 )
(homogeneity : ∀ (c : α) (v : β), norm(c • v) = multiplicative_normed_field.norm c * norm v)
(norm_dist : ∀ v w, dist v w = norm (v - w))
axiom exists_real_multiplicative_normed_field :
(∃!p : multiplicative_normed_field ℝ, p.norm = real_abs)
instance real_multiplicative_normed_field :=
classical.some exists_real_multiplicative_normed_field
axiom exists_complex_multiplicative_normed_field :
(∃!p : multiplicative_normed_field ℂ, p.norm = complex.norm)
instance complex_multiplicative_normed_field :=
classical.some exists_complex_multiplicative_normed_field
class banach_space (α : Type u) (β : Type v) [multiplicative_normed_field α] extends normed_space α β, complete_metric_space β
class real_banach_space (β : Type v) extends banach_space ℝ β
def linear { α : Type u} {β : Type v} {γ : Type w} [field α] [vector_space α β] [vector_space α γ] (f : β → γ) : Prop :=
(∀ (x : α) (v : β), f (x • v) = x • f v) ∧
(∀ v w, f (v + w) = f v + f w)
-- bounded in a topological vector space
--def bounded { α : Type u} [topological_vector_space α]
/-
class complex_vector_space β extends vector_space ℂ β
class complex_normed_space (β : Type u) extends complex_vector_space β :=
(norm : β → ℝ)
(positivity : ∀ v, norm v ≥ 0)
(norm0 : ∀ v, norm v = 0 ↔ v = 0)
(homogeneity : ∀ (c : ℂ) (v : β), norm(c • v) = complex.norm c * norm v)
(triangle_inequality : ∀ v w, norm(v + w) ≤ norm v + norm w)
-/
end derivatives
|
078fe30db9e4e7833866becd54973591cd0c6216
|
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
|
/tests/lean/run/reduce2.lean
|
ff4c9d2bbcdb5b2926a4a9464c05f49c3b6f243b
|
[
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"
] |
permissive
|
leanprover/lean4
|
4bdf9790294964627eb9be79f5e8f6157780b4cc
|
f1f9dc0f2f531af3312398999d8b8303fa5f096b
|
refs/heads/master
| 1,693,360,665,786
| 1,693,350,868,000
| 1,693,350,868,000
| 129,571,436
| 2,827
| 311
|
Apache-2.0
| 1,694,716,156,000
| 1,523,760,560,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 129
|
lean
|
def fact : Nat → Nat
| 0 => 1
| (n+1) => (n+1)*fact n
def v1 := fact 10
theorem v1Eq : v1 = fact 10 :=
Eq.refl (fact 10)
|
91b6efea52333b5dc90b4e4a8ef39e84c767feb0
|
82e44445c70db0f03e30d7be725775f122d72f3e
|
/src/topology/continuous_on.lean
|
de17a427ced36c18880dfdc48ac98c71775bacf0
|
[
"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
| 47,115
|
lean
|
/-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import topology.constructions
/-!
# Neighborhoods and continuity relative to a subset
This file defines relative versions
* `nhds_within` of `nhds`
* `continuous_on` of `continuous`
* `continuous_within_at` of `continuous_at`
and proves their basic properties, including the relationships between
these restricted notions and the corresponding notions for the subtype
equipped with the subspace topology.
## Notation
* `𝓝 x`: the filter of neighborhoods of a point `x`;
* `𝓟 s`: the principal filter of a set `s`;
* `𝓝[s] x`: the filter `nhds_within x s` of neighborhoods of a point `x` within a set `s`.
-/
open set filter
open_locale topological_space filter
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
variables [topological_space α]
@[simp] lemma nhds_bind_nhds_within {a : α} {s : set α} :
(𝓝 a).bind (λ x, 𝓝[s] x) = 𝓝[s] a :=
bind_inf_principal.trans $ congr_arg2 _ nhds_bind_nhds rfl
@[simp] lemma eventually_nhds_nhds_within {a : α} {s : set α} {p : α → Prop} :
(∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝[s] y, p x) ↔ ∀ᶠ x in 𝓝[s] a, p x :=
filter.ext_iff.1 nhds_bind_nhds_within {x | p x}
lemma eventually_nhds_within_iff {a : α} {s : set α} {p : α → Prop} :
(∀ᶠ x in 𝓝[s] a, p x) ↔ ∀ᶠ x in 𝓝 a, x ∈ s → p x :=
eventually_inf_principal
@[simp] lemma eventually_nhds_within_nhds_within {a : α} {s : set α} {p : α → Prop} :
(∀ᶠ y in 𝓝[s] a, ∀ᶠ x in 𝓝[s] y, p x) ↔ ∀ᶠ x in 𝓝[s] a, p x :=
begin
refine ⟨λ h, _, λ h, (eventually_nhds_nhds_within.2 h).filter_mono inf_le_left⟩,
simp only [eventually_nhds_within_iff] at h ⊢,
exact h.mono (λ x hx hxs, (hx hxs).self_of_nhds hxs)
end
theorem nhds_within_eq (a : α) (s : set α) :
𝓝[s] a = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, 𝓟 (t ∩ s) :=
((nhds_basis_opens a).inf_principal s).eq_binfi
theorem nhds_within_univ (a : α) : 𝓝[set.univ] a = 𝓝 a :=
by rw [nhds_within, principal_univ, inf_top_eq]
lemma nhds_within_has_basis {p : β → Prop} {s : β → set α} {a : α} (h : (𝓝 a).has_basis p s)
(t : set α) :
(𝓝[t] a).has_basis p (λ i, s i ∩ t) :=
h.inf_principal t
lemma nhds_within_basis_open (a : α) (t : set α) :
(𝓝[t] a).has_basis (λ u, a ∈ u ∧ is_open u) (λ u, u ∩ t) :=
nhds_within_has_basis (nhds_basis_opens a) t
theorem mem_nhds_within {t : set α} {a : α} {s : set α} :
t ∈ 𝓝[s] a ↔ ∃ u, is_open u ∧ a ∈ u ∧ u ∩ s ⊆ t :=
by simpa only [exists_prop, and_assoc, and_comm] using (nhds_within_basis_open a s).mem_iff
lemma mem_nhds_within_iff_exists_mem_nhds_inter {t : set α} {a : α} {s : set α} :
t ∈ 𝓝[s] a ↔ ∃ u ∈ 𝓝 a, u ∩ s ⊆ t :=
(nhds_within_has_basis (𝓝 a).basis_sets s).mem_iff
lemma diff_mem_nhds_within_compl {X : Type*} [topological_space X] {x : X} {s : set X}
(hs : s ∈ 𝓝 x) (t : set X) : s \ t ∈ 𝓝[tᶜ] x :=
diff_mem_inf_principal_compl hs t
lemma nhds_of_nhds_within_of_nhds
{s t : set α} {a : α} (h1 : s ∈ 𝓝 a) (h2 : t ∈ 𝓝[s] a) : (t ∈ 𝓝 a) :=
begin
rcases mem_nhds_within_iff_exists_mem_nhds_inter.mp h2 with ⟨_, Hw, hw⟩,
exact (nhds a).sets_of_superset ((nhds a).inter_sets Hw h1) hw,
end
lemma preimage_nhds_within_coinduced' {π : α → β} {s : set β} {t : set α} {a : α}
(h : a ∈ t) (ht : is_open t)
(hs : s ∈ @nhds β (topological_space.coinduced (λ x : t, π x) subtype.topological_space) (π a)) :
π ⁻¹' s ∈ 𝓝[t] a :=
begin
letI := topological_space.coinduced (λ x : t, π x) subtype.topological_space,
rcases mem_nhds_iff.mp hs with ⟨V, hVs, V_op, mem_V⟩,
refine mem_nhds_within_iff_exists_mem_nhds_inter.mpr ⟨π ⁻¹' V, mem_nhds_iff.mpr ⟨t ∩ π ⁻¹' V,
inter_subset_right t (π ⁻¹' V), _, mem_sep h mem_V⟩, subset.trans (inter_subset_left _ _)
(preimage_mono hVs)⟩,
obtain ⟨u, hu1, hu2⟩ := is_open_induced_iff.mp (is_open_coinduced.1 V_op),
rw [preimage_comp] at hu2,
rw [set.inter_comm, ←(subtype.preimage_coe_eq_preimage_coe_iff.mp hu2)],
exact hu1.inter ht,
end
lemma mem_nhds_within_of_mem_nhds {s t : set α} {a : α} (h : s ∈ 𝓝 a) :
s ∈ 𝓝[t] a :=
mem_inf_sets_of_left h
theorem self_mem_nhds_within {a : α} {s : set α} : s ∈ 𝓝[s] a :=
mem_inf_sets_of_right (mem_principal_self s)
theorem inter_mem_nhds_within (s : set α) {t : set α} {a : α} (h : t ∈ 𝓝 a) :
s ∩ t ∈ 𝓝[s] a :=
inter_mem_sets self_mem_nhds_within (mem_inf_sets_of_left h)
theorem nhds_within_mono (a : α) {s t : set α} (h : s ⊆ t) : 𝓝[s] a ≤ 𝓝[t] a :=
inf_le_inf_left _ (principal_mono.mpr h)
lemma pure_le_nhds_within {a : α} {s : set α} (ha : a ∈ s) : pure a ≤ 𝓝[s] a :=
le_inf (pure_le_nhds a) (le_principal_iff.2 ha)
lemma mem_of_mem_nhds_within {a : α} {s t : set α} (ha : a ∈ s) (ht : t ∈ 𝓝[s] a) :
a ∈ t :=
pure_le_nhds_within ha ht
lemma filter.eventually.self_of_nhds_within {p : α → Prop} {s : set α} {x : α}
(h : ∀ᶠ y in 𝓝[s] x, p y) (hx : x ∈ s) : p x :=
mem_of_mem_nhds_within hx h
lemma tendsto_const_nhds_within {l : filter β} {s : set α} {a : α} (ha : a ∈ s) :
tendsto (λ x : β, a) l (𝓝[s] a) :=
tendsto_const_pure.mono_right $ pure_le_nhds_within ha
theorem nhds_within_restrict'' {a : α} (s : set α) {t : set α} (h : t ∈ 𝓝[s] a) :
𝓝[s] a = 𝓝[s ∩ t] a :=
le_antisymm
(le_inf inf_le_left (le_principal_iff.mpr (inter_mem_sets self_mem_nhds_within h)))
(inf_le_inf_left _ (principal_mono.mpr (set.inter_subset_left _ _)))
theorem nhds_within_restrict' {a : α} (s : set α) {t : set α} (h : t ∈ 𝓝 a) :
𝓝[s] a = 𝓝[s ∩ t] a :=
nhds_within_restrict'' s $ mem_inf_sets_of_left h
theorem nhds_within_restrict {a : α} (s : set α) {t : set α} (h₀ : a ∈ t) (h₁ : is_open t) :
𝓝[s] a = 𝓝[s ∩ t] a :=
nhds_within_restrict' s (is_open.mem_nhds h₁ h₀)
theorem nhds_within_le_of_mem {a : α} {s t : set α} (h : s ∈ 𝓝[t] a) :
𝓝[t] a ≤ 𝓝[s] a :=
begin
rcases mem_nhds_within.1 h with ⟨u, u_open, au, uts⟩,
have : 𝓝[t] a = 𝓝[t ∩ u] a := nhds_within_restrict _ au u_open,
rw [this, inter_comm],
exact nhds_within_mono _ uts
end
theorem nhds_within_le_nhds {a : α} {s : set α} : 𝓝[s] a ≤ 𝓝 a :=
by { rw ← nhds_within_univ, apply nhds_within_le_of_mem, exact univ_mem_sets }
theorem nhds_within_eq_nhds_within {a : α} {s t u : set α}
(h₀ : a ∈ s) (h₁ : is_open s) (h₂ : t ∩ s = u ∩ s) :
𝓝[t] a = 𝓝[u] a :=
by rw [nhds_within_restrict t h₀ h₁, nhds_within_restrict u h₀ h₁, h₂]
theorem nhds_within_eq_of_open {a : α} {s : set α} (h₀ : a ∈ s) (h₁ : is_open s) :
𝓝[s] a = 𝓝 a :=
inf_eq_left.2 $ le_principal_iff.2 $ is_open.mem_nhds h₁ h₀
lemma preimage_nhds_within_coinduced {π : α → β} {s : set β} {t : set α} {a : α}
(h : a ∈ t) (ht : is_open t)
(hs : s ∈ @nhds β (topological_space.coinduced (λ x : t, π x) subtype.topological_space) (π a)) :
π ⁻¹' s ∈ 𝓝 a :=
by { rw ←nhds_within_eq_of_open h ht, exact preimage_nhds_within_coinduced' h ht hs }
@[simp] theorem nhds_within_empty (a : α) : 𝓝[∅] a = ⊥ :=
by rw [nhds_within, principal_empty, inf_bot_eq]
theorem nhds_within_union (a : α) (s t : set α) :
𝓝[s ∪ t] a = 𝓝[s] a ⊔ 𝓝[t] a :=
by { delta nhds_within, rw [←inf_sup_left, sup_principal] }
theorem nhds_within_inter (a : α) (s t : set α) :
𝓝[s ∩ t] a = 𝓝[s] a ⊓ 𝓝[t] a :=
by { delta nhds_within, rw [inf_left_comm, inf_assoc, inf_principal, ←inf_assoc, inf_idem] }
theorem nhds_within_inter' (a : α) (s t : set α) :
𝓝[s ∩ t] a = (𝓝[s] a) ⊓ 𝓟 t :=
by { delta nhds_within, rw [←inf_principal, inf_assoc] }
theorem nhds_within_inter_of_mem {a : α} {s t : set α} (h : s ∈ 𝓝[t] a) :
𝓝[s ∩ t] a = 𝓝[t] a :=
by { rw [nhds_within_inter, inf_eq_right], exact nhds_within_le_of_mem h }
@[simp] theorem nhds_within_singleton (a : α) : 𝓝[{a}] a = pure a :=
by rw [nhds_within, principal_singleton, inf_eq_right.2 (pure_le_nhds a)]
@[simp] theorem nhds_within_insert (a : α) (s : set α) :
𝓝[insert a s] a = pure a ⊔ 𝓝[s] a :=
by rw [← singleton_union, nhds_within_union, nhds_within_singleton]
lemma mem_nhds_within_insert {a : α} {s t : set α} :
t ∈ 𝓝[insert a s] a ↔ a ∈ t ∧ t ∈ 𝓝[s] a :=
by simp
lemma insert_mem_nhds_within_insert {a : α} {s t : set α} (h : t ∈ 𝓝[s] a) :
insert a t ∈ 𝓝[insert a s] a :=
by simp [mem_sets_of_superset h]
lemma nhds_within_prod_eq {α : Type*} [topological_space α] {β : Type*} [topological_space β]
(a : α) (b : β) (s : set α) (t : set β) :
𝓝[s.prod t] (a, b) = 𝓝[s] a ×ᶠ 𝓝[t] b :=
by { delta nhds_within, rw [nhds_prod_eq, ←filter.prod_inf_prod, filter.prod_principal_principal] }
lemma nhds_within_prod {α : Type*} [topological_space α] {β : Type*} [topological_space β]
{s u : set α} {t v : set β} {a : α} {b : β}
(hu : u ∈ 𝓝[s] a) (hv : v ∈ 𝓝[t] b) :
(u.prod v) ∈ 𝓝[s.prod t] (a, b) :=
by { rw nhds_within_prod_eq, exact prod_mem_prod hu hv, }
lemma nhds_within_pi_eq' {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)]
{I : set ι} (hI : finite I) (s : Π i, set (α i)) (x : Π i, α i) :
𝓝[pi I s] x = ⨅ i, comap (λ x, x i) (𝓝 (x i) ⊓ ⨅ (hi : i ∈ I), 𝓟 (s i)) :=
by simp only [nhds_within, nhds_pi, comap_inf, comap_infi, pi_def, comap_principal,
← infi_principal_finite hI, ← infi_inf_eq]
lemma nhds_within_pi_eq {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)]
{I : set ι} (hI : finite I) (s : Π i, set (α i)) (x : Π i, α i) :
𝓝[pi I s] x = (⨅ i ∈ I, comap (λ x, x i) (𝓝[s i] (x i))) ⊓
⨅ (i ∉ I), comap (λ x, x i) (𝓝 (x i)) :=
begin
simp only [nhds_within, nhds_pi, pi_def, ← infi_principal_finite hI, comap_inf, comap_principal,
function.eval],
rw [infi_split _ (λ i, i ∈ I), inf_right_comm],
simp only [infi_inf_eq]
end
lemma nhds_within_pi_univ_eq {ι : Type*} {α : ι → Type*} [fintype ι] [Π i, topological_space (α i)]
(s : Π i, set (α i)) (x : Π i, α i) :
𝓝[pi univ s] x = ⨅ i, comap (λ x, x i) 𝓝[s i] (x i) :=
by simpa [nhds_within] using nhds_within_pi_eq finite_univ s x
lemma nhds_within_pi_univ_eq_bot {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)]
{s : Π i, set (α i)} {x : Π i, α i} :
𝓝[pi univ s] x = ⊥ ↔ ∃ i, 𝓝[s i] (x i) = ⊥ :=
begin
classical,
split,
{ haveI : Π i, inhabited (α i) := λ i, ⟨x i⟩,
simp only [nhds_within, nhds_pi, inf_principal_eq_bot, mem_infi_iff', mem_comap_sets],
rintro ⟨I, hIf, V, hV, hVs⟩, choose! t htx htV using hV,
contrapose! hVs,
change ∀ i, ∃ᶠ y in 𝓝 (x i), y ∈ s i at hVs,
have : ∀ i ∈ I, (s i ∩ t i).nonempty, from λ i hi, ((hVs i).and_eventually (htx i hi)).exists,
choose! y hys hyt,
choose z hzs using λ i, (hVs i).exists,
suffices : I.piecewise y z ∈ (⋂ i ∈ I, V i) ∩ (pi univ s),
from λ H, H this.1 this.2,
refine ⟨mem_bInter $ λ i hi, htV i hi _, λ i hi', _⟩,
{ simp only [mem_preimage, piecewise_eq_of_mem _ _ _ hi, hyt i hi] },
{ by_cases hi : i ∈ I; simp * } },
{ rintro ⟨i, eq⟩,
rw [← @map_eq_bot_iff _ _ _ (λ x : Π i, α i, x i)],
refine eq_bot_mono _ eq,
exact ((continuous_apply i).tendsto x).inf
(tendsto_principal_principal.2 $ λ y hy, hy i trivial) }
end
lemma nhds_within_pi_eq_bot {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)]
{I : set ι} {s : Π i, set (α i)} {x : Π i, α i} :
𝓝[pi I s] x = ⊥ ↔ ∃ i ∈ I, 𝓝[s i] (x i) = ⊥ :=
begin
classical,
rw [← univ_pi_piecewise I, nhds_within_pi_univ_eq_bot],
refine exists_congr (λ i, _),
by_cases hi : i ∈ I; simp [*, nhds_within_univ, nhds_ne_bot.ne]
end
lemma nhds_within_pi_ne_bot {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)]
{I : set ι} {s : Π i, set (α i)} {x : Π i, α i} :
(𝓝[pi I s] x).ne_bot ↔ ∀ i ∈ I, (𝓝[s i] (x i)).ne_bot :=
by simp [ne_bot_iff, nhds_within_pi_eq_bot]
theorem filter.tendsto.piecewise_nhds_within {f g : α → β} {t : set α} [∀ x, decidable (x ∈ t)]
{a : α} {s : set α} {l : filter β}
(h₀ : tendsto f (𝓝[s ∩ t] a) l) (h₁ : tendsto g (𝓝[s ∩ tᶜ] a) l) :
tendsto (piecewise t f g) (𝓝[s] a) l :=
by apply tendsto.piecewise; rwa ← nhds_within_inter'
theorem filter.tendsto.if_nhds_within {f g : α → β} {p : α → Prop} [decidable_pred p]
{a : α} {s : set α} {l : filter β}
(h₀ : tendsto f (𝓝[s ∩ {x | p x}] a) l)
(h₁ : tendsto g (𝓝[s ∩ {x | ¬ p x}] a) l) :
tendsto (λ x, if p x then f x else g x) (𝓝[s] a) l :=
h₀.piecewise_nhds_within h₁
lemma map_nhds_within (f : α → β) (a : α) (s : set α) :
map f (𝓝[s] a) = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, 𝓟 (f '' (t ∩ s)) :=
((nhds_within_basis_open a s).map f).eq_binfi
theorem tendsto_nhds_within_mono_left {f : α → β} {a : α}
{s t : set α} {l : filter β} (hst : s ⊆ t) (h : tendsto f (𝓝[t] a) l) :
tendsto f (𝓝[s] a) l :=
h.mono_left $ nhds_within_mono a hst
theorem tendsto_nhds_within_mono_right {f : β → α} {l : filter β}
{a : α} {s t : set α} (hst : s ⊆ t) (h : tendsto f l (𝓝[s] a)) :
tendsto f l (𝓝[t] a) :=
h.mono_right (nhds_within_mono a hst)
theorem tendsto_nhds_within_of_tendsto_nhds {f : α → β} {a : α}
{s : set α} {l : filter β} (h : tendsto f (𝓝 a) l) :
tendsto f (𝓝[s] a) l :=
h.mono_left inf_le_left
theorem principal_subtype {α : Type*} (s : set α) (t : set {x // x ∈ s}) :
𝓟 t = comap coe (𝓟 ((coe : s → α) '' t)) :=
by rw [comap_principal, set.preimage_image_eq _ subtype.coe_injective]
lemma mem_closure_iff_nhds_within_ne_bot {s : set α} {x : α} :
x ∈ closure s ↔ ne_bot (𝓝[s] x) :=
mem_closure_iff_cluster_pt
lemma nhds_within_ne_bot_of_mem {s : set α} {x : α} (hx : x ∈ s) :
ne_bot (𝓝[s] x) :=
mem_closure_iff_nhds_within_ne_bot.1 $ subset_closure hx
lemma is_closed.mem_of_nhds_within_ne_bot {s : set α} (hs : is_closed s)
{x : α} (hx : ne_bot $ 𝓝[s] x) : x ∈ s :=
by simpa only [hs.closure_eq] using mem_closure_iff_nhds_within_ne_bot.2 hx
lemma dense_range.nhds_within_ne_bot {ι : Type*} {f : ι → α} (h : dense_range f) (x : α) :
ne_bot (𝓝[range f] x) :=
mem_closure_iff_cluster_pt.1 (h x)
lemma mem_closure_pi {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)]
{I : set ι} {s : Π i, set (α i)} {x : Π i, α i} :
x ∈ closure (pi I s) ↔ ∀ i ∈ I, x i ∈ closure (s i) :=
by simp only [mem_closure_iff_nhds_within_ne_bot, nhds_within_pi_ne_bot]
lemma closure_pi_set {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)]
(I : set ι) (s : Π i, set (α i)) :
closure (pi I s) = pi I (λ i, closure (s i)) :=
set.ext $ λ x, mem_closure_pi
lemma dense_pi {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {s : Π i, set (α i)}
(I : set ι) (hs : ∀ i ∈ I, dense (s i)) :
dense (pi I s) :=
by simp only [dense_iff_closure_eq, closure_pi_set,
pi_congr rfl (λ i hi, (hs i hi).closure_eq), pi_univ]
lemma eventually_eq_nhds_within_iff {f g : α → β} {s : set α} {a : α} :
(f =ᶠ[𝓝[s] a] g) ↔ ∀ᶠ x in 𝓝 a, x ∈ s → f x = g x :=
mem_inf_principal
lemma eventually_eq_nhds_within_of_eq_on {f g : α → β} {s : set α} {a : α} (h : eq_on f g s) :
f =ᶠ[𝓝[s] a] g :=
mem_inf_sets_of_right h
lemma set.eq_on.eventually_eq_nhds_within {f g : α → β} {s : set α} {a : α} (h : eq_on f g s) :
f =ᶠ[𝓝[s] a] g :=
eventually_eq_nhds_within_of_eq_on h
lemma tendsto_nhds_within_congr {f g : α → β} {s : set α} {a : α} {l : filter β}
(hfg : ∀ x ∈ s, f x = g x) (hf : tendsto f (𝓝[s] a) l) : tendsto g (𝓝[s] a) l :=
(tendsto_congr' $ eventually_eq_nhds_within_of_eq_on hfg).1 hf
lemma eventually_nhds_with_of_forall {s : set α} {a : α} {p : α → Prop} (h : ∀ x ∈ s, p x) :
∀ᶠ x in 𝓝[s] a, p x :=
mem_inf_sets_of_right h
lemma tendsto_nhds_within_of_tendsto_nhds_of_eventually_within {a : α} {l : filter β}
{s : set α} (f : β → α) (h1 : tendsto f l (𝓝 a)) (h2 : ∀ᶠ x in l, f x ∈ s) :
tendsto f l (𝓝[s] a) :=
tendsto_inf.2 ⟨h1, tendsto_principal.2 h2⟩
@[simp] lemma tendsto_nhds_within_range {a : α} {l : filter β} {f : β → α} :
tendsto f l (𝓝[range f] a) ↔ tendsto f l (𝓝 a) :=
⟨λ h, h.mono_right inf_le_left, λ h, tendsto_inf.2
⟨h, tendsto_principal.2 $ eventually_of_forall mem_range_self⟩⟩
lemma filter.eventually_eq.eq_of_nhds_within {s : set α} {f g : α → β} {a : α}
(h : f =ᶠ[𝓝[s] a] g) (hmem : a ∈ s) : f a = g a :=
h.self_of_nhds_within hmem
lemma eventually_nhds_within_of_eventually_nhds {α : Type*} [topological_space α]
{s : set α} {a : α} {p : α → Prop} (h : ∀ᶠ x in 𝓝 a, p x) :
∀ᶠ x in 𝓝[s] a, p x :=
mem_nhds_within_of_mem_nhds h
/-!
### `nhds_within` and subtypes
-/
theorem mem_nhds_within_subtype {s : set α} {a : {x // x ∈ s}} {t u : set {x // x ∈ s}} :
t ∈ 𝓝[u] a ↔ t ∈ comap (coe : s → α) (𝓝[coe '' u] a) :=
by rw [nhds_within, nhds_subtype, principal_subtype, ←comap_inf, ←nhds_within]
theorem nhds_within_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) :
𝓝[t] a = comap (coe : s → α) (𝓝[coe '' t] a) :=
filter.ext $ λ u, mem_nhds_within_subtype
theorem nhds_within_eq_map_subtype_coe {s : set α} {a : α} (h : a ∈ s) :
𝓝[s] a = map (coe : s → α) (𝓝 ⟨a, h⟩) :=
by simpa only [subtype.range_coe] using (embedding_subtype_coe.map_nhds_eq ⟨a, h⟩).symm
theorem tendsto_nhds_within_iff_subtype {s : set α} {a : α} (h : a ∈ s) (f : α → β) (l : filter β) :
tendsto f (𝓝[s] a) l ↔ tendsto (s.restrict f) (𝓝 ⟨a, h⟩) l :=
by simp only [tendsto, nhds_within_eq_map_subtype_coe h, filter.map_map, restrict]
variables [topological_space β] [topological_space γ] [topological_space δ]
/-- A function between topological spaces is continuous at a point `x₀` within a subset `s`
if `f x` tends to `f x₀` when `x` tends to `x₀` while staying within `s`. -/
def continuous_within_at (f : α → β) (s : set α) (x : α) : Prop :=
tendsto f (𝓝[s] x) (𝓝 (f x))
/-- If a function is continuous within `s` at `x`, then it tends to `f x` within `s` by definition.
We register this fact for use with the dot notation, especially to use `tendsto.comp` as
`continuous_within_at.comp` will have a different meaning. -/
lemma continuous_within_at.tendsto {f : α → β} {s : set α} {x : α}
(h : continuous_within_at f s x) :
tendsto f (𝓝[s] x) (𝓝 (f x)) := h
/-- A function between topological spaces is continuous on a subset `s`
when it's continuous at every point of `s` within `s`. -/
def continuous_on (f : α → β) (s : set α) : Prop := ∀ x ∈ s, continuous_within_at f s x
lemma continuous_on.continuous_within_at {f : α → β} {s : set α} {x : α} (hf : continuous_on f s)
(hx : x ∈ s) : continuous_within_at f s x :=
hf x hx
theorem continuous_within_at_univ (f : α → β) (x : α) :
continuous_within_at f set.univ x ↔ continuous_at f x :=
by rw [continuous_at, continuous_within_at, nhds_within_univ]
theorem continuous_within_at_iff_continuous_at_restrict (f : α → β) {x : α} {s : set α}
(h : x ∈ s) :
continuous_within_at f s x ↔ continuous_at (s.restrict f) ⟨x, h⟩ :=
tendsto_nhds_within_iff_subtype h f _
theorem continuous_within_at.tendsto_nhds_within {f : α → β} {x : α} {s : set α} {t : set β}
(h : continuous_within_at f s x) (ht : maps_to f s t) :
tendsto f (𝓝[s] x) (𝓝[t] (f x)) :=
tendsto_inf.2 ⟨h, tendsto_principal.2 $ mem_inf_sets_of_right $ mem_principal_sets.2 $ ht⟩
theorem continuous_within_at.tendsto_nhds_within_image {f : α → β} {x : α} {s : set α}
(h : continuous_within_at f s x) :
tendsto f (𝓝[s] x) (𝓝[f '' s] (f x)) :=
h.tendsto_nhds_within (maps_to_image _ _)
lemma continuous_within_at.prod_map {f : α → γ} {g : β → δ} {s : set α} {t : set β}
{x : α} {y : β}
(hf : continuous_within_at f s x) (hg : continuous_within_at g t y) :
continuous_within_at (prod.map f g) (s.prod t) (x, y) :=
begin
unfold continuous_within_at at *,
rw [nhds_within_prod_eq, prod.map, nhds_prod_eq],
exact hf.prod_map hg,
end
lemma continuous_within_at_pi {ι : Type*} {π : ι → Type*} [∀ i, topological_space (π i)]
{f : α → Π i, π i} {s : set α} {x : α} :
continuous_within_at f s x ↔ ∀ i, continuous_within_at (λ y, f y i) s x :=
tendsto_pi
lemma continuous_on_pi {ι : Type*} {π : ι → Type*} [∀ i, topological_space (π i)]
{f : α → Π i, π i} {s : set α} :
continuous_on f s ↔ ∀ i, continuous_on (λ y, f y i) s :=
⟨λ h i x hx, tendsto_pi.1 (h x hx) i, λ h x hx, tendsto_pi.2 (λ i, h i x hx)⟩
theorem continuous_on_iff {f : α → β} {s : set α} :
continuous_on f s ↔ ∀ x ∈ s, ∀ t : set β, is_open t → f x ∈ t → ∃ u, is_open u ∧ x ∈ u ∧
u ∩ s ⊆ f ⁻¹' t :=
by simp only [continuous_on, continuous_within_at, tendsto_nhds, mem_nhds_within]
theorem continuous_on_iff_continuous_restrict {f : α → β} {s : set α} :
continuous_on f s ↔ continuous (s.restrict f) :=
begin
rw [continuous_on, continuous_iff_continuous_at], split,
{ rintros h ⟨x, xs⟩,
exact (continuous_within_at_iff_continuous_at_restrict f xs).mp (h x xs) },
intros h x xs,
exact (continuous_within_at_iff_continuous_at_restrict f xs).mpr (h ⟨x, xs⟩)
end
theorem continuous_on_iff' {f : α → β} {s : set α} :
continuous_on f s ↔ ∀ t : set β, is_open t → ∃ u, is_open u ∧ f ⁻¹' t ∩ s = u ∩ s :=
have ∀ t, is_open (s.restrict f ⁻¹' t) ↔ ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s,
begin
intro t,
rw [is_open_induced_iff, set.restrict_eq, set.preimage_comp],
simp only [subtype.preimage_coe_eq_preimage_coe_iff],
split; { rintros ⟨u, ou, useq⟩, exact ⟨u, ou, useq.symm⟩ }
end,
by rw [continuous_on_iff_continuous_restrict, continuous_def]; simp only [this]
theorem continuous_on_iff_is_closed {f : α → β} {s : set α} :
continuous_on f s ↔ ∀ t : set β, is_closed t → ∃ u, is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s :=
have ∀ t, is_closed (s.restrict f ⁻¹' t) ↔ ∃ (u : set α), is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s,
begin
intro t,
rw [is_closed_induced_iff, set.restrict_eq, set.preimage_comp],
simp only [subtype.preimage_coe_eq_preimage_coe_iff, eq_comm]
end,
by rw [continuous_on_iff_continuous_restrict, continuous_iff_is_closed]; simp only [this]
lemma continuous_on.prod_map {f : α → γ} {g : β → δ} {s : set α} {t : set β}
(hf : continuous_on f s) (hg : continuous_on g t) :
continuous_on (prod.map f g) (s.prod t) :=
λ ⟨x, y⟩ ⟨hx, hy⟩, continuous_within_at.prod_map (hf x hx) (hg y hy)
lemma continuous_on_empty (f : α → β) : continuous_on f ∅ :=
λ x, false.elim
theorem nhds_within_le_comap {x : α} {s : set α} {f : α → β} (ctsf : continuous_within_at f s x) :
𝓝[s] x ≤ comap f (𝓝[f '' s] (f x)) :=
map_le_iff_le_comap.1 ctsf.tendsto_nhds_within_image
theorem continuous_within_at_iff_ptendsto_res (f : α → β) {x : α} {s : set α} :
continuous_within_at f s x ↔ ptendsto (pfun.res f s) (𝓝 x) (𝓝 (f x)) :=
tendsto_iff_ptendsto _ _ _ _
lemma continuous_iff_continuous_on_univ {f : α → β} : continuous f ↔ continuous_on f univ :=
by simp [continuous_iff_continuous_at, continuous_on, continuous_at, continuous_within_at,
nhds_within_univ]
lemma continuous_within_at.mono {f : α → β} {s t : set α} {x : α} (h : continuous_within_at f t x)
(hs : s ⊆ t) : continuous_within_at f s x :=
h.mono_left (nhds_within_mono x hs)
lemma continuous_within_at.mono_of_mem {f : α → β} {s t : set α} {x : α}
(h : continuous_within_at f t x) (hs : t ∈ 𝓝[s] x) : continuous_within_at f s x :=
h.mono_left (nhds_within_le_of_mem hs)
lemma continuous_within_at_inter' {f : α → β} {s t : set α} {x : α} (h : t ∈ 𝓝[s] x) :
continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x :=
by simp [continuous_within_at, nhds_within_restrict'' s h]
lemma continuous_within_at_inter {f : α → β} {s t : set α} {x : α} (h : t ∈ 𝓝 x) :
continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x :=
by simp [continuous_within_at, nhds_within_restrict' s h]
lemma continuous_within_at_union {f : α → β} {s t : set α} {x : α} :
continuous_within_at f (s ∪ t) x ↔ continuous_within_at f s x ∧ continuous_within_at f t x :=
by simp only [continuous_within_at, nhds_within_union, tendsto_sup]
lemma continuous_within_at.union {f : α → β} {s t : set α} {x : α}
(hs : continuous_within_at f s x) (ht : continuous_within_at f t x) :
continuous_within_at f (s ∪ t) x :=
continuous_within_at_union.2 ⟨hs, ht⟩
lemma continuous_within_at.mem_closure_image {f : α → β} {s : set α} {x : α}
(h : continuous_within_at f s x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) :=
by haveI := (mem_closure_iff_nhds_within_ne_bot.1 hx);
exact (mem_closure_of_tendsto h $
mem_sets_of_superset self_mem_nhds_within (subset_preimage_image f s))
lemma continuous_within_at.mem_closure {f : α → β} {s : set α} {x : α} {A : set β}
(h : continuous_within_at f s x) (hx : x ∈ closure s) (hA : s ⊆ f⁻¹' A) : f x ∈ closure A :=
closure_mono (image_subset_iff.2 hA) (h.mem_closure_image hx)
lemma continuous_within_at.image_closure {f : α → β} {s : set α}
(hf : ∀ x ∈ closure s, continuous_within_at f s x) :
f '' (closure s) ⊆ closure (f '' s) :=
begin
rintros _ ⟨x, hx, rfl⟩,
exact (hf x hx).mem_closure_image hx
end
lemma continuous_on.image_closure {f : α → β} {s : set α} (hf : continuous_on f (closure s)) :
f '' (closure s) ⊆ closure (f '' s) :=
continuous_within_at.image_closure $ λ x hx, (hf x hx).mono subset_closure
@[simp] lemma continuous_within_at_singleton {f : α → β} {x : α} : continuous_within_at f {x} x :=
by simp only [continuous_within_at, nhds_within_singleton, tendsto_pure_nhds]
@[simp] lemma continuous_within_at_insert_self {f : α → β} {x : α} {s : set α} :
continuous_within_at f (insert x s) x ↔ continuous_within_at f s x :=
by simp only [← singleton_union, continuous_within_at_union, continuous_within_at_singleton,
true_and]
alias continuous_within_at_insert_self ↔ _ continuous_within_at.insert_self
lemma continuous_within_at.diff_iff {f : α → β} {s t : set α} {x : α}
(ht : continuous_within_at f t x) :
continuous_within_at f (s \ t) x ↔ continuous_within_at f s x :=
⟨λ h, (h.union ht).mono $ by simp only [diff_union_self, subset_union_left],
λ h, h.mono (diff_subset _ _)⟩
@[simp] lemma continuous_within_at_diff_self {f : α → β} {s : set α} {x : α} :
continuous_within_at f (s \ {x}) x ↔ continuous_within_at f s x :=
continuous_within_at_singleton.diff_iff
theorem is_open_map.continuous_on_image_of_left_inv_on {f : α → β} {s : set α}
(h : is_open_map (s.restrict f)) {finv : β → α} (hleft : left_inv_on finv f s) :
continuous_on finv (f '' s) :=
begin
refine continuous_on_iff'.2 (λ t ht, ⟨f '' (t ∩ s), _, _⟩),
{ rw ← image_restrict, exact h _ (ht.preimage continuous_subtype_coe) },
{ rw [inter_eq_self_of_subset_left (image_subset f (inter_subset_right t s)),
hleft.image_inter'] },
end
theorem is_open_map.continuous_on_range_of_left_inverse {f : α → β} (hf : is_open_map f)
{finv : β → α} (hleft : function.left_inverse finv f) :
continuous_on finv (range f) :=
begin
rw [← image_univ],
exact (hf.restrict is_open_univ).continuous_on_image_of_left_inv_on (λ x _, hleft x)
end
lemma continuous_on.congr_mono {f g : α → β} {s s₁ : set α} (h : continuous_on f s)
(h' : eq_on g f s₁) (h₁ : s₁ ⊆ s) : continuous_on g s₁ :=
begin
assume x hx,
unfold continuous_within_at,
have A := (h x (h₁ hx)).mono h₁,
unfold continuous_within_at at A,
rw ← h' hx at A,
exact A.congr' h'.eventually_eq_nhds_within.symm
end
lemma continuous_on.congr {f g : α → β} {s : set α} (h : continuous_on f s) (h' : eq_on g f s) :
continuous_on g s :=
h.congr_mono h' (subset.refl _)
lemma continuous_on_congr {f g : α → β} {s : set α} (h' : eq_on g f s) :
continuous_on g s ↔ continuous_on f s :=
⟨λ h, continuous_on.congr h h'.symm, λ h, h.congr h'⟩
lemma continuous_at.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous_at f x) :
continuous_within_at f s x :=
continuous_within_at.mono ((continuous_within_at_univ f x).2 h) (subset_univ _)
lemma continuous_within_at.continuous_at {f : α → β} {s : set α} {x : α}
(h : continuous_within_at f s x) (hs : s ∈ 𝓝 x) : continuous_at f x :=
begin
have : s = univ ∩ s, by rw univ_inter,
rwa [this, continuous_within_at_inter hs, continuous_within_at_univ] at h
end
lemma continuous_on.continuous_at {f : α → β} {s : set α} {x : α}
(h : continuous_on f s) (hx : s ∈ 𝓝 x) : continuous_at f x :=
(h x (mem_of_mem_nhds hx)).continuous_at hx
lemma continuous_at.continuous_on {f : α → β} {s : set α} (hcont : ∀ x ∈ s, continuous_at f x) :
continuous_on f s :=
λ x hx, (hcont x hx).continuous_within_at
lemma continuous_within_at.comp {g : β → γ} {f : α → β} {s : set α} {t : set β} {x : α}
(hg : continuous_within_at g t (f x)) (hf : continuous_within_at f s x) (h : s ⊆ f ⁻¹' t) :
continuous_within_at (g ∘ f) s x :=
hg.tendsto.comp (hf.tendsto_nhds_within h)
lemma continuous_within_at.comp' {g : β → γ} {f : α → β} {s : set α} {t : set β} {x : α}
(hg : continuous_within_at g t (f x)) (hf : continuous_within_at f s x) :
continuous_within_at (g ∘ f) (s ∩ f⁻¹' t) x :=
hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _)
lemma continuous_at.comp_continuous_within_at {g : β → γ} {f : α → β} {s : set α} {x : α}
(hg : continuous_at g (f x)) (hf : continuous_within_at f s x) :
continuous_within_at (g ∘ f) s x :=
hg.continuous_within_at.comp hf subset_preimage_univ
lemma continuous_on.comp {g : β → γ} {f : α → β} {s : set α} {t : set β}
(hg : continuous_on g t) (hf : continuous_on f s) (h : s ⊆ f ⁻¹' t) :
continuous_on (g ∘ f) s :=
λx hx, continuous_within_at.comp (hg _ (h hx)) (hf x hx) h
lemma continuous_on.mono {f : α → β} {s t : set α} (hf : continuous_on f s) (h : t ⊆ s) :
continuous_on f t :=
λx hx, (hf x (h hx)).mono_left (nhds_within_mono _ h)
lemma continuous_on.comp' {g : β → γ} {f : α → β} {s : set α} {t : set β}
(hg : continuous_on g t) (hf : continuous_on f s) :
continuous_on (g ∘ f) (s ∩ f⁻¹' t) :=
hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _)
lemma continuous.continuous_on {f : α → β} {s : set α} (h : continuous f) :
continuous_on f s :=
begin
rw continuous_iff_continuous_on_univ at h,
exact h.mono (subset_univ _)
end
lemma continuous.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous f) :
continuous_within_at f s x :=
h.continuous_at.continuous_within_at
lemma continuous.comp_continuous_on {g : β → γ} {f : α → β} {s : set α}
(hg : continuous g) (hf : continuous_on f s) :
continuous_on (g ∘ f) s :=
hg.continuous_on.comp hf subset_preimage_univ
lemma continuous_on.comp_continuous {g : β → γ} {f : α → β} {s : set β}
(hg : continuous_on g s) (hf : continuous f) (hs : ∀ x, f x ∈ s) : continuous (g ∘ f) :=
begin
rw continuous_iff_continuous_on_univ at *,
exact hg.comp hf (λ x _, hs x),
end
lemma continuous_within_at.preimage_mem_nhds_within {f : α → β} {x : α} {s : set α} {t : set β}
(h : continuous_within_at f s x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝[s] x :=
h ht
lemma set.left_inv_on.map_nhds_within_eq {f : α → β} {g : β → α} {x : β} {s : set β}
(h : left_inv_on f g s) (hx : f (g x) = x) (hf : continuous_within_at f (g '' s) (g x))
(hg : continuous_within_at g s x) :
map g (𝓝[s] x) = 𝓝[g '' s] (g x) :=
begin
apply le_antisymm,
{ exact hg.tendsto_nhds_within (maps_to_image _ _) },
{ have A : g ∘ f =ᶠ[𝓝[g '' s] (g x)] id,
from h.right_inv_on_image.eq_on.eventually_eq_of_mem self_mem_nhds_within,
refine le_map_of_right_inverse A _,
simpa only [hx] using hf.tendsto_nhds_within (h.maps_to (surj_on_image _ _)) }
end
lemma function.left_inverse.map_nhds_eq {f : α → β} {g : β → α} {x : β}
(h : function.left_inverse f g) (hf : continuous_within_at f (range g) (g x))
(hg : continuous_at g x) :
map g (𝓝 x) = 𝓝[range g] (g x) :=
by simpa only [nhds_within_univ, image_univ]
using (h.left_inv_on univ).map_nhds_within_eq (h x) (by rwa image_univ) hg.continuous_within_at
lemma continuous_within_at.preimage_mem_nhds_within' {f : α → β} {x : α} {s : set α} {t : set β}
(h : continuous_within_at f s x) (ht : t ∈ 𝓝[f '' s] (f x)) :
f ⁻¹' t ∈ 𝓝[s] x :=
h.tendsto_nhds_within (maps_to_image _ _) ht
lemma continuous_within_at.congr_of_eventually_eq {f f₁ : α → β} {s : set α} {x : α}
(h : continuous_within_at f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) :
continuous_within_at f₁ s x :=
by rwa [continuous_within_at, filter.tendsto, hx, filter.map_congr h₁]
lemma continuous_within_at.congr {f f₁ : α → β} {s : set α} {x : α}
(h : continuous_within_at f s x) (h₁ : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) :
continuous_within_at f₁ s x :=
h.congr_of_eventually_eq (mem_sets_of_superset self_mem_nhds_within h₁) hx
lemma continuous_within_at.congr_mono {f g : α → β} {s s₁ : set α} {x : α}
(h : continuous_within_at f s x) (h' : eq_on g f s₁) (h₁ : s₁ ⊆ s) (hx : g x = f x):
continuous_within_at g s₁ x :=
(h.mono h₁).congr h' hx
lemma continuous_on_const {s : set α} {c : β} : continuous_on (λx, c) s :=
continuous_const.continuous_on
lemma continuous_within_at_const {b : β} {s : set α} {x : α} :
continuous_within_at (λ _:α, b) s x :=
continuous_const.continuous_within_at
lemma continuous_on_id {s : set α} : continuous_on id s :=
continuous_id.continuous_on
lemma continuous_within_at_id {s : set α} {x : α} : continuous_within_at id s x :=
continuous_id.continuous_within_at
lemma continuous_on_open_iff {f : α → β} {s : set α} (hs : is_open s) :
continuous_on f s ↔ (∀t, is_open t → is_open (s ∩ f⁻¹' t)) :=
begin
rw continuous_on_iff',
split,
{ assume h t ht,
rcases h t ht with ⟨u, u_open, hu⟩,
rw [inter_comm, hu],
apply is_open.inter u_open hs },
{ assume h t ht,
refine ⟨s ∩ f ⁻¹' t, h t ht, _⟩,
rw [@inter_comm _ s (f ⁻¹' t), inter_assoc, inter_self] }
end
lemma continuous_on.preimage_open_of_open {f : α → β} {s : set α} {t : set β}
(hf : continuous_on f s) (hs : is_open s) (ht : is_open t) : is_open (s ∩ f⁻¹' t) :=
(continuous_on_open_iff hs).1 hf t ht
lemma continuous_on.is_open_preimage {f : α → β} {s : set α} {t : set β} (h : continuous_on f s)
(hs : is_open s) (hp : f ⁻¹' t ⊆ s) (ht : is_open t) : is_open (f ⁻¹' t) :=
begin
convert (continuous_on_open_iff hs).mp h t ht,
rw [inter_comm, inter_eq_self_of_subset_left hp],
end
lemma continuous_on.preimage_closed_of_closed {f : α → β} {s : set α} {t : set β}
(hf : continuous_on f s) (hs : is_closed s) (ht : is_closed t) : is_closed (s ∩ f⁻¹' t) :=
begin
rcases continuous_on_iff_is_closed.1 hf t ht with ⟨u, hu⟩,
rw [inter_comm, hu.2],
apply is_closed.inter hu.1 hs
end
lemma continuous_on.preimage_interior_subset_interior_preimage {f : α → β} {s : set α} {t : set β}
(hf : continuous_on f s) (hs : is_open s) : s ∩ f⁻¹' (interior t) ⊆ s ∩ interior (f⁻¹' t) :=
calc s ∩ f ⁻¹' (interior t) ⊆ interior (s ∩ f ⁻¹' t) :
interior_maximal (inter_subset_inter (subset.refl _) (preimage_mono interior_subset))
(hf.preimage_open_of_open hs is_open_interior)
... = s ∩ interior (f ⁻¹' t) : by rw [interior_inter, hs.interior_eq]
lemma continuous_on_of_locally_continuous_on {f : α → β} {s : set α}
(h : ∀x∈s, ∃t, is_open t ∧ x ∈ t ∧ continuous_on f (s ∩ t)) : continuous_on f s :=
begin
assume x xs,
rcases h x xs with ⟨t, open_t, xt, ct⟩,
have := ct x ⟨xs, xt⟩,
rwa [continuous_within_at, ← nhds_within_restrict _ xt open_t] at this
end
lemma continuous_on_open_of_generate_from {β : Type*} {s : set α} {T : set (set β)} {f : α → β}
(hs : is_open s) (h : ∀t ∈ T, is_open (s ∩ f⁻¹' t)) :
@continuous_on α β _ (topological_space.generate_from T) f s :=
begin
rw continuous_on_open_iff,
assume t ht,
induction ht with u hu u v Tu Tv hu hv U hU hU',
{ exact h u hu },
{ simp only [preimage_univ, inter_univ], exact hs },
{ have : s ∩ f ⁻¹' (u ∩ v) = (s ∩ f ⁻¹' u) ∩ (s ∩ f ⁻¹' v),
by { ext x, simp, split, finish, finish },
rw this,
exact is_open.inter hu hv },
{ rw [preimage_sUnion, inter_bUnion],
exact is_open_bUnion hU' },
{ exact hs }
end
lemma continuous_within_at.prod {f : α → β} {g : α → γ} {s : set α} {x : α}
(hf : continuous_within_at f s x) (hg : continuous_within_at g s x) :
continuous_within_at (λx, (f x, g x)) s x :=
hf.prod_mk_nhds hg
lemma continuous_on.prod {f : α → β} {g : α → γ} {s : set α}
(hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, (f x, g x)) s :=
λx hx, continuous_within_at.prod (hf x hx) (hg x hx)
lemma inducing.continuous_on_iff {f : α → β} {g : β → γ} (hg : inducing g) {s : set α} :
continuous_on f s ↔ continuous_on (g ∘ f) s :=
begin
simp only [continuous_on_iff_continuous_restrict, restrict_eq],
conv_rhs { rw [function.comp.assoc, ← (inducing.continuous_iff hg)] },
end
lemma embedding.continuous_on_iff {f : α → β} {g : β → γ} (hg : embedding g) {s : set α} :
continuous_on f s ↔ continuous_on (g ∘ f) s :=
inducing.continuous_on_iff hg.1
lemma continuous_within_at_of_not_mem_closure {f : α → β} {s : set α} {x : α} :
x ∉ closure s → continuous_within_at f s x :=
begin
intros hx,
rw [mem_closure_iff_nhds_within_ne_bot, ne_bot_iff, not_not] at hx,
rw [continuous_within_at, hx],
exact tendsto_bot,
end
lemma continuous_on.piecewise' {s t : set α} {f g : α → β} [∀ a, decidable (a ∈ t)]
(hpf : ∀ a ∈ s ∩ frontier t, tendsto f (𝓝[s ∩ t] a) (𝓝 (piecewise t f g a)))
(hpg : ∀ a ∈ s ∩ frontier t, tendsto g (𝓝[s ∩ tᶜ] a) (𝓝 (piecewise t f g a)))
(hf : continuous_on f $ s ∩ t) (hg : continuous_on g $ s ∩ tᶜ) :
continuous_on (piecewise t f g) s :=
begin
intros x hx,
by_cases hx' : x ∈ frontier t,
{ exact (hpf x ⟨hx, hx'⟩).piecewise_nhds_within (hpg x ⟨hx, hx'⟩) },
{ rw [← inter_univ s, ← union_compl_self t, inter_union_distrib_left] at hx ⊢,
cases hx,
{ apply continuous_within_at.union,
{ exact (hf x hx).congr (λ y hy, piecewise_eq_of_mem _ _ _ hy.2)
(piecewise_eq_of_mem _ _ _ hx.2) },
{ have : x ∉ closure tᶜ,
from λ h, hx' ⟨subset_closure hx.2, by rwa closure_compl at h⟩,
exact continuous_within_at_of_not_mem_closure
(λ h, this (closure_inter_subset_inter_closure _ _ h).2) } },
{ apply continuous_within_at.union,
{ have : x ∉ closure t,
from (λ h, hx' ⟨h, (λ (h' : x ∈ interior t), hx.2 (interior_subset h'))⟩),
exact continuous_within_at_of_not_mem_closure
(λ h, this (closure_inter_subset_inter_closure _ _ h).2) },
{ exact (hg x hx).congr
(λ y hy, piecewise_eq_of_not_mem _ _ _ hy.2)
(piecewise_eq_of_not_mem _ _ _ hx.2) } } }
end
lemma continuous_on.if' {s : set α} {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)]
(hpf : ∀ a ∈ s ∩ frontier {a | p a},
tendsto f (𝓝[s ∩ {a | p a}] a) (𝓝 $ if p a then f a else g a))
(hpg : ∀ a ∈ s ∩ frontier {a | p a},
tendsto g (𝓝[s ∩ {a | ¬p a}] a) (𝓝 $ if p a then f a else g a))
(hf : continuous_on f $ s ∩ {a | p a}) (hg : continuous_on g $ s ∩ {a | ¬p a}) :
continuous_on (λ a, if p a then f a else g a) s :=
hf.piecewise' hpf hpg hg
lemma continuous_on.if {α β : Type*} [topological_space α] [topological_space β] {p : α → Prop}
[∀ a, decidable (p a)] {s : set α} {f g : α → β}
(hp : ∀ a ∈ s ∩ frontier {a | p a}, f a = g a) (hf : continuous_on f $ s ∩ closure {a | p a})
(hg : continuous_on g $ s ∩ closure {a | ¬ p a}) :
continuous_on (λa, if p a then f a else g a) s :=
begin
apply continuous_on.if',
{ rintros a ha,
simp only [← hp a ha, if_t_t],
apply tendsto_nhds_within_mono_left (inter_subset_inter_right s subset_closure),
exact hf a ⟨ha.1, ha.2.1⟩ },
{ rintros a ha,
simp only [hp a ha, if_t_t],
apply tendsto_nhds_within_mono_left (inter_subset_inter_right s subset_closure),
rcases ha with ⟨has, ⟨_, ha⟩⟩,
rw [← mem_compl_iff, ← closure_compl] at ha,
apply hg a ⟨has, ha⟩ },
{ exact hf.mono (inter_subset_inter_right s subset_closure) },
{ exact hg.mono (inter_subset_inter_right s subset_closure) }
end
lemma continuous_on.piecewise {s t : set α} {f g : α → β} [∀ a, decidable (a ∈ t)]
(ht : ∀ a ∈ s ∩ frontier t, f a = g a) (hf : continuous_on f $ s ∩ closure t)
(hg : continuous_on g $ s ∩ closure tᶜ) :
continuous_on (piecewise t f g) s :=
hf.if ht hg
lemma continuous_if' {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)]
(hpf : ∀ a ∈ frontier {x | p x}, tendsto f (𝓝[{x | p x}] a) (𝓝 $ ite (p a) (f a) (g a)))
(hpg : ∀ a ∈ frontier {x | p x}, tendsto g (𝓝[{x | ¬p x}] a) (𝓝 $ ite (p a) (f a) (g a)))
(hf : continuous_on f {x | p x}) (hg : continuous_on g {x | ¬p x}) :
continuous (λ a, ite (p a) (f a) (g a)) :=
begin
rw continuous_iff_continuous_on_univ,
apply continuous_on.if'; simp *; assumption
end
lemma continuous_if {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)]
(hp : ∀ a ∈ frontier {x | p x}, f a = g a) (hf : continuous_on f (closure {x | p x}))
(hg : continuous_on g (closure {x | ¬p x})) :
continuous (λ a, if p a then f a else g a) :=
begin
rw continuous_iff_continuous_on_univ,
apply continuous_on.if; simp; assumption
end
lemma continuous.if {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)]
(hp : ∀ a ∈ frontier {x | p x}, f a = g a) (hf : continuous f) (hg : continuous g) :
continuous (λ a, if p a then f a else g a) :=
continuous_if hp hf.continuous_on hg.continuous_on
lemma continuous_piecewise {s : set α} {f g : α → β} [∀ a, decidable (a ∈ s)]
(hs : ∀ a ∈ frontier s, f a = g a) (hf : continuous_on f (closure s))
(hg : continuous_on g (closure sᶜ)) :
continuous (piecewise s f g) :=
continuous_if hs hf hg
lemma continuous.piecewise {s : set α} {f g : α → β} [∀ a, decidable (a ∈ s)]
(hs : ∀ a ∈ frontier s, f a = g a) (hf : continuous f) (hg : continuous g) :
continuous (piecewise s f g) :=
hf.if hs hg
lemma is_open.ite' {s s' t : set α}
(hs : is_open s) (hs' : is_open s') (ht : ∀ x ∈ frontier t, x ∈ s ↔ x ∈ s') :
is_open (t.ite s s') :=
begin
classical,
simp only [is_open_iff_continuous_mem, set.ite] at *,
convert continuous_piecewise (λ x hx, propext (ht x hx)) hs.continuous_on hs'.continuous_on,
ext x, by_cases hx : x ∈ t; simp [hx]
end
lemma is_open.ite {s s' t : set α} (hs : is_open s) (hs' : is_open s')
(ht : s ∩ frontier t = s' ∩ frontier t) :
is_open (t.ite s s') :=
hs.ite' hs' $ λ x hx, by simpa [hx] using ext_iff.1 ht x
lemma ite_inter_closure_eq_of_inter_frontier_eq {s s' t : set α}
(ht : s ∩ frontier t = s' ∩ frontier t) :
t.ite s s' ∩ closure t = s ∩ closure t :=
by rw [closure_eq_self_union_frontier, inter_union_distrib_left, inter_union_distrib_left,
ite_inter_self, ite_inter_of_inter_eq _ ht]
lemma ite_inter_closure_compl_eq_of_inter_frontier_eq {s s' t : set α}
(ht : s ∩ frontier t = s' ∩ frontier t) :
t.ite s s' ∩ closure tᶜ = s' ∩ closure tᶜ :=
by { rw [← ite_compl, ite_inter_closure_eq_of_inter_frontier_eq], rwa [frontier_compl, eq_comm] }
lemma continuous_on_piecewise_ite' {s s' t : set α} {f f' : α → β} [∀ x, decidable (x ∈ t)]
(h : continuous_on f (s ∩ closure t)) (h' : continuous_on f' (s' ∩ closure tᶜ))
(H : s ∩ frontier t = s' ∩ frontier t) (Heq : eq_on f f' (s ∩ frontier t)) :
continuous_on (t.piecewise f f') (t.ite s s') :=
begin
apply continuous_on.piecewise,
{ rwa ite_inter_of_inter_eq _ H },
{ rwa ite_inter_closure_eq_of_inter_frontier_eq H },
{ rwa ite_inter_closure_compl_eq_of_inter_frontier_eq H }
end
lemma continuous_on_piecewise_ite {s s' t : set α} {f f' : α → β} [∀ x, decidable (x ∈ t)]
(h : continuous_on f s) (h' : continuous_on f' s')
(H : s ∩ frontier t = s' ∩ frontier t) (Heq : eq_on f f' (s ∩ frontier t)) :
continuous_on (t.piecewise f f') (t.ite s s') :=
continuous_on_piecewise_ite' (h.mono (inter_subset_left _ _)) (h'.mono (inter_subset_left _ _))
H Heq
lemma continuous_on_fst {s : set (α × β)} : continuous_on prod.fst s :=
continuous_fst.continuous_on
lemma continuous_within_at_fst {s : set (α × β)} {p : α × β} :
continuous_within_at prod.fst s p :=
continuous_fst.continuous_within_at
lemma continuous_on_snd {s : set (α × β)} : continuous_on prod.snd s :=
continuous_snd.continuous_on
lemma continuous_within_at_snd {s : set (α × β)} {p : α × β} :
continuous_within_at prod.snd s p :=
continuous_snd.continuous_within_at
lemma continuous_within_at.fst {f : α → β × γ} {s : set α} {a : α}
(h : continuous_within_at f s a) : continuous_within_at (λ x, (f x).fst) s a :=
continuous_at_fst.comp_continuous_within_at h
lemma continuous_within_at.snd {f : α → β × γ} {s : set α} {a : α}
(h : continuous_within_at f s a) : continuous_within_at (λ x, (f x).snd) s a :=
continuous_at_snd.comp_continuous_within_at h
lemma continuous_within_at_prod_iff {f : α → β × γ} {s : set α} {x : α} :
continuous_within_at f s x ↔ continuous_within_at (prod.fst ∘ f) s x ∧
continuous_within_at (prod.snd ∘ f) s x :=
⟨λ h, ⟨h.fst, h.snd⟩, by { rintro ⟨h1, h2⟩, convert h1.prod h2, ext, refl, refl }⟩
|
e0d51b28cb3254cc501ba1d85573e2c0b10d4c1a
|
d406927ab5617694ec9ea7001f101b7c9e3d9702
|
/src/topology/shrinking_lemma.lean
|
9224bb9a6526a603bed7ff30fd8b0d348a9b9f64
|
[
"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
| 12,196
|
lean
|
/-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Reid Barton
-/
import topology.separation
/-!
# The shrinking lemma
In this file we prove a few versions of the shrinking lemma. The lemma says that in a normal
topological space a point finite open covering can be “shrunk”: for a point finite open covering
`u : ι → set X` there exists a refinement `v : ι → set X` such that `closure (v i) ⊆ u i`.
For finite or countable coverings this lemma can be proved without the axiom of choice, see
[ncatlab](https://ncatlab.org/nlab/show/shrinking+lemma) for details. We only formalize the most
general result that works for any covering but needs the axiom of choice.
We prove two versions of the lemma:
* `exists_subset_Union_closure_subset` deals with a covering of a closed set in a normal space;
* `exists_Union_eq_closure_subset` deals with a covering of the whole space.
## Tags
normal space, shrinking lemma
-/
open set function
open_locale classical
noncomputable theory
variables {ι X : Type*} [topological_space X] [normal_space X]
namespace shrinking_lemma
/-- Auxiliary definition for the proof of `shrinking_lemma`. A partial refinement of a covering
`⋃ i, u i` of a set `s` is a map `v : ι → set X` and a set `carrier : set ι` such that
* `s ⊆ ⋃ i, v i`;
* all `v i` are open;
* if `i ∈ carrier v`, then `closure (v i) ⊆ u i`;
* if `i ∉ carrier`, then `v i = u i`.
This type is equipped with the folowing partial order: `v ≤ v'` if `v.carrier ⊆ v'.carrier`
and `v i = v' i` for `i ∈ v.carrier`. We will use Zorn's lemma to prove that this type has
a maximal element, then show that the maximal element must have `carrier = univ`. -/
@[nolint has_nonempty_instance] -- the trivial refinement needs `u` to be a covering
structure partial_refinement (u : ι → set X) (s : set X) :=
(to_fun : ι → set X)
(carrier : set ι)
(is_open' : ∀ i, is_open (to_fun i))
(subset_Union' : s ⊆ ⋃ i, to_fun i)
(closure_subset' : ∀ i ∈ carrier, closure (to_fun i) ⊆ (u i))
(apply_eq' : ∀ i ∉ carrier, to_fun i = u i)
namespace partial_refinement
variables {u : ι → set X} {s : set X}
instance : has_coe_to_fun (partial_refinement u s) (λ _, ι → set X) := ⟨to_fun⟩
lemma subset_Union (v : partial_refinement u s) : s ⊆ ⋃ i, v i := v.subset_Union'
lemma closure_subset (v : partial_refinement u s) {i : ι} (hi : i ∈ v.carrier) :
closure (v i) ⊆ (u i) :=
v.closure_subset' i hi
lemma apply_eq (v : partial_refinement u s) {i : ι} (hi : i ∉ v.carrier) : v i = u i :=
v.apply_eq' i hi
protected lemma is_open (v : partial_refinement u s) (i : ι) : is_open (v i) := v.is_open' i
protected lemma subset (v : partial_refinement u s) (i : ι) : v i ⊆ u i :=
if h : i ∈ v.carrier then subset.trans subset_closure (v.closure_subset h)
else (v.apply_eq h).le
attribute [ext] partial_refinement
instance : partial_order (partial_refinement u s) :=
{ le := λ v₁ v₂, v₁.carrier ⊆ v₂.carrier ∧ ∀ i ∈ v₁.carrier, v₁ i = v₂ i,
le_refl := λ v, ⟨subset.refl _, λ _ _, rfl⟩,
le_trans := λ v₁ v₂ v₃ h₁₂ h₂₃,
⟨subset.trans h₁₂.1 h₂₃.1, λ i hi, (h₁₂.2 i hi).trans (h₂₃.2 i $ h₁₂.1 hi)⟩,
le_antisymm := λ v₁ v₂ h₁₂ h₂₁,
have hc : v₁.carrier = v₂.carrier, from subset.antisymm h₁₂.1 h₂₁.1,
ext _ _ (funext $ λ x,
if hx : x ∈ v₁.carrier then h₁₂.2 _ hx
else (v₁.apply_eq hx).trans (eq.symm $ v₂.apply_eq $ hc ▸ hx)) hc }
/-- If two partial refinements `v₁`, `v₂` belong to a chain (hence, they are comparable)
and `i` belongs to the carriers of both partial refinements, then `v₁ i = v₂ i`. -/
lemma apply_eq_of_chain {c : set (partial_refinement u s)} (hc : is_chain (≤) c) {v₁ v₂}
(h₁ : v₁ ∈ c) (h₂ : v₂ ∈ c) {i} (hi₁ : i ∈ v₁.carrier) (hi₂ : i ∈ v₂.carrier) :
v₁ i = v₂ i :=
begin
wlog hle : v₁ ≤ v₂ := hc.total h₁ h₂ using [v₁ v₂, v₂ v₁],
exact hle.2 _ hi₁,
end
/-- The carrier of the least upper bound of a non-empty chain of partial refinements
is the union of their carriers. -/
def chain_Sup_carrier (c : set (partial_refinement u s)) : set ι :=
⋃ v ∈ c, carrier v
/-- Choice of an element of a nonempty chain of partial refinements. If `i` belongs to one of
`carrier v`, `v ∈ c`, then `find c ne i` is one of these partial refinements. -/
def find (c : set (partial_refinement u s)) (ne : c.nonempty) (i : ι) :
partial_refinement u s :=
if hi : ∃ v ∈ c, i ∈ carrier v then hi.some else ne.some
lemma find_mem {c : set (partial_refinement u s)} (i : ι) (ne : c.nonempty) :
find c ne i ∈ c :=
by { rw find, split_ifs, exacts [h.some_spec.fst, ne.some_spec] }
lemma mem_find_carrier_iff {c : set (partial_refinement u s)} {i : ι} (ne : c.nonempty) :
i ∈ (find c ne i).carrier ↔ i ∈ chain_Sup_carrier c :=
begin
rw find,
split_ifs,
{ have : i ∈ h.some.carrier ∧ i ∈ chain_Sup_carrier c,
from ⟨h.some_spec.snd, mem_Union₂.2 h⟩,
simp only [this] },
{ have : i ∉ ne.some.carrier ∧ i ∉ chain_Sup_carrier c,
from ⟨λ hi, h ⟨_, ne.some_spec, hi⟩, mt mem_Union₂.1 h⟩,
simp only [this] }
end
lemma find_apply_of_mem {c : set (partial_refinement u s)} (hc : is_chain (≤) c) (ne : c.nonempty)
{i v} (hv : v ∈ c) (hi : i ∈ carrier v) :
find c ne i i = v i :=
apply_eq_of_chain hc (find_mem _ _) hv
((mem_find_carrier_iff _).2 $ mem_Union₂.2 ⟨v, hv, hi⟩) hi
/-- Least upper bound of a nonempty chain of partial refinements. -/
def chain_Sup (c : set (partial_refinement u s)) (hc : is_chain (≤) c)
(ne : c.nonempty) (hfin : ∀ x ∈ s, {i | x ∈ u i}.finite) (hU : s ⊆ ⋃ i, u i) :
partial_refinement u s :=
begin
refine ⟨λ i, find c ne i i, chain_Sup_carrier c,
λ i, (find _ _ _).is_open i,
λ x hxs, mem_Union.2 _,
λ i hi, (find c ne i).closure_subset ((mem_find_carrier_iff _).2 hi),
λ i hi, (find c ne i).apply_eq (mt (mem_find_carrier_iff _).1 hi)⟩,
rcases em (∃ i ∉ chain_Sup_carrier c, x ∈ u i) with ⟨i, hi, hxi⟩|hx,
{ use i,
rwa (find c ne i).apply_eq (mt (mem_find_carrier_iff _).1 hi) },
{ simp_rw [not_exists, not_imp_not, chain_Sup_carrier, mem_Union₂] at hx,
haveI : nonempty (partial_refinement u s) := ⟨ne.some⟩,
choose! v hvc hiv using hx,
rcases (hfin x hxs).exists_maximal_wrt v _ (mem_Union.1 (hU hxs))
with ⟨i, hxi : x ∈ u i, hmax : ∀ j, x ∈ u j → v i ≤ v j → v i = v j⟩,
rcases mem_Union.1 ((v i).subset_Union hxs) with ⟨j, hj⟩,
use j,
have hj' : x ∈ u j := (v i).subset _ hj,
have : v j ≤ v i,
from (hc.total (hvc _ hxi) (hvc _ hj')).elim (λ h, (hmax j hj' h).ge) id,
rwa find_apply_of_mem hc ne (hvc _ hxi) (this.1 $ hiv _ hj') }
end
/-- `chain_Sup hu c hc ne hfin hU` is an upper bound of the chain `c`. -/
lemma le_chain_Sup {c : set (partial_refinement u s)} (hc : is_chain (≤) c)
(ne : c.nonempty) (hfin : ∀ x ∈ s, {i | x ∈ u i}.finite) (hU : s ⊆ ⋃ i, u i)
{v} (hv : v ∈ c) :
v ≤ chain_Sup c hc ne hfin hU :=
⟨λ i hi, mem_bUnion hv hi, λ i hi, (find_apply_of_mem hc _ hv hi).symm⟩
/-- If `s` is a closed set, `v` is a partial refinement, and `i` is an index such that
`i ∉ v.carrier`, then there exists a partial refinement that is strictly greater than `v`. -/
lemma exists_gt (v : partial_refinement u s) (hs : is_closed s) (i : ι) (hi : i ∉ v.carrier) :
∃ v' : partial_refinement u s, v < v' :=
begin
have I : s ∩ (⋂ j ≠ i, (v j)ᶜ) ⊆ v i,
{ simp only [subset_def, mem_inter_iff, mem_Inter, and_imp],
intros x hxs H,
rcases mem_Union.1 (v.subset_Union hxs) with ⟨j, hj⟩,
exact (em (j = i)).elim (λ h, h ▸ hj) (λ h, (H j h hj).elim) },
have C : is_closed (s ∩ (⋂ j ≠ i, (v j)ᶜ)),
from is_closed.inter hs (is_closed_bInter $ λ _ _, is_closed_compl_iff.2 $ v.is_open _),
rcases normal_exists_closure_subset C (v.is_open i) I with ⟨vi, ovi, hvi, cvi⟩,
refine ⟨⟨update v i vi, insert i v.carrier, _, _, _, _⟩, _, _⟩,
{ intro j, by_cases h : j = i; simp [h, ovi, v.is_open] },
{ refine λ x hx, mem_Union.2 _,
rcases em (∃ j ≠ i, x ∈ v j) with ⟨j, hji, hj⟩|h,
{ use j, rwa update_noteq hji },
{ push_neg at h, use i, rw update_same, exact hvi ⟨hx, mem_bInter h⟩ } },
{ rintro j (rfl|hj),
{ rwa [update_same, ← v.apply_eq hi] },
{ rw update_noteq (ne_of_mem_of_not_mem hj hi), exact v.closure_subset hj } },
{ intros j hj,
rw [mem_insert_iff, not_or_distrib] at hj,
rw [update_noteq hj.1, v.apply_eq hj.2] },
{ refine ⟨subset_insert _ _, λ j hj, _⟩,
exact (update_noteq (ne_of_mem_of_not_mem hj hi) _ _).symm },
{ exact λ hle, hi (hle.1 $ mem_insert _ _) }
end
end partial_refinement
end shrinking_lemma
open shrinking_lemma
variables {u : ι → set X} {s : set X}
/-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk"
to a new open cover so that the closure of each new open set is contained in the corresponding
original open set. -/
lemma exists_subset_Union_closure_subset (hs : is_closed s) (uo : ∀ i, is_open (u i))
(uf : ∀ x ∈ s, {i | x ∈ u i}.finite) (us : s ⊆ ⋃ i, u i) :
∃ v : ι → set X, s ⊆ Union v ∧ (∀ i, is_open (v i)) ∧ ∀ i, closure (v i) ⊆ u i :=
begin
classical,
haveI : nonempty (partial_refinement u s) := ⟨⟨u, ∅, uo, us, λ _, false.elim, λ _ _, rfl⟩⟩,
have : ∀ c : set (partial_refinement u s), is_chain (≤) c → c.nonempty → ∃ ub, ∀ v ∈ c, v ≤ ub,
from λ c hc ne, ⟨partial_refinement.chain_Sup c hc ne uf us,
λ v hv, partial_refinement.le_chain_Sup _ _ _ _ hv⟩,
rcases zorn_nonempty_partial_order this with ⟨v, hv⟩,
suffices : ∀ i, i ∈ v.carrier,
from ⟨v, v.subset_Union, λ i, v.is_open _, λ i, v.closure_subset (this i)⟩,
contrapose! hv,
rcases hv with ⟨i, hi⟩,
rcases v.exists_gt hs i hi with ⟨v', hlt⟩,
exact ⟨v', hlt.le, hlt.ne'⟩
end
/-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk"
to a new closed cover so that each new closed set is contained in the corresponding original open
set. See also `exists_subset_Union_closure_subset` for a stronger statement. -/
lemma exists_subset_Union_closed_subset (hs : is_closed s) (uo : ∀ i, is_open (u i))
(uf : ∀ x ∈ s, {i | x ∈ u i}.finite) (us : s ⊆ ⋃ i, u i) :
∃ v : ι → set X, s ⊆ Union v ∧ (∀ i, is_closed (v i)) ∧ ∀ i, v i ⊆ u i :=
let ⟨v, hsv, hvo, hv⟩ := exists_subset_Union_closure_subset hs uo uf us
in ⟨λ i, closure (v i), subset.trans hsv (Union_mono $ λ i, subset_closure),
λ i, is_closed_closure, hv⟩
/-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk"
to a new open cover so that the closure of each new open set is contained in the corresponding
original open set. -/
lemma exists_Union_eq_closure_subset (uo : ∀ i, is_open (u i)) (uf : ∀ x, {i | x ∈ u i}.finite)
(uU : (⋃ i, u i) = univ) :
∃ v : ι → set X, Union v = univ ∧ (∀ i, is_open (v i)) ∧ ∀ i, closure (v i) ⊆ u i :=
let ⟨v, vU, hv⟩ := exists_subset_Union_closure_subset is_closed_univ uo (λ x _, uf x) uU.ge
in ⟨v, univ_subset_iff.1 vU, hv⟩
/-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk"
to a new closed cover so that each of the new closed sets is contained in the corresponding
original open set. See also `exists_Union_eq_closure_subset` for a stronger statement. -/
lemma exists_Union_eq_closed_subset (uo : ∀ i, is_open (u i)) (uf : ∀ x, {i | x ∈ u i}.finite)
(uU : (⋃ i, u i) = univ) :
∃ v : ι → set X, Union v = univ ∧ (∀ i, is_closed (v i)) ∧ ∀ i, v i ⊆ u i :=
let ⟨v, vU, hv⟩ := exists_subset_Union_closed_subset is_closed_univ uo (λ x _, uf x) uU.ge
in ⟨v, univ_subset_iff.1 vU, hv⟩
|
0df08cc5e02fe0863afa8722c4260c1d8e229000
|
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
|
/src/algebra/ring/basic.lean
|
2ff747d635384cb0df419d166e47dc62463ed164
|
[
"Apache-2.0"
] |
permissive
|
molodiuc/mathlib
|
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
|
98ebe5a6739fbe254f9ee9d401882d4388f91035
|
refs/heads/master
| 1,674,237,127,059
| 1,606,353,533,000
| 1,606,353,533,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 38,353
|
lean
|
/-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Amelia Livingston, Yury Kudryashov,
Neil Strickland
-/
import algebra.divisibility
import data.set.basic
/-!
# Properties and homomorphisms of semirings and rings
This file proves simple properties of semirings, rings and domains and their unit groups. It also
defines bundled homomorphisms of semirings and rings. As with monoid and groups, we use the same
structure `ring_hom a β`, a.k.a. `α →+* β`, for both homomorphism types.
The unbundled homomorphisms are defined in `deprecated/ring`. They are deprecated and the plan is to
slowly remove them from mathlib.
## Main definitions
ring_hom, nonzero, domain, integral_domain
## Notations
→+* for bundled ring homs (also use for semiring homs)
## Implementation notes
There's a coercion from bundled homs to fun, and the canonical
notation is to use the bundled hom as a function via this coercion.
There is no `semiring_hom` -- the idea is that `ring_hom` is used.
The constructor for a `ring_hom` between semirings needs a proof of `map_zero`, `map_one` and
`map_add` as well as `map_mul`; a separate constructor `ring_hom.mk'` will construct ring homs
between rings from monoid homs given only a proof that addition is preserved.
## Tags
`ring_hom`, `semiring_hom`, `semiring`, `comm_semiring`, `ring`, `comm_ring`, `domain`,
`integral_domain`, `nonzero`, `units`
-/
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {R : Type x}
set_option old_structure_cmd true
open function
/-!
### `distrib` class
-/
/-- A typeclass stating that multiplication is left and right distributive
over addition. -/
@[protect_proj, ancestor has_mul has_add]
class distrib (R : Type*) extends has_mul R, has_add R :=
(left_distrib : ∀ a b c : R, a * (b + c) = (a * b) + (a * c))
(right_distrib : ∀ a b c : R, (a + b) * c = (a * c) + (b * c))
lemma left_distrib [distrib R] (a b c : R) : a * (b + c) = a * b + a * c :=
distrib.left_distrib a b c
alias left_distrib ← mul_add
lemma right_distrib [distrib R] (a b c : R) : (a + b) * c = a * c + b * c :=
distrib.right_distrib a b c
alias right_distrib ← add_mul
/-- Pullback a `distrib` instance along an injective function. -/
protected def function.injective.distrib {S} [has_mul R] [has_add R] [distrib S]
(f : R → S) (hf : injective f) (add : ∀ x y, f (x + y) = f x + f y)
(mul : ∀ x y, f (x * y) = f x * f y) :
distrib R :=
{ mul := (*),
add := (+),
left_distrib := λ x y z, hf $ by simp only [*, left_distrib],
right_distrib := λ x y z, hf $ by simp only [*, right_distrib] }
/-- Pushforward a `distrib` instance along a surjective function. -/
protected def function.surjective.distrib {S} [distrib R] [has_add S] [has_mul S]
(f : R → S) (hf : surjective f) (add : ∀ x y, f (x + y) = f x + f y)
(mul : ∀ x y, f (x * y) = f x * f y) :
distrib S :=
{ mul := (*),
add := (+),
left_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, left_distrib],
right_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, right_distrib] }
/-!
### Semirings
-/
/-- A semiring is a type with the following structures: additive commutative monoid
(`add_comm_monoid`), multiplicative monoid (`monoid`), distributive laws (`distrib`), and
multiplication by zero law (`mul_zero_class`). The actual definition extends `monoid_with_zero`
instead of `monoid` and `mul_zero_class`. -/
@[protect_proj, ancestor add_comm_monoid monoid_with_zero distrib]
class semiring (α : Type u) extends add_comm_monoid α, monoid_with_zero α, distrib α
section semiring
variables [semiring α]
/-- Pullback a `semiring` instance along an injective function. -/
protected def function.injective.semiring [has_zero β] [has_one β] [has_add β] [has_mul β]
(f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) :
semiring β :=
{ .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add,
.. hf.distrib f add mul }
/-- Pullback a `semiring` instance along an injective function. -/
protected def function.surjective.semiring [has_zero β] [has_one β] [has_add β] [has_mul β]
(f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) :
semiring β :=
{ .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add,
.. hf.distrib f add mul }
lemma one_add_one_eq_two : 1 + 1 = (2 : α) :=
by unfold bit0
theorem two_mul (n : α) : 2 * n = n + n :=
eq.trans (right_distrib 1 1 n) (by simp)
lemma distrib_three_right (a b c d : α) : (a + b + c) * d = a * d + b * d + c * d :=
by simp [right_distrib]
theorem mul_two (n : α) : n * 2 = n + n :=
(left_distrib n 1 1).trans (by simp)
theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n :=
(two_mul _).symm
@[to_additive] lemma mul_ite {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) :
a * (if P then b else c) = if P then a * b else a * c :=
by split_ifs; refl
@[to_additive] lemma ite_mul {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) :
(if P then a else b) * c = if P then a * c else b * c :=
by split_ifs; refl
-- We make `mul_ite` and `ite_mul` simp lemmas,
-- but not `add_ite` or `ite_add`.
-- The problem we're trying to avoid is dealing with
-- summations of the form `∑ x in s, (f x + ite P 1 0)`,
-- in which `add_ite` followed by `sum_ite` would needlessly slice up
-- the `f x` terms according to whether `P` holds at `x`.
-- There doesn't appear to be a corresponding difficulty so far with
-- `mul_ite` and `ite_mul`.
attribute [simp] mul_ite ite_mul
@[simp] lemma mul_boole {α} [semiring α] (P : Prop) [decidable P] (a : α) :
a * (if P then 1 else 0) = if P then a else 0 :=
by simp
@[simp] lemma boole_mul {α} [semiring α] (P : Prop) [decidable P] (a : α) :
(if P then 1 else 0) * a = if P then a else 0 :=
by simp
lemma ite_mul_zero_left {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) :
ite P (a * b) 0 = ite P a 0 * b :=
by { by_cases h : P; simp [h], }
lemma ite_mul_zero_right {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) :
ite P (a * b) 0 = a * ite P b 0 :=
by { by_cases h : P; simp [h], }
/-- An element `a` of a semiring is even if there exists `k` such `a = 2*k`. -/
def even (a : α) : Prop := ∃ k, a = 2*k
lemma even_iff_two_dvd {a : α} : even a ↔ 2 ∣ a := iff.rfl
/-- An element `a` of a semiring is odd if there exists `k` such `a = 2*k + 1`. -/
def odd (a : α) : Prop := ∃ k, a = 2*k + 1
end semiring
namespace add_monoid_hom
/-- Left multiplication by an element of a (semi)ring is an `add_monoid_hom` -/
def mul_left {R : Type*} [semiring R] (r : R) : R →+ R :=
{ to_fun := (*) r,
map_zero' := mul_zero r,
map_add' := mul_add r }
@[simp] lemma coe_mul_left {R : Type*} [semiring R] (r : R) : ⇑(mul_left r) = (*) r := rfl
/-- Right multiplication by an element of a (semi)ring is an `add_monoid_hom` -/
def mul_right {R : Type*} [semiring R] (r : R) : R →+ R :=
{ to_fun := λ a, a * r,
map_zero' := zero_mul r,
map_add' := λ _ _, add_mul _ _ r }
@[simp] lemma coe_mul_right {R : Type*} [semiring R] (r : R) :
⇑(mul_right r) = (* r) := rfl
lemma mul_right_apply {R : Type*} [semiring R] (a r : R) :
mul_right r a = a * r := rfl
end add_monoid_hom
/-- Bundled semiring homomorphisms; use this for bundled ring homomorphisms too.
This extends from both `monoid_hom` and `monoid_with_zero_hom` in order to put the fields in a
sensible order, even though `monoid_with_zero_hom` already extends `monoid_hom`. -/
structure ring_hom (α : Type*) (β : Type*) [semiring α] [semiring β]
extends monoid_hom α β, add_monoid_hom α β, monoid_with_zero_hom α β
infixr ` →+* `:25 := ring_hom
/-- Reinterpret a ring homomorphism `f : R →+* S` as a `monoid_with_zero_hom R S`.
The `simp`-normal form is `(f : monoid_with_zero_hom R S)`. -/
add_decl_doc ring_hom.to_monoid_with_zero_hom
/-- Reinterpret a ring homomorphism `f : R →+* S` as a monoid homomorphism `R →* S`.
The `simp`-normal form is `(f : R →* S)`. -/
add_decl_doc ring_hom.to_monoid_hom
/-- Reinterpret a ring homomorphism `f : R →+* S` as an additive monoid homomorphism `R →+ S`.
The `simp`-normal form is `(f : R →+ S)`. -/
add_decl_doc ring_hom.to_add_monoid_hom
namespace ring_hom
section coe
/-!
Throughout this section, some `semiring` arguments are specified with `{}` instead of `[]`.
See note [implicit instance arguments].
-/
variables {rα : semiring α} {rβ : semiring β}
include rα rβ
instance : has_coe_to_fun (α →+* β) := ⟨_, ring_hom.to_fun⟩
initialize_simps_projections ring_hom (to_fun → apply)
@[simp] lemma to_fun_eq_coe (f : α →+* β) : f.to_fun = f := rfl
@[simp] lemma coe_mk (f : α → β) (h₁ h₂ h₃ h₄) : ⇑(⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) = f := rfl
instance has_coe_monoid_hom : has_coe (α →+* β) (α →* β) := ⟨ring_hom.to_monoid_hom⟩
@[simp, norm_cast] lemma coe_monoid_hom (f : α →+* β) : ⇑(f : α →* β) = f := rfl
@[simp] lemma to_monoid_hom_eq_coe (f : α →+* β) : f.to_monoid_hom = f := rfl
@[simp] lemma coe_monoid_hom_mk (f : α → β) (h₁ h₂ h₃ h₄) :
((⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) : α →* β) = ⟨f, h₁, h₂⟩ :=
rfl
instance has_coe_add_monoid_hom : has_coe (α →+* β) (α →+ β) := ⟨ring_hom.to_add_monoid_hom⟩
@[simp, norm_cast] lemma coe_add_monoid_hom (f : α →+* β) : ⇑(f : α →+ β) = f := rfl
@[simp] lemma to_add_monoid_hom_eq_coe (f : α →+* β) : f.to_add_monoid_hom = f := rfl
@[simp] lemma coe_add_monoid_hom_mk (f : α → β) (h₁ h₂ h₃ h₄) :
((⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) : α →+ β) = ⟨f, h₃, h₄⟩ :=
rfl
end coe
variables [rα : semiring α] [rβ : semiring β]
section
include rα rβ
variables (f : α →+* β) {x y : α} {rα rβ}
theorem congr_fun {f g : α →+* β} (h : f = g) (x : α) : f x = g x :=
congr_arg (λ h : α →+* β, h x) h
theorem congr_arg (f : α →+* β) {x y : α} (h : x = y) : f x = f y :=
congr_arg (λ x : α, f x) h
theorem coe_inj ⦃f g : α →+* β⦄ (h : (f : α → β) = g) : f = g :=
by cases f; cases g; cases h; refl
@[ext] theorem ext ⦃f g : α →+* β⦄ (h : ∀ x, f x = g x) : f = g :=
coe_inj (funext h)
theorem ext_iff {f g : α →+* β} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, ext h⟩
theorem coe_add_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →+ β)) :=
λ f g h, ext (λ x, add_monoid_hom.congr_fun h x)
theorem coe_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →* β)) :=
λ f g h, ext (λ x, monoid_hom.congr_fun h x)
/-- Ring homomorphisms map zero to zero. -/
@[simp] lemma map_zero (f : α →+* β) : f 0 = 0 := f.map_zero'
/-- Ring homomorphisms map one to one. -/
@[simp] lemma map_one (f : α →+* β) : f 1 = 1 := f.map_one'
/-- Ring homomorphisms preserve addition. -/
@[simp] lemma map_add (f : α →+* β) (a b : α) : f (a + b) = f a + f b := f.map_add' a b
/-- Ring homomorphisms preserve multiplication. -/
@[simp] lemma map_mul (f : α →+* β) (a b : α) : f (a * b) = f a * f b := f.map_mul' a b
/-- Ring homomorphisms preserve `bit0`. -/
@[simp] lemma map_bit0 (f : α →+* β) (a : α) : f (bit0 a) = bit0 (f a) := map_add _ _ _
/-- Ring homomorphisms preserve `bit1`. -/
@[simp] lemma map_bit1 (f : α →+* β) (a : α) : f (bit1 a) = bit1 (f a) :=
by simp [bit1]
/-- `f : R →+* S` has a trivial codomain iff `f 1 = 0`. -/
lemma codomain_trivial_iff_map_one_eq_zero : (0 : β) = 1 ↔ f 1 = 0 :=
by rw [map_one, eq_comm]
/-- `f : R →+* S` has a trivial codomain iff it has a trivial range. -/
lemma codomain_trivial_iff_range_trivial : (0 : β) = 1 ↔ (∀ x, f x = 0) :=
f.codomain_trivial_iff_map_one_eq_zero.trans
⟨λ h x, by rw [←mul_one x, map_mul, h, mul_zero], λ h, h 1⟩
/-- `f : R →+* S` has a trivial codomain iff its range is `{0}`. -/
lemma codomain_trivial_iff_range_eq_singleton_zero : (0 : β) = 1 ↔ set.range f = {0} :=
f.codomain_trivial_iff_range_trivial.trans
⟨ λ h, set.ext (λ y, ⟨λ ⟨x, hx⟩, by simp [←hx, h x], λ hy, ⟨0, by simpa using hy.symm⟩⟩),
λ h x, set.mem_singleton_iff.mp (h ▸ set.mem_range_self x)⟩
/-- `f : R →+* S` doesn't map `1` to `0` if `S` is nontrivial -/
lemma map_one_ne_zero [nontrivial β] : f 1 ≠ 0 :=
mt f.codomain_trivial_iff_map_one_eq_zero.mpr zero_ne_one
/-- If there is a homomorphism `f : R →+* S` and `S` is nontrivial, then `R` is nontrivial. -/
lemma domain_nontrivial [nontrivial β] : nontrivial α :=
⟨⟨1, 0, mt (λ h, show f 1 = 0, by rw [h, map_zero]) f.map_one_ne_zero⟩⟩
lemma is_unit_map (f : α →+* β) {a : α} (h : is_unit a) : is_unit (f a) :=
h.map (f.to_monoid_hom)
end
/-- The identity ring homomorphism from a semiring to itself. -/
def id (α : Type*) [semiring α] : α →+* α :=
by refine {to_fun := id, ..}; intros; refl
include rα
instance : inhabited (α →+* α) := ⟨id α⟩
@[simp] lemma id_apply (x : α) : ring_hom.id α x = x := rfl
variable {rγ : semiring γ}
include rβ rγ
/-- Composition of ring homomorphisms is a ring homomorphism. -/
def comp (hnp : β →+* γ) (hmn : α →+* β) : α →+* γ :=
{ to_fun := hnp ∘ hmn,
map_zero' := by simp,
map_one' := by simp,
map_add' := λ x y, by simp,
map_mul' := λ x y, by simp}
/-- Composition of semiring homomorphisms is associative. -/
lemma comp_assoc {δ} {rδ: semiring δ} (f : α →+* β) (g : β →+* γ) (h : γ →+* δ) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
@[simp] lemma coe_comp (hnp : β →+* γ) (hmn : α →+* β) : (hnp.comp hmn : α → γ) = hnp ∘ hmn := rfl
lemma comp_apply (hnp : β →+* γ) (hmn : α →+* β) (x : α) : (hnp.comp hmn : α → γ) x =
(hnp (hmn x)) := rfl
omit rγ
@[simp] lemma comp_id (f : α →+* β) : f.comp (id α) = f := ext $ λ x, rfl
@[simp] lemma id_comp (f : α →+* β) : (id β).comp f = f := ext $ λ x, rfl
omit rβ
instance : monoid (α →+* α) :=
{ one := id α,
mul := comp,
mul_one := comp_id,
one_mul := id_comp,
mul_assoc := λ f g h, comp_assoc _ _ _ }
lemma one_def : (1 : α →+* α) = id α := rfl
@[simp] lemma coe_one : ⇑(1 : α →+* α) = _root_.id := rfl
lemma mul_def (f g : α →+* α) : f * g = f.comp g := rfl
@[simp] lemma coe_mul (f g : α →+* α) : ⇑(f * g) = f ∘ g := rfl
include rβ rγ
lemma cancel_right {g₁ g₂ : β →+* γ} {f : α →+* β} (hf : surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, ring_hom.ext $ (forall_iff_forall_surj hf).1 (ext_iff.1 h), λ h, h ▸ rfl⟩
lemma cancel_left {g : β →+* γ} {f₁ f₂ : α →+* β} (hg : injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, ring_hom.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩
omit rα rβ rγ
end ring_hom
/-- A commutative semiring is a `semiring` with commutative multiplication. In other words, it is a
type with the following structures: additive commutative monoid (`add_comm_monoid`), multiplicative
commutative monoid (`comm_monoid`), distributive laws (`distrib`), and multiplication by zero law
(`mul_zero_class`). -/
@[protect_proj, ancestor semiring comm_monoid]
class comm_semiring (α : Type u) extends semiring α, comm_monoid α
@[priority 100] -- see Note [lower instance priority]
instance comm_semiring.to_comm_monoid_with_zero [comm_semiring α] : comm_monoid_with_zero α :=
{ .. comm_semiring.to_comm_monoid α, .. comm_semiring.to_semiring α }
section comm_semiring
variables [comm_semiring α] [comm_semiring β] {a b c : α}
@[priority 100] -- see Note [lower instance priority]
instance comm_semiring.comm_monoid_with_zero : comm_monoid_with_zero α :=
{ .. (‹_› : comm_semiring α) }
/-- Pullback a `semiring` instance along an injective function. -/
protected def function.injective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ]
(f : γ → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) :
comm_semiring γ :=
{ .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul }
/-- Pullback a `semiring` instance along an injective function. -/
protected def function.surjective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ]
(f : α → γ) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) :
comm_semiring γ :=
{ .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul }
lemma add_mul_self_eq (a b : α) : (a + b) * (a + b) = a*a + 2*a*b + b*b :=
calc (a + b)*(a + b) = a*a + (1+1)*a*b + b*b : by simp [add_mul, mul_add, mul_comm, add_assoc]
... = a*a + 2*a*b + b*b : by rw one_add_one_eq_two
theorem dvd_add (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c :=
dvd.elim h₁ (λ d hd, dvd.elim h₂ (λ e he, dvd.intro (d + e) (by simp [left_distrib, hd, he])))
@[simp] theorem two_dvd_bit0 : 2 ∣ bit0 a := ⟨a, bit0_eq_two_mul _⟩
lemma ring_hom.map_dvd (f : α →+* β) {a b : α} : a ∣ b → f a ∣ f b :=
λ ⟨z, hz⟩, ⟨f z, by rw [hz, f.map_mul]⟩
end comm_semiring
/-!
### Rings
-/
/-- A ring is a type with the following structures: additive commutative group (`add_comm_group`),
multiplicative monoid (`monoid`), and distributive laws (`distrib`). Equivalently, a ring is a
`semiring` with a negation operation making it an additive group. -/
@[protect_proj, ancestor add_comm_group monoid distrib]
class ring (α : Type u) extends add_comm_group α, monoid α, distrib α
section ring
variables [ring α] {a b c d e : α}
/- The instance from `ring` to `semiring` happens often in linear algebra, for which all the basic
definitions are given in terms of semirings, but many applications use rings or fields. We increase
a little bit its priority above 100 to try it quickly, but remaining below the default 1000 so that
more specific instances are tried first. -/
@[priority 200]
instance ring.to_semiring : semiring α :=
{ zero_mul := λ a, add_left_cancel $ show 0 * a + 0 * a = 0 * a + 0,
by rw [← add_mul, zero_add, add_zero],
mul_zero := λ a, add_left_cancel $ show a * 0 + a * 0 = a * 0 + 0,
by rw [← mul_add, add_zero, add_zero],
..‹ring α› }
/-- Pullback a `ring` instance along an injective function. -/
protected def function.injective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β]
(f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) :
ring β :=
{ .. hf.add_comm_group f zero add neg, .. hf.monoid f one mul, .. hf.distrib f add mul }
/-- Pullback a `ring` instance along an injective function. -/
protected def function.surjective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β]
(f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) :
ring β :=
{ .. hf.add_comm_group f zero add neg, .. hf.monoid f one mul, .. hf.distrib f add mul }
lemma neg_mul_eq_neg_mul (a b : α) : -(a * b) = -a * b :=
neg_eq_of_add_eq_zero
begin rw [← right_distrib, add_right_neg, zero_mul] end
lemma neg_mul_eq_mul_neg (a b : α) : -(a * b) = a * -b :=
neg_eq_of_add_eq_zero
begin rw [← left_distrib, add_right_neg, mul_zero] end
@[simp] lemma neg_mul_eq_neg_mul_symm (a b : α) : - a * b = - (a * b) :=
eq.symm (neg_mul_eq_neg_mul a b)
@[simp] lemma mul_neg_eq_neg_mul_symm (a b : α) : a * - b = - (a * b) :=
eq.symm (neg_mul_eq_mul_neg a b)
lemma neg_mul_neg (a b : α) : -a * -b = a * b :=
by simp
lemma neg_mul_comm (a b : α) : -a * b = a * -b :=
by simp
theorem neg_eq_neg_one_mul (a : α) : -a = -1 * a :=
by simp
lemma mul_sub_left_distrib (a b c : α) : a * (b - c) = a * b - a * c :=
calc
a * (b - c) = a * b + a * -c : left_distrib a b (-c)
... = a * b - a * c : by simp [sub_eq_add_neg]
alias mul_sub_left_distrib ← mul_sub
lemma mul_sub_right_distrib (a b c : α) : (a - b) * c = a * c - b * c :=
calc
(a - b) * c = a * c + -b * c : right_distrib a (-b) c
... = a * c - b * c : by simp [sub_eq_add_neg]
alias mul_sub_right_distrib ← sub_mul
/-- An element of a ring multiplied by the additive inverse of one is the element's additive
inverse. -/
lemma mul_neg_one (a : α) : a * -1 = -a := by simp
/-- The additive inverse of one multiplied by an element of a ring is the element's additive
inverse. -/
lemma neg_one_mul (a : α) : -1 * a = -a := by simp
/-- An iff statement following from right distributivity in rings and the definition
of subtraction. -/
theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d :=
calc
a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp [add_comm]
... ↔ a * e + c - b * e = d : iff.intro (λ h, begin rw h, simp end) (λ h,
begin rw ← h, simp end)
... ↔ (a - b) * e + c = d : begin simp [sub_mul, sub_add_eq_add_sub] end
/-- A simplification of one side of an equation exploiting right distributivity in rings
and the definition of subtraction. -/
theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d :=
assume h,
calc
(a - b) * e + c = (a * e + c) - b * e : begin simp [sub_mul, sub_add_eq_add_sub] end
... = d : begin rw h, simp [@add_sub_cancel α] end
end ring
namespace units
variables [ring α] {a b : α}
/-- Each element of the group of units of a ring has an additive inverse. -/
instance : has_neg (units α) := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩
/-- Representing an element of a ring's unit group as an element of the ring commutes with
mapping this element to its additive inverse. -/
@[simp, norm_cast] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := rfl
@[simp, norm_cast] protected theorem coe_neg_one : ((-1 : units α) : α) = -1 := rfl
/-- Mapping an element of a ring's unit group to its inverse commutes with mapping this element
to its additive inverse. -/
@[simp] protected theorem neg_inv (u : units α) : (-u)⁻¹ = -u⁻¹ := rfl
/-- An element of a ring's unit group equals the additive inverse of its additive inverse. -/
@[simp] protected theorem neg_neg (u : units α) : - -u = u :=
units.ext $ neg_neg _
/-- Multiplication of elements of a ring's unit group commutes with mapping the first
argument to its additive inverse. -/
@[simp] protected theorem neg_mul (u₁ u₂ : units α) : -u₁ * u₂ = -(u₁ * u₂) :=
units.ext $ neg_mul_eq_neg_mul_symm _ _
/-- Multiplication of elements of a ring's unit group commutes with mapping the second argument
to its additive inverse. -/
@[simp] protected theorem mul_neg (u₁ u₂ : units α) : u₁ * -u₂ = -(u₁ * u₂) :=
units.ext $ (neg_mul_eq_mul_neg _ _).symm
/-- Multiplication of the additive inverses of two elements of a ring's unit group equals
multiplication of the two original elements. -/
@[simp] protected theorem neg_mul_neg (u₁ u₂ : units α) : -u₁ * -u₂ = u₁ * u₂ := by simp
/-- The additive inverse of an element of a ring's unit group equals the additive inverse of
one times the original element. -/
protected theorem neg_eq_neg_one_mul (u : units α) : -u = -1 * u := by simp
end units
namespace ring_hom
/-- Ring homomorphisms preserve additive inverse. -/
@[simp] theorem map_neg {α β} [ring α] [ring β] (f : α →+* β) (x : α) : f (-x) = -(f x) :=
(f : α →+ β).map_neg x
/-- Ring homomorphisms preserve subtraction. -/
@[simp] theorem map_sub {α β} [ring α] [ring β] (f : α →+* β) (x y : α) :
f (x - y) = (f x) - (f y) := (f : α →+ β).map_sub x y
/-- A ring homomorphism is injective iff its kernel is trivial. -/
theorem injective_iff {α β} [ring α] [semiring β] (f : α →+* β) :
function.injective f ↔ (∀ a, f a = 0 → a = 0) :=
(f : α →+ β).injective_iff
/-- Makes a ring homomorphism from a monoid homomorphism of rings which preserves addition. -/
def mk' {γ} [semiring α] [ring γ] (f : α →* γ) (map_add : ∀ a b : α, f (a + b) = f a + f b) :
α →+* γ :=
{ to_fun := f,
.. add_monoid_hom.mk' f map_add, .. f }
end ring_hom
/-- A commutative ring is a `ring` with commutative multiplication. -/
@[protect_proj, ancestor ring comm_semigroup]
class comm_ring (α : Type u) extends ring α, comm_semigroup α
@[priority 100] -- see Note [lower instance priority]
instance comm_ring.to_comm_semiring [s : comm_ring α] : comm_semiring α :=
{ mul_zero := mul_zero, zero_mul := zero_mul, ..s }
section comm_ring
variables [comm_ring α] {a b c : α}
/-- Pullback a `ring` instance along an injective function. -/
protected def function.injective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β]
[has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) :
comm_ring β :=
{ .. hf.ring f zero one add mul neg, .. hf.comm_semigroup f mul }
/-- Pullback a `ring` instance along an injective function. -/
protected def function.surjective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β]
[has_neg β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) :
comm_ring β :=
{ .. hf.ring f zero one add mul neg, .. hf.comm_semigroup f mul }
local attribute [simp] add_assoc add_comm add_left_comm mul_comm
theorem dvd_neg_of_dvd (h : a ∣ b) : (a ∣ -b) :=
dvd.elim h
(assume c, assume : b = a * c,
dvd.intro (-c) (by simp [this]))
theorem dvd_of_dvd_neg (h : a ∣ -b) : (a ∣ b) :=
let t := dvd_neg_of_dvd h in by rwa neg_neg at t
theorem dvd_neg_iff_dvd (a b : α) : (a ∣ -b) ↔ (a ∣ b) :=
⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩
theorem neg_dvd_of_dvd (h : a ∣ b) : -a ∣ b :=
dvd.elim h
(assume c, assume : b = a * c,
dvd.intro (-c) (by simp [this]))
theorem dvd_of_neg_dvd (h : -a ∣ b) : a ∣ b :=
let t := neg_dvd_of_dvd h in by rwa neg_neg at t
theorem neg_dvd_iff_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) :=
⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩
theorem dvd_sub (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b - c :=
dvd_add h₁ (dvd_neg_of_dvd h₂)
theorem dvd_add_iff_left (h : a ∣ c) : a ∣ b ↔ a ∣ b + c :=
⟨λh₂, dvd_add h₂ h, λH, by have t := dvd_sub H h; rwa add_sub_cancel at t⟩
theorem dvd_add_iff_right (h : a ∣ b) : a ∣ c ↔ a ∣ b + c :=
by rw add_comm; exact dvd_add_iff_left h
theorem two_dvd_bit1 : 2 ∣ bit1 a ↔ (2 : α) ∣ 1 := (dvd_add_iff_right (@two_dvd_bit0 _ _ a)).symm
/-- Representation of a difference of two squares in a commutative ring as a product. -/
theorem mul_self_sub_mul_self (a b : α) : a * a - b * b = (a + b) * (a - b) :=
by rw [add_mul, mul_sub, mul_sub, mul_comm a b, sub_add_sub_cancel]
lemma mul_self_sub_one (a : α) : a * a - 1 = (a + 1) * (a - 1) :=
by rw [← mul_self_sub_mul_self, mul_one]
/-- An element a of a commutative ring divides the additive inverse of an element b iff a
divides b. -/
@[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) :=
⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩
/-- The additive inverse of an element a of a commutative ring divides another element b iff a
divides b. -/
@[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) :=
⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩
/-- If an element a divides another element c in a commutative ring, a divides the sum of another
element b with c iff a divides b. -/
theorem dvd_add_left (h : a ∣ c) : a ∣ b + c ↔ a ∣ b :=
(dvd_add_iff_left h).symm
/-- If an element a divides another element b in a commutative ring, a divides the sum of b and
another element c iff a divides c. -/
theorem dvd_add_right (h : a ∣ b) : a ∣ b + c ↔ a ∣ c :=
(dvd_add_iff_right h).symm
/-- An element a divides the sum a + b if and only if a divides b.-/
@[simp] lemma dvd_add_self_left {a b : α} : a ∣ a + b ↔ a ∣ b :=
dvd_add_right (dvd_refl a)
/-- An element a divides the sum b + a if and only if a divides b.-/
@[simp] lemma dvd_add_self_right {a b : α} : a ∣ b + a ↔ a ∣ b :=
dvd_add_left (dvd_refl a)
/-- Vieta's formula for a quadratic equation, relating the coefficients of the polynomial with
its roots. This particular version states that if we have a root `x` of a monic quadratic
polynomial, then there is another root `y` such that `x + y` is negative the `a_1` coefficient
and `x * y` is the `a_0` coefficient. -/
lemma Vieta_formula_quadratic {b c x : α} (h : x * x - b * x + c = 0) :
∃ y : α, y * y - b * y + c = 0 ∧ x + y = b ∧ x * y = c :=
begin
have : c = -(x * x - b * x) := (neg_eq_of_add_eq_zero h).symm,
have : c = x * (b - x), by subst this; simp [mul_sub, mul_comm],
refine ⟨b - x, _, by simp, by rw this⟩,
rw [this, sub_add, ← sub_mul, sub_self]
end
lemma dvd_mul_sub_mul {k a b x y : α} (hab : k ∣ a - b) (hxy : k ∣ x - y) :
k ∣ a * x - b * y :=
begin
convert dvd_add (dvd_mul_of_dvd_right hxy a) (dvd_mul_of_dvd_left hab y),
rw [mul_sub_left_distrib, mul_sub_right_distrib],
simp only [sub_eq_add_neg, add_assoc, neg_add_cancel_left],
end
lemma dvd_iff_dvd_of_dvd_sub {a b c : α} (h : a ∣ (b - c)) : (a ∣ b ↔ a ∣ c) :=
begin
split,
{ intro h',
convert dvd_sub h' h,
exact eq.symm (sub_sub_self b c) },
{ intro h',
convert dvd_add h h',
exact eq_add_of_sub_eq rfl }
end
end comm_ring
lemma succ_ne_self [ring α] [nontrivial α] (a : α) : a + 1 ≠ a :=
λ h, one_ne_zero ((add_right_inj a).mp (by simp [h]))
lemma pred_ne_self [ring α] [nontrivial α] (a : α) : a - 1 ≠ a :=
λ h, one_ne_zero (neg_injective ((add_right_inj a).mp (by { convert h, simp })))
/-- A domain is a ring with no zero divisors, i.e. satisfying
the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain
is an integral domain without assuming commutativity of multiplication. -/
@[protect_proj] class domain (α : Type u) extends ring α, nontrivial α :=
(eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0)
section domain
variable [domain α]
@[priority 100] -- see Note [lower instance priority]
instance domain.to_no_zero_divisors : no_zero_divisors α :=
⟨domain.eq_zero_or_eq_zero_of_mul_eq_zero⟩
@[priority 100] -- see Note [lower instance priority]
instance domain.to_cancel_monoid_with_zero : cancel_monoid_with_zero α :=
{ mul_left_cancel_of_ne_zero := λ a b c ha,
by { rw [← sub_eq_zero, ← mul_sub], simp [ha, sub_eq_zero] },
mul_right_cancel_of_ne_zero := λ a b c hb,
by { rw [← sub_eq_zero, ← sub_mul], simp [hb, sub_eq_zero] },
.. (infer_instance : semiring α) }
/-- Pullback a `domain` instance along an injective function. -/
protected def function.injective.domain [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β]
(f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) :
domain β :=
{ .. hf.ring f zero one add mul neg, .. pullback_nonzero f zero one,
.. hf.no_zero_divisors f zero mul }
end domain
/-!
### Integral domains
-/
/-- An integral domain is a commutative ring with no zero divisors, i.e. satisfying the condition
`a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, an integral domain is a domain with commutative
multiplication. -/
@[protect_proj, ancestor comm_ring domain]
class integral_domain (α : Type u) extends comm_ring α, domain α
section integral_domain
variables [integral_domain α] {a b c d e : α}
@[priority 100] -- see Note [lower instance priority]
instance integral_domain.to_comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero α :=
{ ..comm_semiring.to_comm_monoid_with_zero, ..domain.to_cancel_monoid_with_zero }
/-- Pullback an `integral_domain` instance along an injective function. -/
protected def function.injective.integral_domain [has_zero β] [has_one β] [has_add β]
[has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) :
integral_domain β :=
{ .. hf.comm_ring f zero one add mul neg, .. hf.domain f zero one add mul neg }
lemma mul_self_eq_mul_self_iff {a b : α} : a * a = b * b ↔ a = b ∨ a = -b :=
by rw [← sub_eq_zero, mul_self_sub_mul_self, mul_eq_zero, or_comm, sub_eq_zero,
add_eq_zero_iff_eq_neg]
lemma mul_self_eq_one_iff {a : α} : a * a = 1 ↔ a = 1 ∨ a = -1 :=
by rw [← mul_self_eq_mul_self_iff, one_mul]
/-- In the unit group of an integral domain, a unit is its own inverse iff the unit is one or
one's additive inverse. -/
lemma units.inv_eq_self_iff (u : units α) : u⁻¹ = u ↔ u = 1 ∨ u = -1 :=
by { rw inv_eq_iff_mul_eq_one, simp only [units.ext_iff], push_cast, exact mul_self_eq_one_iff }
end integral_domain
namespace ring
variables [ring R]
open_locale classical
/-- Introduce a function `inverse` on a ring `R`, which sends `x` to `x⁻¹` if `x` is invertible and
to `0` otherwise. This definition is somewhat ad hoc, but one needs a fully (rather than partially)
defined inverse function for some purposes, including for calculus. -/
noncomputable def inverse : R → R :=
λ x, if h : is_unit x then (((classical.some h)⁻¹ : units R) : R) else 0
/-- By definition, if `x` is invertible then `inverse x = x⁻¹`. -/
@[simp] lemma inverse_unit (a : units R) : inverse (a : R) = (a⁻¹ : units R) :=
begin
simp [is_unit_unit, inverse],
exact units.inv_unique (classical.some_spec (is_unit_unit a)),
end
/-- By definition, if `x` is not invertible then `inverse x = 0`. -/
@[simp] lemma inverse_non_unit (x : R) (h : ¬(is_unit x)) : inverse x = 0 := dif_neg h
end ring
/-- A predicate to express that a ring is an integral domain.
This is mainly useful because such a predicate does not contain data,
and can therefore be easily transported along ring isomorphisms. -/
structure is_integral_domain (R : Type u) [ring R] extends nontrivial R : Prop :=
(mul_comm : ∀ (x y : R), x * y = y * x)
(eq_zero_or_eq_zero_of_mul_eq_zero : ∀ x y : R, x * y = 0 → x = 0 ∨ y = 0)
-- The linter does not recognize that is_integral_domain.to_nontrivial is a structure
-- projection, disable it
attribute [nolint def_lemma doc_blame] is_integral_domain.to_nontrivial
/-- Every integral domain satisfies the predicate for integral domains. -/
lemma integral_domain.to_is_integral_domain (R : Type u) [integral_domain R] :
is_integral_domain R :=
{ .. (‹_› : integral_domain R) }
/-- If a ring satisfies the predicate for integral domains,
then it can be endowed with an `integral_domain` instance
whose data is definitionally equal to the existing data. -/
def is_integral_domain.to_integral_domain (R : Type u) [ring R] (h : is_integral_domain R) :
integral_domain R :=
{ .. (‹_› : ring R), .. (‹_› : is_integral_domain R) }
namespace semiconj_by
@[simp] lemma add_right [distrib R] {a x y x' y' : R}
(h : semiconj_by a x y) (h' : semiconj_by a x' y') :
semiconj_by a (x + x') (y + y') :=
by simp only [semiconj_by, left_distrib, right_distrib, h.eq, h'.eq]
@[simp] lemma add_left [distrib R] {a b x y : R}
(ha : semiconj_by a x y) (hb : semiconj_by b x y) :
semiconj_by (a + b) x y :=
by simp only [semiconj_by, left_distrib, right_distrib, ha.eq, hb.eq]
variables [ring R] {a b x y x' y' : R}
lemma neg_right (h : semiconj_by a x y) : semiconj_by a (-x) (-y) :=
by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm]
@[simp] lemma neg_right_iff : semiconj_by a (-x) (-y) ↔ semiconj_by a x y :=
⟨λ h, neg_neg x ▸ neg_neg y ▸ h.neg_right, semiconj_by.neg_right⟩
lemma neg_left (h : semiconj_by a x y) : semiconj_by (-a) x y :=
by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm]
@[simp] lemma neg_left_iff : semiconj_by (-a) x y ↔ semiconj_by a x y :=
⟨λ h, neg_neg a ▸ h.neg_left, semiconj_by.neg_left⟩
@[simp] lemma neg_one_right (a : R) : semiconj_by a (-1) (-1) :=
(one_right a).neg_right
@[simp] lemma neg_one_left (x : R) : semiconj_by (-1) x x :=
(semiconj_by.one_left x).neg_left
@[simp] lemma sub_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') :
semiconj_by a (x - x') (y - y') :=
h.add_right h'.neg_right
@[simp] lemma sub_left (ha : semiconj_by a x y) (hb : semiconj_by b x y) :
semiconj_by (a - b) x y :=
ha.add_left hb.neg_left
end semiconj_by
namespace commute
@[simp] theorem add_right [distrib R] {a b c : R} :
commute a b → commute a c → commute a (b + c) :=
semiconj_by.add_right
@[simp] theorem add_left [distrib R] {a b c : R} :
commute a c → commute b c → commute (a + b) c :=
semiconj_by.add_left
variables [ring R] {a b c : R}
theorem neg_right : commute a b → commute a (- b) := semiconj_by.neg_right
@[simp] theorem neg_right_iff : commute a (-b) ↔ commute a b := semiconj_by.neg_right_iff
theorem neg_left : commute a b → commute (- a) b := semiconj_by.neg_left
@[simp] theorem neg_left_iff : commute (-a) b ↔ commute a b := semiconj_by.neg_left_iff
@[simp] theorem neg_one_right (a : R) : commute a (-1) := semiconj_by.neg_one_right a
@[simp] theorem neg_one_left (a : R): commute (-1) a := semiconj_by.neg_one_left a
@[simp] theorem sub_right : commute a b → commute a c → commute a (b - c) := semiconj_by.sub_right
@[simp] theorem sub_left : commute a c → commute b c → commute (a - b) c := semiconj_by.sub_left
end commute
|
8787ffe8e351edb9134cea0cff09dc2caa752f23
|
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
|
/stage0/src/Init/Data/Format/Basic.lean
|
4212d3b4b2b14b21810b433f4826b77640ed65fb
|
[
"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
| 7,271
|
lean
|
/-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.Control.State
import Init.Data.Int.Basic
import Init.Data.String.Basic
namespace Std
inductive Format.FlattenBehavior where
| allOrNone
| fill
deriving Inhabited, BEq
open Format
inductive Format where
| nil : Format
| line : Format
| text : String → Format
| nest (indent : Int) : Format → Format
| append : Format → Format → Format
| group : Format → (behavior : FlattenBehavior := FlattenBehavior.allOrNone) → Format
deriving Inhabited
namespace Format
def fill (f : Format) : Format :=
group f (behavior := FlattenBehavior.fill)
@[export lean_format_append]
protected def appendEx (a b : Format) : Format :=
append a b
@[export lean_format_group]
protected def groupEx : Format → Format :=
group
instance : Append Format := ⟨Format.append⟩
instance : Coe String Format := ⟨text⟩
def join (xs : List Format) : Format :=
xs.foldl (·++·) ""
def isNil : Format → Bool
| nil => true
| _ => false
private structure SpaceResult where
foundLine : Bool := false
foundFlattenedHardLine : Bool := false
space : Nat := 0
deriving Inhabited
@[inline] private def merge (w : Nat) (r₁ : SpaceResult) (r₂ : Nat → SpaceResult) : SpaceResult :=
if r₁.space > w || r₁.foundLine then
r₁
else
let r₂ := r₂ (w - r₁.space);
{ r₂ with space := r₁.space + r₂.space }
private def spaceUptoLine : Format → Bool → Nat → SpaceResult
| nil, flatten, w => {}
| line, flatten, w => if flatten then { space := 1 } else { foundLine := true }
| text s, flatten, w =>
let p := s.posOf '\n';
let off := s.offsetOfPos p;
{ foundLine := p != s.bsize, foundFlattenedHardLine := flatten && p != s.bsize, space := off }
| append f₁ f₂, flatten, w => merge w (spaceUptoLine f₁ flatten w) (spaceUptoLine f₂ flatten)
| nest _ f, flatten, w => spaceUptoLine f flatten w
| group f _, _, w => spaceUptoLine f true w
private structure WorkItem where
f : Format
indent : Int
private structure WorkGroup where
flatten : Bool
flb : FlattenBehavior
items : List WorkItem
private partial def spaceUptoLine' : List WorkGroup → Nat → SpaceResult
| [], w => {}
| { items := [], .. }::gs, w => spaceUptoLine' gs w
| g@{ items := i::is, .. }::gs, w => merge w (spaceUptoLine i.f g.flatten w) (spaceUptoLine' ({ g with items := is }::gs))
private structure State where
out : String := ""
column : Nat := 0
private def pushGroup (flb : FlattenBehavior) (items : List WorkItem) (gs : List WorkGroup) (w : Nat) : StateM State (List WorkGroup) := do
let k := (← get).column
-- Flatten group if it + the remainder (gs) fits in the remaining space. For `fill`, measure only up to the next (ungrouped) line break.
let g := { flatten := flb == FlattenBehavior.allOrNone, flb := flb, items := items : WorkGroup }
let r := spaceUptoLine' [g] (w-k)
let r' := merge (w-k) r (spaceUptoLine' gs);
-- Prevent flattening if any item contains a hard line break, except within `fill` if it is ungrouped (=> unflattened)
return { g with flatten := !r.foundFlattenedHardLine && r'.space <= w-k }::gs
private def pushOutput (s : String) : StateM State Unit :=
modify fun st => { st with out := st.out ++ s, column := st.column + s.length }
private def pushNewline (indent : Nat) : StateM State Unit :=
modify fun st => { st with out := st.out ++ "\n".pushn ' ' indent, column := indent }
private partial def be (w : Nat) : List WorkGroup → StateM State Unit
| [] => pure ()
| { items := [], .. }::gs => be w gs
| g@{ items := i::is, .. }::gs => do
let gs' (is' : List WorkItem) := { g with items := is' }::gs;
match i.f with
| nil => be w (gs' is)
| append f₁ f₂ => be w (gs' ({ i with f := f₁ }::{ i with f := f₂ }::is))
| nest n f => be w (gs' ({ i with f := f, indent := i.indent + n }::is))
| text s =>
let p := s.posOf '\n'
if p == s.bsize then
pushOutput s
be w (gs' is)
else
pushOutput (s.extract 0 p)
pushNewline i.indent.toNat
let is := { i with f := s.extract (s.next p) s.bsize }::is
-- after a hard line break, re-evaluate whether to flatten the remaining group
pushGroup g.flb is gs w >>= be w
| line =>
match g.flb with
| FlattenBehavior.allOrNone =>
if g.flatten then
-- flatten line = text " "
pushOutput " "
be w (gs' is)
else
pushNewline i.indent.toNat
be w (gs' is)
| FlattenBehavior.fill =>
let breakHere := do
pushNewline i.indent.toNat
-- make new `fill` group and recurse
pushGroup FlattenBehavior.fill is gs w >>= be w
-- if preceding fill item fit in a single line, try to fit next one too
if g.flatten then
let gs'@(g'::_) ← pushGroup FlattenBehavior.fill is gs (w - " ".length)
| panic "unreunreachable"
if g'.flatten then
pushOutput " ";
be w gs' -- TODO: use `return`
else
breakHere
else
breakHere
| group f flb =>
if g.flatten then
-- flatten (group f) = flatten f
be w (gs' ({ i with f := f }::is))
else
pushGroup flb [{ i with f := f }] (gs' is) w >>= be w
@[inline] def bracket (l : String) (f : Format) (r : String) : Format :=
group (nest l.length $ l ++ f ++ r)
@[inline] def paren (f : Format) : Format :=
bracket "(" f ")"
@[inline] def sbracket (f : Format) : Format :=
bracket "[" f "]"
@[inline] def bracketFill (l : String) (f : Format) (r : String) : Format :=
fill (nest l.length $ l ++ f ++ r)
def defIndent := 2
def defUnicode := true
def defWidth := 120
@[export lean_format_pretty]
def pretty (f : Format) (w : Nat := defWidth) : String :=
let (_, st) := be w [{ flb := FlattenBehavior.allOrNone, flatten := false, items := [{ f := f, indent := 0 }] }] {};
st.out
end Format
class ToFormat (α : Type u) where
format : α → Format
export ToFormat (format)
def fmt {α : Type u} [ToFormat α] : α → Format := format
-- note: must take precendence over the above instance to avoid premature formatting
instance : ToFormat Format where
format f := f
instance : ToFormat String where
format s := Format.text s
def Format.joinSep {α : Type u} [ToFormat α] : List α → Format → Format
| [], sep => nil
| [a], sep => format a
| a::as, sep => format a ++ sep ++ joinSep as sep
def Format.prefixJoin {α : Type u} [ToFormat α] (pre : Format) : List α → Format
| [] => nil
| a::as => pre ++ format a ++ prefixJoin pre as
def Format.joinSuffix {α : Type u} [ToFormat α] : List α → Format → Format
| [], suffix => nil
| a::as, suffix => format a ++ suffix ++ joinSuffix as suffix
end Std
open Std
open Std.Format
|
500c6ca2114d64b0cc3a494cc66a79df9b496f63
|
fa01e273a2a9f22530e6adb1ed7d4f54bb15c8d7
|
/src/N2O/Network/Web/Default.lean
|
ecd2951eebfd2dfcb879d84b8288fe97d972874b
|
[
"LicenseRef-scancode-mit-taylor-variant",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
o89/n2o
|
4c99afb11fff0a1e3dae6b3bc8a3b7fc42c314ac
|
58c1fbf4ef892ed86bdc6b78ec9ca5a403715c2d
|
refs/heads/master
| 1,670,314,676,229
| 1,669,086,375,000
| 1,669,086,375,000
| 200,506,953
| 16
| 6
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 28
|
lean
|
import N2O.Network.Web.HTTP
|
fefbbc5565f43c50215d6f144550b381600504a4
|
74addaa0e41490cbaf2abd313a764c96df57b05d
|
/Mathlib/order/complete_boolean_algebra.lean
|
1fa1701de2b3f0ae5524788b86b8f6a07be1f971
|
[] |
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
| 4,043
|
lean
|
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
Theory of complete Boolean algebras.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.order.complete_lattice
import Mathlib.PostPort
universes u_1 l u w
namespace Mathlib
/-- A complete distributive lattice is a bit stronger than the name might
suggest; perhaps completely distributive lattice is more descriptive,
as this class includes a requirement that the lattice join
distribute over *arbitrary* infima, and similarly for the dual. -/
class complete_distrib_lattice (α : Type u_1)
extends complete_lattice α
where
infi_sup_le_sup_Inf : ∀ (a : α) (s : set α), (infi fun (b : α) => infi fun (H : b ∈ s) => a ⊔ b) ≤ a ⊔ Inf s
inf_Sup_le_supr_inf : ∀ (a : α) (s : set α), a ⊓ Sup s ≤ supr fun (b : α) => supr fun (H : b ∈ s) => a ⊓ b
theorem sup_Inf_eq {α : Type u} [complete_distrib_lattice α] {a : α} {s : set α} : a ⊔ Inf s = infi fun (b : α) => infi fun (H : b ∈ s) => a ⊔ b :=
le_antisymm (le_infi fun (i : α) => le_infi fun (h : i ∈ s) => sup_le_sup_left (Inf_le h) a)
(complete_distrib_lattice.infi_sup_le_sup_Inf a s)
theorem Inf_sup_eq {α : Type u} [complete_distrib_lattice α] {b : α} {s : set α} : Inf s ⊔ b = infi fun (a : α) => infi fun (H : a ∈ s) => a ⊔ b := sorry
theorem inf_Sup_eq {α : Type u} [complete_distrib_lattice α] {a : α} {s : set α} : a ⊓ Sup s = supr fun (b : α) => supr fun (H : b ∈ s) => a ⊓ b :=
le_antisymm (complete_distrib_lattice.inf_Sup_le_supr_inf a s)
(supr_le fun (i : α) => supr_le fun (h : i ∈ s) => inf_le_inf_left a (le_Sup h))
theorem Sup_inf_eq {α : Type u} [complete_distrib_lattice α] {b : α} {s : set α} : Sup s ⊓ b = supr fun (a : α) => supr fun (H : a ∈ s) => a ⊓ b := sorry
theorem Inf_sup_Inf {α : Type u} [complete_distrib_lattice α] {s : set α} {t : set α} : Inf s ⊔ Inf t = infi fun (p : α × α) => infi fun (H : p ∈ set.prod s t) => prod.fst p ⊔ prod.snd p := sorry
theorem Sup_inf_Sup {α : Type u} [complete_distrib_lattice α] {s : set α} {t : set α} : Sup s ⊓ Sup t = supr fun (p : α × α) => supr fun (H : p ∈ set.prod s t) => prod.fst p ⊓ prod.snd p := sorry
protected instance complete_distrib_lattice.bounded_distrib_lattice {α : Type u} [d : complete_distrib_lattice α] : bounded_distrib_lattice α :=
bounded_distrib_lattice.mk complete_distrib_lattice.sup complete_distrib_lattice.le complete_distrib_lattice.lt
complete_distrib_lattice.le_refl complete_distrib_lattice.le_trans complete_distrib_lattice.le_antisymm
complete_distrib_lattice.le_sup_left complete_distrib_lattice.le_sup_right complete_distrib_lattice.sup_le
complete_distrib_lattice.inf complete_distrib_lattice.inf_le_left complete_distrib_lattice.inf_le_right
complete_distrib_lattice.le_inf sorry complete_distrib_lattice.top complete_distrib_lattice.le_top
complete_distrib_lattice.bot complete_distrib_lattice.bot_le
/-- A complete boolean algebra is a completely distributive boolean algebra. -/
class complete_boolean_algebra (α : Type u_1)
extends boolean_algebra α, complete_distrib_lattice α
where
theorem compl_infi {α : Type u} {ι : Sort w} [complete_boolean_algebra α] {f : ι → α} : infi fᶜ = supr fun (i : ι) => f iᶜ :=
le_antisymm (compl_le_of_compl_le (le_infi fun (i : ι) => compl_le_of_compl_le (le_supr (compl ∘ f) i)))
(supr_le fun (i : ι) => compl_le_compl (infi_le f i))
theorem compl_supr {α : Type u} {ι : Sort w} [complete_boolean_algebra α] {f : ι → α} : supr fᶜ = infi fun (i : ι) => f iᶜ := sorry
theorem compl_Inf {α : Type u} [complete_boolean_algebra α] {s : set α} : Inf sᶜ = supr fun (i : α) => supr fun (H : i ∈ s) => iᶜ := sorry
theorem compl_Sup {α : Type u} [complete_boolean_algebra α] {s : set α} : Sup sᶜ = infi fun (i : α) => infi fun (H : i ∈ s) => iᶜ := sorry
|
45ef38daa1981bc6392e81823c058612ee863c9c
|
d406927ab5617694ec9ea7001f101b7c9e3d9702
|
/src/tactic/interval_cases.lean
|
9cffa15e8d41a9ecf6730414b4e43f15b6fe7993
|
[
"Apache-2.0"
] |
permissive
|
alreadydone/mathlib
|
dc0be621c6c8208c581f5170a8216c5ba6721927
|
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
|
refs/heads/master
| 1,685,523,275,196
| 1,670,184,141,000
| 1,670,184,141,000
| 287,574,545
| 0
| 0
|
Apache-2.0
| 1,670,290,714,000
| 1,597,421,623,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 11,244
|
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 tactic.fin_cases
import data.fin.interval -- These imports aren't required to compile this file,
import data.int.interval -- but they are needed at the use site for the tactic to work
import data.pnat.interval -- (on values of type fin/int/pnat)
import data.pnat.basic
/-!
# Case bash on variables in finite intervals
This file provides the tactic `interval_cases`. `interval_cases n` will:
1. inspect hypotheses looking for lower and upper bounds of the form `a ≤ n` and `n < b`
(in `ℕ`, `ℤ`, `ℕ+`, bounds of the form `a < n` and `n ≤ b` are also allowed),
and also makes use of lower and upper bounds found via `le_top` and `bot_le`
(so for example if `n : ℕ`, then the bound `0 ≤ n` is automatically found).
2. call `fin_cases` on the synthesised hypothesis `n ∈ set.Ico a b`,
assuming an appropriate `fintype` instance can be found for the type of `n`.
The variable `n` can belong to any type `α`, with the following restrictions:
* only bounds on which `expr.to_rat` succeeds will be considered "explicit" (TODO: generalise this?)
* an instance of `decidable_eq α` is available,
* an explicit lower bound can be found among the hypotheses, or from `bot_le n`,
* an explicit upper bound can be found among the hypotheses, or from `le_top n`,
* if multiple bounds are located, an instance of `linear_order α` is available, and
* an instance of `fintype set.Ico l u` is available for the relevant bounds.
You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`,
where the hypotheses should be of the form `hl : a ≤ n` and `hu : n < b`. In that case,
`interval_cases` calls `fin_cases` on the resulting hypothesis `h : n ∈ set.Ico a b`.
-/
open set
namespace tactic
namespace interval_cases
/--
If `e` easily implies `(%%n < %%b)`
for some explicit `b`,
return that proof.
-/
-- We use `expr.to_rat` merely to decide if an `expr` is an explicit number.
-- It would be more natural to use `expr.to_int`, but that hasn't been implemented.
meta def gives_upper_bound (n e : expr) : tactic expr :=
do t ← infer_type e,
match t with
| `(%%n' < %%b) := do guard (n = n'), b ← b.to_rat, return e
| `(%%b > %%n') := do guard (n = n'), b ← b.to_rat, return e
| `(%%n' ≤ %%b) := do
guard (n = n'),
b ← b.to_rat,
tn ← infer_type n,
match tn with
| `(ℕ) := to_expr ``(nat.lt_add_one_iff.mpr %%e)
| `(ℕ+) := to_expr ``(pnat.lt_add_one_iff.mpr %%e)
| `(ℤ) := to_expr ``(int.lt_add_one_iff.mpr %%e)
| _ := failed
end
| `(%%b ≥ %%n') := do
guard (n = n'),
b ← b.to_rat,
tn ← infer_type n,
match tn with
| `(ℕ) := to_expr ``(nat.lt_add_one_iff.mpr %%e)
| `(ℕ+) := to_expr ``(pnat.lt_add_one_iff.mpr %%e)
| `(ℤ) := to_expr ``(int.lt_add_one_iff.mpr %%e)
| _ := failed
end
| _ := failed
end
/--
If `e` easily implies `(%%n ≥ %%b)`
for some explicit `b`,
return that proof.
-/
meta def gives_lower_bound (n e : expr) : tactic expr :=
do t ← infer_type e,
match t with
| `(%%n' ≥ %%b) := do guard (n = n'), b ← b.to_rat, return e
| `(%%b ≤ %%n') := do guard (n = n'), b ← b.to_rat, return e
| `(%%n' > %%b) := do
guard (n = n'),
b ← b.to_rat,
tn ← infer_type n,
match tn with
| `(ℕ) := to_expr ``(nat.add_one_le_iff.mpr %%e)
| `(ℕ+) := to_expr ``(pnat.add_one_le_iff.mpr %%e)
| `(ℤ) := to_expr ``(int.add_one_le_iff.mpr %%e)
| _ := failed
end
| `(%%b < %%n') := do
guard (n = n'),
b ← b.to_rat,
tn ← infer_type n,
match tn with
| `(ℕ) := to_expr ``(nat.add_one_le_iff.mpr %%e)
| `(ℕ+) := to_expr ``(pnat.add_one_le_iff.mpr %%e)
| `(ℤ) := to_expr ``(int.add_one_le_iff.mpr %%e)
| _ := failed
end
| _ := failed
end
/-- Combine two upper bounds. -/
meta def combine_upper_bounds : option expr → option expr → tactic (option expr)
| none none := return none
| (some prf) none := return $ some prf
| none (some prf) := return $ some prf
| (some prf₁) (some prf₂) :=
do option.some <$> to_expr ``(lt_min %%prf₁ %%prf₂)
/-- Combine two lower bounds. -/
meta def combine_lower_bounds : option expr → option expr → tactic (option expr)
| none none := return $ none
| (some prf) none := return $ some prf
| none (some prf) := return $ some prf
| (some prf₁) (some prf₂) :=
do option.some <$> to_expr ``(max_le %%prf₂ %%prf₁)
/-- Inspect a given expression, using it to update a set of upper and lower bounds on `n`. -/
meta def update_bounds (n : expr) (bounds : option expr × option expr) (e : expr) :
tactic (option expr × option expr) :=
do nlb ← try_core $ gives_lower_bound n e,
nub ← try_core $ gives_upper_bound n e,
clb ← combine_lower_bounds bounds.1 nlb,
cub ← combine_upper_bounds bounds.2 nub,
return (clb, cub)
/--
Attempt to find a lower bound for the variable `n`, by evaluating `bot_le n`.
-/
meta def initial_lower_bound (n : expr) : tactic expr :=
do e ← to_expr ``(@bot_le _ _ _ %%n),
t ← infer_type e,
match t with
| `(%%b ≤ %%n) := do return e
| _ := failed
end
/--
Attempt to find an upper bound for the variable `n`, by evaluating `le_top n`.
-/
meta def initial_upper_bound (n : expr) : tactic expr :=
do e ← to_expr ``(@le_top _ _ _ %%n),
match e with
| `(%%n ≤ %%b) := do
tn ← infer_type n,
e ← match tn with
| `(ℕ) := to_expr ``(nat.add_one_le_iff.mpr %%e)
| `(ℕ+) := to_expr ``(pnat.add_one_le_iff.mpr %%e)
| `(ℤ) := to_expr ``(int.add_one_le_iff.mpr %%e)
| _ := failed
end,
return e
| _ := failed
end
/-- Inspect the local hypotheses for upper and lower bounds on a variable `n`. -/
meta def get_bounds (n : expr) : tactic (expr × expr) :=
do
hl ← try_core (initial_lower_bound n),
hu ← try_core (initial_upper_bound n),
lc ← local_context,
r ← lc.mfoldl (update_bounds n) (hl, hu),
match r with
| (_, none) := fail "No upper bound located."
| (none, _) := fail "No lower bound located."
| (some lb_prf, some ub_prf) := return (lb_prf, ub_prf)
end
/-- The finset of elements of a set `s` for which we have `fintype s`. -/
def set_elems {α} [decidable_eq α] (s : set α) [fintype s] : finset α :=
(fintype.elems s).image subtype.val
/-- Each element of `s` is a member of `set_elems s`. -/
lemma mem_set_elems {α} [decidable_eq α] (s : set α) [fintype s] {a : α} (h : a ∈ s) :
a ∈ set_elems s :=
finset.mem_image.2 ⟨⟨a, h⟩, fintype.complete _, rfl⟩
end interval_cases
open interval_cases
/-- Call `fin_cases` on membership of the finset built from
an `Ico` interval corresponding to a lower and an upper bound.
Here `hl` should be an expression of the form `a ≤ n`, for some explicit `a`, and
`hu` should be of the form `n < b`, for some explicit `b`.
By default `interval_cases_using` automatically generates a name for the new hypothesis. The name
can be specified via the optional argument `n`.
-/
meta def interval_cases_using (hl hu : expr) (n : option name) : tactic unit :=
to_expr ``(mem_set_elems (Ico _ _) ⟨%%hl, %%hu⟩) >>=
(if hn : n.is_some then
note (option.get hn)
else
note_anon none) >>= fin_cases_at none none
setup_tactic_parser
namespace interactive
local postfix (name := parser.optional) `?`:9001 := optional
/--
`interval_cases n` searches for upper and lower bounds on a variable `n`,
and if bounds are found,
splits into separate cases for each possible value of `n`.
As an example, in
```
example (n : ℕ) (w₁ : n ≥ 3) (w₂ : n < 5) : n = 3 ∨ n = 4 :=
begin
interval_cases n,
all_goals {simp}
end
```
after `interval_cases n`, the goals are `3 = 3 ∨ 3 = 4` and `4 = 3 ∨ 4 = 4`.
You can also explicitly specify a lower and upper bound to use,
as `interval_cases using hl hu`.
The hypotheses should be in the form `hl : a ≤ n` and `hu : n < b`,
in which case `interval_cases` calls `fin_cases` on the resulting fact `n ∈ set.Ico a b`.
You can specify a name `h` for the new hypothesis,
as `interval_cases n with h` or `interval_cases n using hl hu with h`.
-/
meta def interval_cases (n : parse texpr?)
(bounds : parse (tk "using" *> (prod.mk <$> ident <*> ident))?)
(lname : parse (tk "with" *> ident)?) :
tactic unit :=
do
if h : n.is_some then (do
guard bounds.is_none <|>
fail "Do not use the `using` keyword if specifying the variable explicitly.",
n ← to_expr (option.get h),
(hl, hu) ← get_bounds n,
tactic.interval_cases_using hl hu lname)
else if h' : bounds.is_some then (do
[hl, hu] ← [(option.get h').1, (option.get h').2].mmap get_local,
tactic.interval_cases_using hl hu lname)
else
fail ("Call `interval_cases n` (specifying a variable), or `interval_cases lb ub`\n" ++
"(specifying a lower bound and upper bound on the same variable).")
/--
`interval_cases n` searches for upper and lower bounds on a variable `n`,
and if bounds are found,
splits into separate cases for each possible value of `n`.
As an example, in
```
example (n : ℕ) (w₁ : n ≥ 3) (w₂ : n < 5) : n = 3 ∨ n = 4 :=
begin
interval_cases n,
all_goals {simp}
end
```
after `interval_cases n`, the goals are `3 = 3 ∨ 3 = 4` and `4 = 3 ∨ 4 = 4`.
You can also explicitly specify a lower and upper bound to use,
as `interval_cases using hl hu`.
The hypotheses should be in the form `hl : a ≤ n` and `hu : n < b`,
in which case `interval_cases` calls `fin_cases` on the resulting fact `n ∈ set.Ico a b`.
You can also explicitly specify a name to use for the hypothesis added,
as `interval_cases n with hn` or `interval_cases n using hl hu with hn`.
In particular, `interval_cases n`
1) inspects hypotheses looking for lower and upper bounds of the form `a ≤ n` and `n < b`
(although in `ℕ`, `ℤ`, and `ℕ+` bounds of the form `a < n` and `n ≤ b` are also allowed),
and also makes use of lower and upper bounds found via `le_top` and `bot_le`
(so for example if `n : ℕ`, then the bound `0 ≤ n` is found automatically), then
2) calls `fin_cases` on the synthesised hypothesis `n ∈ set.Ico a b`,
assuming an appropriate `fintype` instance can be found for the type of `n`.
The variable `n` can belong to any type `α`, with the following restrictions:
* only bounds on which `expr.to_rat` succeeds will be considered "explicit" (TODO: generalise this?)
* an instance of `decidable_eq α` is available,
* an explicit lower bound can be found amongst the hypotheses, or from `bot_le n`,
* an explicit upper bound can be found amongst the hypotheses, or from `le_top n`,
* if multiple bounds are located, an instance of `linear_order α` is available, and
* an instance of `fintype set.Ico l u` is available for the relevant bounds.
-/
add_tactic_doc
{ name := "interval_cases",
category := doc_category.tactic,
decl_names := [`tactic.interactive.interval_cases],
tags := ["case bashing"] }
end interactive
end tactic
|
84605979b5a7c109e1ec0625484763e987c3860b
|
31f556cdeb9239ffc2fad8f905e33987ff4feab9
|
/src/Lean/Compiler/LCNF/Simp/DiscrM.lean
|
2117a67dd07452cf4c7c9469f58644da35a6bb39
|
[
"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
| 3,215
|
lean
|
/-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Compiler.LCNF.CompilerM
import Lean.Compiler.LCNF.Types
import Lean.Compiler.LCNF.InferType
import Lean.Compiler.LCNF.Simp.Basic
namespace Lean.Compiler.LCNF
namespace Simp
structure DiscrM.Context where
/--
A mapping from discriminant to constructor application it is equal to in the current context.
-/
discrCtorMap : FVarIdMap Expr := {}
/--
A mapping from constructor application to discriminant it is equal to in the current context.
-/
ctorDiscrMap : PersistentExprMap FVarId := {}
/--
Helper monad for tracking mappings from discriminant to constructor applications and back.
The combinator `withDiscrCtor` should be used when visiting `cases` alternatives.
-/
abbrev DiscrM := ReaderT DiscrM.Context CompilerM
/--
This method uses `findExpr`, and if the result is a free variable, checks whether it is in the map `discrCtorMap`.
We use this method when simplifying projections and cases-constructor.
-/
def findCtor (e : Expr) : DiscrM Expr := do
let e ← findExpr e
let .fvar fvarId := e | return e
let some ctor := (← read).discrCtorMap.find? fvarId | return e
return ctor
/--
If `type` is an inductive datatype, return its universe levels and parameters.
-/
def getIndInfo? (type : Expr) : CoreM (Option (List Level × Array Expr)) := do
let type := type.headBeta
let .const declName us := type.getAppFn | return none
let .inductInfo info ← getConstInfo declName | return none
unless type.getAppNumArgs >= info.numParams do return none
return some (us, type.getAppArgs[:info.numParams])
/--
Execute `x` with the information that `discr = ctorName ctorFields`.
We use this information to simplify nested cases on the same discriminant.
-/
def withDiscrCtorImp (discr : FVarId) (ctorName : Name) (ctorFields : Array Param) (x : DiscrM α) : DiscrM α := do
let ctorInfo ← getConstInfoCtor ctorName
let fieldArgs := ctorFields.map (.fvar ·.fvarId)
if let some (us, params) ← getIndInfo? (← getType discr) then
let ctor := mkAppN (mkAppN (mkConst ctorName us) params) fieldArgs
withReader (fun ctx => { ctx with discrCtorMap := ctx.discrCtorMap.insert discr ctor, ctorDiscrMap := ctx.ctorDiscrMap.insert ctor discr }) do
x
else
-- For the discrCtor map, the constructor parameters are irrelevant for optimizations that use this information
let ctor := mkAppN (mkAppN (mkConst ctorName) (mkArray ctorInfo.numParams erasedExpr)) fieldArgs
withReader (fun ctx => { ctx with discrCtorMap := ctx.discrCtorMap.insert discr ctor }) do
x
@[inline, inheritDoc withDiscrCtorImp] def withDiscrCtor [MonadFunctorT DiscrM m] (discr : FVarId) (ctorName : Name) (ctorFields : Array Param) : m α → m α :=
monadMap (m := DiscrM) <| withDiscrCtorImp discr ctorName ctorFields
def simpCtorDiscrCore? (e : Expr) : DiscrM (Option Expr) := do
let some discr := (← read).ctorDiscrMap.find? e | return none
unless (← compatibleTypes (← getType discr) (← inferType e)) do return none
return some <| .fvar discr
end Simp
end Lean.Compiler.LCNF
|
e601a9faa5ef425040916bf1bb1e76e9a6100268
|
9c1ad797ec8a5eddb37d34806c543602d9a6bf70
|
/category.lean
|
4a50af076022345e94c8157a3adbaa76b751568d
|
[] |
no_license
|
timjb/lean-category-theory
|
816eefc3a0582c22c05f4ee1c57ed04e57c0982f
|
12916cce261d08bb8740bc85e0175b75fb2a60f4
|
refs/heads/master
| 1,611,078,926,765
| 1,492,080,000,000
| 1,492,080,000,000
| 88,348,246
| 0
| 0
| null | 1,492,262,499,000
| 1,492,262,498,000
| null |
UTF-8
|
Lean
| false
| false
| 2,510
|
lean
|
-- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Stephen Morgan, Scott Morrison
import .tactics
/-
-- We've decided that Obj and Hom should be fields of Category, rather than parameters.
-- Mostly this is for the sake of simpler signatures, but it's possible that it is not the right choice.
-- Functor and NaturalTransformation are each parameterized by both their source and target.
-/
namespace tqft.categories
structure {u v} Category :=
(Obj : Type u)
(Hom : Obj → Obj → Type v)
(identity : Π X : Obj, Hom X X)
(compose : Π { X Y Z : Obj }, Hom X Y → Hom Y Z → Hom X Z)
(left_identity : ∀ { X Y : Obj } (f : Hom X Y), compose (identity X) f = f)
(right_identity : ∀ { X Y : Obj } (f : Hom X Y), compose f (identity Y) = f)
(associativity : ∀ { W X Y Z : Obj } (f : Hom W X) (g : Hom X Y) (h : Hom Y Z),
compose (compose f g) h = compose f (compose g h))
attribute [simp] Category.left_identity
attribute [simp] Category.right_identity
attribute [ematch] Category.associativity
attribute [pointwise] Category.identity
-- instance Category_to_Hom : has_coe_to_fun Category :=
-- { F := λ C, C.Obj → C.Obj → Type v,
-- coe := Category.Hom }
@[ematch] lemma Category.identity_idempotent
( C : Category )
( X : C.Obj ) : C.identity X = C.compose (C.identity X) (C.identity X) := ♮
open Category
-- TODO, eventually unify this code with the corresponding code for Graph, perhaps just by making Categories Graphs.
inductive {u v} morphism_path { C : Category.{u v} } : Obj C → Obj C → Type (max u v)
| nil : Π ( h : C.Obj ), morphism_path h h
| cons : Π { h s t : C.Obj } ( e : C.Hom h s ) ( l : morphism_path s t ), morphism_path h t
notation a :: b := morphism_path.cons a b
notation `c[` l:(foldr `, ` (h t, morphism_path.cons h t) morphism_path.nil _ `]`) := l
definition {u v} concatenate_paths
{ C : Category.{u v} } :
Π { x y z : C.Obj }, morphism_path x y → morphism_path y z → morphism_path x z
| ._ ._ _ (morphism_path.nil _) q := q
| ._ ._ _ (@morphism_path.cons ._ _ _ _ e p') q := morphism_path.cons e (concatenate_paths p' q)
definition {u v} Category.compose_path ( C : Category.{u v} ) : Π { X Y : C.Obj }, morphism_path X Y → C.Hom X Y
| X ._ (morphism_path.nil ._) := C.identity X
| _ _ (@morphism_path.cons ._ ._ _ ._ e p) := C.compose e (Category.compose_path p)
end tqft.categories
|
5d80654c7e3cd66f553952a44d91d064875857d9
|
3f48345ac9bbaa421714efc9872a0409379bb4ae
|
/src/help_functions.lean
|
2f2bec1d2cb077ec197672d19be0a130cc0907c3
|
[] |
no_license
|
QaisHamarneh/Coalgebra-in-Lean
|
b4318ee6d83780e5c734eb78fed98b1fe8016f7e
|
bd0452df98bc64b608e5dfd7babc42c301bb6a46
|
refs/heads/master
| 1,663,371,200,241
| 1,661,004,695,000
| 1,661,004,695,000
| 209,798,828
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 10,377
|
lean
|
import category_theory.category
import category_theory.types
import tactic.tidy
namespace help_functions
universe u
open classical function set
variables {A B C : Type u}
lemma eq_in_set {A : Type u} {S: set A} {a b: S}
: a.val = b.val ↔ a = b :=
by {cases a, cases b, dsimp at *, simp at *}
@[simp , tidy] def inclusion (S : set A)
: S → A := λ s , s
notation S ` ↪ ` A := @inclusion A S
@[simp , tidy] lemma inclusion_id
(A : Type u) (S : set A) (s : S)
: (inclusion S) s = s := by simp
@[simp , tidy] lemma inj_inclusion (A : Type u) (S : set A)
: injective (inclusion S) := by tidy
@[simp , tidy] lemma comp_inclusion (A : Type u) (S T: set A) (h: S ⊆ T)
: (S ↪ A) = (T ↪ A) ∘ (set.inclusion h)
:= by tidy
noncomputable def graph_to_map
(G : A → B → Prop)
(h : ∀ a : A , ∃! b : B, G a b) : A → B :=
λ a , some (h a)
def map_to_graph (f : A → B): set (A × B ):= λ r, r.2 = f r.1
lemma bij_map_to_graph_fst (f : A → B) :
let π₁ : (map_to_graph f) → A := λ r , r.val.1 in
bijective π₁ :=
begin
let R : set (A × B) := map_to_graph f,
let π₁ : R → A := λ r , r.val.1,
have inj : injective π₁ :=
begin
assume a₁ a₂ (πa₁_πa₂ : a₁.val.1 = a₂.val.1),
have a1_p : a₁.val.2 = f a₁.val.1 := a₁.property,
have a2_p : a₂.val.2 = f a₂.val.1 := a₂.property,
have a_a : f a₁.val.1 = f a₂.val.1 := by tidy,
have a2_p : a₁.val.2 = a₂.val.2 := by simp [a1_p, a2_p, a_a],
tidy
end,
have sur : surjective π₁ :=
begin
intro a,
let r := (⟨a , f a⟩ : A × B),
have r_R : r ∈ R :=
have r2_fr1 : r.2 = f r.1 := by simp,
r2_fr1,
use r,
tidy
end,
exact ⟨inj, sur⟩
end
noncomputable def invrs (f : A ⟶ B) (bij : bijective f) : B ⟶ A :=
some (iff.elim_left bijective_iff_has_inverse bij)
lemma invrs_id (f : A ⟶ B) (bij : bijective f)
:
f ∘ (invrs f bij) = id :=
begin
have h0 : left_inverse (some _) f ∧ right_inverse (some _) f :=
some_spec (iff.elim_left bijective_iff_has_inverse bij),
have h1: right_inverse _ f :=
and.elim_right h0,
by tidy
end
lemma id_invrs (f : A ⟶ B) (bij : bijective f) :
(invrs f bij) ∘ f = id :=
begin
have h0 : left_inverse (some _) f ∧ right_inverse (some _) f :=
some_spec (iff.elim_left bijective_iff_has_inverse bij),
have h1: left_inverse _ f :=
and.elim_left h0,
by tidy
end
def kern (f : A ⟶ B) : A → A → Prop :=
λ a₁ a₂ , f a₁ = f a₂
def sub_kern (f : A ⟶ B) (g : A → C) : Prop :=
∀ a₁ a₂, kern f a₁ a₂ → kern g a₁ a₂
@[simp, tidy] def kern_comp (f : A ⟶ B) (g : B → C) :
sub_kern f (g ∘ f) :=
assume a b k_f,
have f_ab : f a = f b := k_f,
show g (f a) = g (f b), from by rw [f_ab]
def emptyOrNot (S : set A) : (nonempty S) ∨ ¬ (nonempty S)
:= em (nonempty S)
noncomputable def nonemptyInhabited {S : set A} (h : nonempty S)
: inhabited S
:= inhabited.mk (choice h)
lemma map_from_empty (S : set A) (B : Type u) :
(¬ ∃ s : S , true) →
∀ f₁ f₂ : S → B, f₁ = f₂ :=
assume h f₁ f₂,
show f₁ = f₂, from
have h0 : ∀ s : S , false := by tidy,
by tidy
lemma nonempty_notexists {S : set A}:
¬ nonempty S → (¬ ∃ s : S , true) :=
assume nonemp ext,
show false,
from nonemp (nonempty_of_exists ext)
lemma only_one {p q: A → Prop}
(ex_uni : ∃! a , p a)
(ex : ∃ a , p a ∧ q a)
: ∃! a , p a ∧ q a :=
let a : A := some ex_uni in
have h : _ := some_spec ex_uni,
have h1 : ∀ a₁ , p a₁ → a₁ = a :=
and.right h,
let a₁ : A := some ex in
have h2 : p a₁ ∧ q a₁ := some_spec ex,
have h3 : a₁ = a := h1 a₁ (and.left h2),
have h4 : ∀ a₂ , p a₂ ∧ q a₂ → a₂ = a₁ :=
λ a₂ pq, by rw [h3, (h1 a₂ (and.left pq))],
exists.intro a₁ ⟨ h2 , h4⟩
lemma eq_range_if_surjective (f: A ⟶ B) (g: B ⟶ C)
(sur: surjective f) : range g = range (g ∘ f):=
calc range g = image g (univ) : by simp
... = image g (range f) : by rw [range_iff_surjective.2 sur]
... = range (g ∘ f) : by tidy
lemma sub_kern_if_injective {X Y Z U : Type u}
(e : X ⟶ Y) (f : Y ⟶ U)
(g : X ⟶ Z) (m : Z ⟶ U)
(h : e ≫ f = g ≫ m) (inj: injective m) : sub_kern e g :=
begin
assume x₁ x₂ xxe,
have h01 : e x₁ = e x₂ := xxe,
have h02 : m (g x₁) = m (g x₂) :=
calc m (g x₁) = (g ≫ m) x₁ : rfl
... = (e ≫ f) x₁ : by rw h
... = f (e x₁) : rfl
... = f (e x₂) : by rw h01
... = (e ≫ f) x₂ : rfl
... = (g ≫ m) x₂ : by rw h,
exact inj h02
end
lemma eq_sets {A : Type u} {S T : set A}
: (∀a : A ,a ∈ S ↔ a ∈ T) ↔ S = T :=
begin
split,
assume h,
have h1 : ∀s : S , s.val ∈ T :=
λ s, (h s.val).1 s.property,
have h2 : ∀t : T , t.val ∈ S :=
λ t, (h t.val).2 t.property,
simp at *,
ext1 x,
split,
intros s,
exact h1 x s,
intros t,
exact h2 x t,
intro h,
intro a,
induction h,
refl
end
@[tidy] def fun_of_two_eq_sets {A B: Type u} {S T : set A}
(h: ∀a : A ,a ∈ S ↔ a ∈ T)
(f: S → B):
T → B :=
λ t ,
f ⟨t.val , (h t.val).2 t.property⟩
@[tidy] lemma eq_fun_of_eq_sets {A B: Type u} (S T : set A)
(h: ∀a : A ,a ∈ S ↔ a ∈ T)
(f: S → B):
let fT : T → B := (fun_of_two_eq_sets h f) in
∀ s , f s = fT ⟨ s.val , (h s.val).1 s.property⟩
:= by tidy
@[tidy] lemma def_of_range {A B: Type u} (T: set A)
(f: T → B) (b : B) :
(∃ (a : A) (h : a ∈ T), f ⟨a, h⟩ = b) ↔
b ∈ range f := by tidy
@[tidy] lemma eq_ranges {A B: Type u} {S T : set A}
(h: ∀a : A ,a ∈ S ↔ a ∈ T)
(f: S → B):
let fT : T → B := (fun_of_two_eq_sets h f) in
range f = range fT
:=
begin
intro fT,
have h1 : ∀b : B ,b ∈ range f ↔ b ∈ range fT :=
begin
intro b,
split,
intro bf,
let s := some bf,
have spec : f s = b := some_spec bf,
have eq : fT ⟨ s.val , (h s.val).1 s.property⟩ = f s :=
eq.symm (eq_fun_of_eq_sets S T h f s),
have ex : ∃ t : T , fT t = b :=
exists.intro
(⟨ s.val , (h s.val).1 s.property⟩ : T)
(by rw [eq , spec]),
exact ex,
intro bfT,
tidy
end,
exact eq_sets.1 h1
end
def img_comp {X Y Z : Type u} (f : X → Y) (g : Y → Z) (s : set X):
image g (image f s) = image (g ∘ f) s :=
begin
have h3: ∀ z : Z, (z ∈ image g (image f s)) ↔
(z ∈ image (g ∘ f) s)
:=
begin
intro z,
split,
intro el,
cases el with fa specFA,
cases specFA.1 with a specA,
use a,
split,
exact specA.1,
simp [specA.2 , specFA.2],
intro ex,
cases ex with a spec,
have fa_Y : f a ∈ image f s :=
begin use a, tidy end,
have gfa_Z : g (f a) ∈ image g (image f s) :=
begin
use f a,
split,
simp,
tidy
end,
rw ← spec.2,
exact gfa_Z
end,
exact eq_sets.1 h3
end
lemma not_and_left {p q : Prop}: ¬ (p ∧ q) → p → ¬ q :=
λ hnpq , λ hp , λ hq, absurd (and.intro hp hq) hnpq
lemma not_and_right {p q : Prop}: ¬ (p ∧ q) → q → ¬ p :=
λ hnpq , λ hp , by {intros a, simp at *, solve_by_elim}
end help_functions
def if_func (p : Prop) [decidable p] : Prop :=
if p
then p
else ¬p
lemma solving_if_func (p : Prop) [d : decidable p] : if_func p :=
match d with
| is_true h := h
| is_false nh := nh
end
def fun_using_if_fun (p : Prop) [decidable p] : ℕ :=
let some_fun : Prop := -- same thing with let ... in
if p
then p
else ¬p in
have some_proof : some_fun :=
begin
dsimp [some_fun], -- some_fun,
split_ifs,
exact h,
exact h
end,
1
def fun_using_if_fun_tactic (p : Prop) [decidable p] : ℕ :=
begin
let some_fun : Prop := -- same thing with let ... in
if p
then p
else ¬p,
have some_proof : some_fun :=
begin
dsimp [some_fun],
split_ifs,
exact h,
exact h
end,
exact 1
end
def eff_len {A : Type*} [inhabited A] (n : ℕ) :
list A → ℕ
| [] := n
| (h::tl) := (eff_len tl)
def subsubset {A: Type*} {V : set A} {U : set V} : set A
:= subtype.val '' U -- or just u.val
|
9976cba4f26215931a2b5306976370c7091fc3c1
|
5a6ff5f8d173cbfe51967eb4c96837e3a791fe3d
|
/mm0-lean/x86/lemmas.lean
|
f544402a26272a98f343e7cffcf3a20238f563ec
|
[
"CC0-1.0"
] |
permissive
|
digama0/mm0
|
491ac09146708aa1bb775007bf3dbe339ffc0096
|
98496badaf6464e56ed7b4204e7d54b85667cb01
|
refs/heads/master
| 1,692,321,030,902
| 1,686,254,458,000
| 1,686,254,458,000
| 172,456,790
| 273
| 38
|
CC0-1.0
| 1,689,939,563,000
| 1,551,080,059,000
|
Rust
|
UTF-8
|
Lean
| false
| false
| 62,553
|
lean
|
import x86.x86 data.list.basic data.zmod.basic
namespace bitvec
theorem of_nat_zero (n) : bitvec.of_nat n 0 = 0 :=
by induction n; [refl, exact congr_arg (vector.cons ff) n_ih]
theorem of_nat_one (n) : bitvec.of_nat n 1 = 1 :=
by cases n; [refl, exact congr_arg (vector.cons tt) (of_nat_zero _)]
theorem from_bits_fill_eq : ∀ {n b l} (e : list.length l = n),
from_bits_fill b l = ⟨l, e⟩
| 0 b [] e := rfl
| (n+1) b (a :: l) e :=
by rw [from_bits_fill, from_bits_fill_eq (nat.succ.inj e)]; refl
theorem bits_to_nat_zero (n) : bits_to_nat (list.repeat ff n) = 0 :=
by simp [bits_to_nat]; induction n; simp *
@[simp] theorem bits_to_nat_cons (a l) :
bits_to_nat (a :: l) = nat.bit a (bits_to_nat l) := rfl
@[simp] theorem to_nat_nil : to_nat vector.nil = 0 := rfl
@[simp] theorem to_nat_zero (n) : to_nat (0 : bitvec n) = 0 :=
bits_to_nat_zero _
@[simp] theorem to_nat_cons (b) {n} (v : bitvec n) :
to_nat (b :: v) = nat.bit b (to_nat v) :=
by cases v; refl
@[simp] theorem of_nat_succ (n i : ℕ) :
bitvec.of_nat n.succ i = i.bodd :: bitvec.of_nat n i.div2 :=
by rw [bitvec.of_nat, nat.bodd_div2_eq, bitvec.of_nat]
@[simp] theorem of_nat_bit (n : ℕ) (b i) :
bitvec.of_nat n.succ (nat.bit b i) = b :: bitvec.of_nat n i :=
by rw [of_nat_succ, nat.div2_bit, nat.bodd_bit]
theorem of_nat_bits_to_nat {n} (l : list bool) :
bitvec.of_nat n (bits_to_nat l) = from_bits_fill ff l :=
begin
rw bits_to_nat,
induction l generalizing n, exact of_nat_zero _,
cases n, refl,
simp [*, bits_to_nat, from_bits_fill,
bitvec.of_nat, nat.bodd_bit, nat.div2_bit]
end
theorem of_nat_bits_to_nat_eq {n} (l : list bool) (e : l.length = n) :
bitvec.of_nat n (bits_to_nat l) = ⟨l, e⟩ :=
begin
induction n generalizing l; cases l; injection e, refl,
simp [bits_to_nat, nat.div2_bit, nat.bodd_bit],
exact congr_arg (vector.cons l_hd) (n_ih _ h_1)
end
@[simp] theorem of_nat_to_nat : ∀ {n} (v : bitvec n),
bitvec.of_nat n (to_nat v) = v
| n ⟨l, e⟩ := of_nat_bits_to_nat_eq l e
theorem to_nat_of_nat_aux (m n b) :
nat.bit b (n % 2 ^ m) = nat.bit b n % 2 ^ nat.succ m :=
begin
have := nat.mod_add_div (n.bit b) (2^m * 2),
conv at this { to_rhs, rw [nat.bit_val, ← nat.mod_add_div n (2^m),
mul_add, add_right_comm, ← nat.bit_val, mul_left_comm,
← mul_assoc] },
rw [nat.pow_succ],
refine add_right_cancel (this.symm.trans _), congr' 2,
rw [mul_comm, ← nat.div_div_eq_div_mul, ← nat.div2_val, nat.div2_bit]
end
theorem to_nat_of_nat (m n) : to_nat (bitvec.of_nat m n) = n % 2 ^ m :=
begin
induction m generalizing n,
{ simp [bitvec.of_nat, to_nat], refl },
simp [bitvec.of_nat, m_ih],
conv { to_rhs, rw ← nat.bit_decomp n },
apply to_nat_of_nat_aux
end
theorem to_nat_lt_pow2 {n} (v : bitvec n) : to_nat v < 2 ^ n :=
begin
rw [← of_nat_to_nat v, to_nat_of_nat],
exact nat.mod_lt _ (nat.pow_pos dec_trivial _),
end
local attribute [instance]
def pow2_pos (n : ℕ) : fact (0 < 2^n) := nat.pow_pos dec_trivial _
def to_zmod {n} (v : bitvec n) : zmod (2^n) := bitvec.to_nat v
def of_zmod {n} (i : zmod (2^n)) : bitvec n := bitvec.of_nat _ i.val
theorem to_zmod_of_zmod {n} (i : zmod (2^n)) : to_zmod (of_zmod i) = i :=
((zmod.eq_iff_modeq_nat _).2
(by convert nat.modeq.mod_modeq _ _; apply to_nat_of_nat)).trans (zmod.cast_val _)
theorem of_zmod_to_zmod {n} (v : bitvec n) : of_zmod (to_zmod v) = v :=
by unfold of_zmod to_zmod; convert of_nat_to_nat v; exact
zmod.val_cast_of_lt (to_nat_lt_pow2 _)
theorem of_nat_eq_iff_modeq {m n₁ n₂} :
bitvec.of_nat m n₁ = bitvec.of_nat m n₂ ↔ n₁ ≡ n₂ [MOD 2 ^ m] :=
begin
dunfold nat.modeq, split; intro h,
{ rw [← to_nat_of_nat, h, to_nat_of_nat] },
{ rw [← of_nat_to_nat (bitvec.of_nat m n₁),
to_nat_of_nat, h, ← to_nat_of_nat, of_nat_to_nat] },
end
theorem of_nat_eq_of_zmod (m n) :
bitvec.of_nat m n = bitvec.of_zmod n :=
eq.symm $ of_nat_eq_iff_modeq.2 $
by convert nat.modeq.mod_modeq _ _; apply zmod.val_cast_nat
theorem to_zmod_zero (n) : to_zmod (0 : bitvec n) = 0 :=
by rw [to_zmod, to_nat_zero]; refl
theorem of_zmod_zero (n) : (of_zmod 0 : bitvec n) = 0 :=
by rw [← to_zmod_zero, of_zmod_to_zmod]
theorem of_zmod_one (n) : (of_zmod 1 : bitvec n) = 1 :=
begin
cases n, {refl},
change bitvec.of_nat _ (_) = _,
haveI : fact (1 < 2 ^ n.succ) :=
@nat.pow_lt_pow_of_lt_right _ dec_trivial 0 _ (nat.succ_pos _),
rw [zmod.val_one, of_nat_one],
end
theorem to_zmod_one (n) : to_zmod (1 : bitvec n) = 1 :=
by rw [← of_zmod_one, to_zmod_of_zmod]
theorem to_zmod_add {n} (a b : bitvec n) : to_zmod (a + b) = to_zmod a + to_zmod b :=
show to_zmod (bitvec.of_nat _ _) = _,
by rw [of_nat_eq_of_zmod, to_zmod_of_zmod, to_zmod, to_zmod, nat.cast_add]
theorem to_zmod_mul {n} (a b : bitvec n) : to_zmod (a * b) = to_zmod a * to_zmod b :=
show to_zmod (bitvec.of_nat _ _) = _,
by rw [of_nat_eq_of_zmod, to_zmod_of_zmod, to_zmod, to_zmod, nat.cast_mul]
theorem to_zmod_neg {n} (a : bitvec n) : to_zmod (-a) = -to_zmod a :=
show to_zmod (bitvec.of_nat _ _) = _,
begin
rw [of_nat_eq_of_zmod, to_zmod_of_zmod, eq_neg_iff_add_eq_zero, to_zmod,
← nat.cast_add, nat.sub_add_cancel (le_of_lt (to_nat_lt_pow2 _))],
exact zmod.cast_self _,
end
theorem of_zmod_add {n} (a b : zmod (2^n)) : of_zmod (a + b) = of_zmod a + of_zmod b :=
by conv_lhs {rw [← to_zmod_of_zmod a, ← to_zmod_of_zmod b]};
rw [← to_zmod_add, of_zmod_to_zmod]
theorem of_zmod_mul {n} (a b : zmod (2^n)) : of_zmod (a * b) = of_zmod a * of_zmod b :=
by conv_lhs {rw [← to_zmod_of_zmod a, ← to_zmod_of_zmod b]};
rw [← to_zmod_mul, of_zmod_to_zmod]
theorem of_zmod_neg {n} (a : zmod (2^n)) : of_zmod (-a) = -of_zmod a :=
by conv_lhs {rw [← to_zmod_of_zmod a]}; rw [← to_zmod_neg, of_zmod_to_zmod]
instance (n : ℕ) : add_comm_semigroup (bitvec n) :=
{ add_assoc := λ a b c, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b, ← of_zmod_to_zmod c,
← of_zmod_add, ← of_zmod_add, add_assoc, of_zmod_add, of_zmod_add],
add_comm := λ a b, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b,
← of_zmod_add, add_comm, of_zmod_add],
..bitvec.has_add }
instance (n : ℕ) : comm_semigroup (bitvec n) :=
{ mul_assoc := λ a b c, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b, ← of_zmod_to_zmod c,
← of_zmod_mul, ← of_zmod_mul, mul_assoc, of_zmod_mul, of_zmod_mul],
mul_comm := λ a b, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b,
← of_zmod_mul, mul_comm, of_zmod_mul],
..bitvec.has_mul }
instance (n : ℕ) : comm_ring (bitvec n) :=
{ zero_add := λ a, by rw [← of_zmod_to_zmod a, ← of_zmod_zero, ← of_zmod_add, zero_add],
add_zero := λ a, by rw [← of_zmod_to_zmod a, ← of_zmod_zero, ← of_zmod_add, add_zero],
add_left_neg := λ a, by rw [← of_zmod_to_zmod a,
← of_zmod_neg, ← of_zmod_add, add_left_neg, ← of_zmod_zero],
one_mul := λ a, by rw [← of_zmod_to_zmod a, ← of_zmod_one, ← of_zmod_mul, one_mul],
mul_one := λ a, by rw [← of_zmod_to_zmod a, ← of_zmod_one, ← of_zmod_mul, mul_one],
left_distrib := λ a b c, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b, ← of_zmod_to_zmod c,
← of_zmod_add, ← of_zmod_mul, left_distrib, of_zmod_add, of_zmod_mul, of_zmod_mul]; refl,
right_distrib := λ a b c, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b, ← of_zmod_to_zmod c,
← of_zmod_add, ← of_zmod_mul, right_distrib, of_zmod_add, of_zmod_mul, of_zmod_mul]; refl,
..bitvec.has_zero,
..bitvec.has_one,
..bitvec.has_neg,
..bitvec.add_comm_semigroup n,
..bitvec.comm_semigroup n }
theorem to_nat_nth {n} (i j) :
(bitvec.of_nat n i).nth j = i.test_bit j.1 :=
begin
generalize e : bitvec.of_nat n i = v, cases v with l e',
cases j with j h,
rw [vector.nth], dsimp only,
induction n generalizing i l j, cases h,
cases l; injection e',
simp [bitvec.of_nat] at e,
generalize_hyp e₂ : bitvec.of_nat n_n i.div2 = v at e, cases v with l e₂',
injection e, cases h_2,
cases j; simp, refl,
rw [← nat.bit_decomp i, nat.test_bit_succ],
exact n_ih _ _ _ _ e₂ (nat.lt_of_succ_lt_succ h)
end
theorem of_nat_from_bits_fill (n m i) (h : n ≤ m) :
bitvec.of_nat n i = from_bits_fill ff (bitvec.of_nat m i).1 :=
begin
generalize e : bitvec.of_nat m i = v, cases v with l h, simp,
induction n generalizing m i l e, exact (vector.eq_nil _).trans (vector.eq_nil _).symm,
rw [of_nat_succ],
cases m, cases h,
rw [of_nat_succ] at e,
generalize e' : bitvec.of_nat m i.div2 = v, cases v with l' h',
rw e' at e, injection e, subst l,
rw [n_ih _ _ (nat.le_of_succ_le_succ h) _ _ e', from_bits_fill],
end
theorem of_nat_bit0_aux {n} (j : bitvec (nat.succ n)) :
bit0 j = ff :: from_bits_fill ff (j.val) :=
begin
change bitvec.of_nat n.succ (bit0 (to_nat j)) = _,
rw [of_nat_succ,
nat.bodd_bit0, nat.div2_bit0, to_nat, of_nat_bits_to_nat]
end
theorem of_nat_bit0 (n i) : bitvec.of_nat n (bit0 i) = bit0 (bitvec.of_nat n i) :=
begin
induction n generalizing i, refl,
rw [of_nat_succ,
nat.bodd_bit0, nat.div2_bit0],
rw [of_nat_from_bits_fill _ _ _ (nat.le_succ _)],
generalize : bitvec.of_nat n_n.succ i = j,
rw of_nat_bit0_aux,
end
theorem of_nat_bit1 (n i) : bitvec.of_nat n (bit1 i) = bit1 (bitvec.of_nat n i) :=
begin
induction n generalizing i, refl,
rw [of_nat_succ,
nat.bodd_bit1, nat.div2_bit1],
rw [of_nat_from_bits_fill _ _ _ (nat.le_succ _)],
generalize : bitvec.of_nat n_n.succ i = j,
change _ = bitvec.of_nat _ (to_nat (bit0 j) + bit0 (@to_nat n_n 0) + 1),
rw [to_nat_zero],
change _ = bitvec.of_nat _ (to_nat (bit0 j) + 1),
rw [of_nat_bit0_aux, to_nat_cons],
change _ = bitvec.of_nat _ (nat.bit tt _),
rw [of_nat_bit, of_nat_to_nat],
end
theorem add_nat_assoc {n} (v : bitvec n) (a b : ℕ) :
v + a + b = v + (a + b : ℕ) :=
by rw [nat.cast_add, add_assoc]
theorem of_nat_add {n} (a b : ℕ) : bitvec.of_nat n (a + b) = bitvec.of_nat n a + bitvec.of_nat n b :=
by simp [of_nat_eq_of_zmod, of_zmod_add]
theorem of_nat_succ' {n} (a : ℕ) : bitvec.of_nat n a.succ = bitvec.of_nat n a + 1 :=
(of_nat_add a 1).trans $ by simp [of_nat_one]
theorem of_nat_mul {n} (a b : ℕ) : bitvec.of_nat n (a * b) = bitvec.of_nat n a * bitvec.of_nat n b :=
by simp [of_nat_eq_of_zmod, of_zmod_mul]
theorem coe_eq_of_nat {n} (a : ℕ) :
(a : bitvec n) = bitvec.of_nat n a :=
begin
induction a, exact (bitvec.of_nat_zero _).symm,
rw [of_nat_succ', ← a_ih], refl,
end
theorem coe_to_nat {n} (v : bitvec n) : (to_nat v : bitvec n) = v :=
by rw [coe_eq_of_nat, of_nat_to_nat]
theorem bits_to_nat_inj : ∀ {l₁ l₂},
bits_to_nat l₁ = bits_to_nat l₂ → l₁.length = l₂.length → l₁ = l₂
| [] [] _ _ := rfl
| (a :: l₁) (b :: l₂) e e' := begin
rw [bits_to_nat_cons, bits_to_nat_cons] at e,
rw [← nat.bodd_bit a (bits_to_nat l₁), e, nat.bodd_bit,
@bits_to_nat_inj l₁ l₂ _ (nat.succ.inj e')],
rw [← nat.div2_bit a (bits_to_nat l₁), e, nat.div2_bit]
end
theorem to_nat_inj {n v₁ v₂}
(h : @bitvec.to_nat n v₁ = bitvec.to_nat v₂) : v₁ = v₂ :=
subtype.eq $ bits_to_nat_inj h (v₁.2.trans v₂.2.symm)
theorem coe_shl {n} (a b) : (nat.shiftl a b : bitvec n) = bitvec.shl a b :=
begin
rw [shl, coe_eq_of_nat, nat.shiftl_eq_mul_pow, nat.shiftl_eq_mul_pow],
refine of_nat_eq_iff_modeq.2 (nat.modeq.modeq_mul_right _ _),
rw [← of_nat_eq_iff_modeq, of_nat_to_nat, coe_eq_of_nat],
end
theorem sign_iff_neg {n v} : @bitvec.sign n v ↔ bitvec.to_int v < 0 :=
begin
unfold bitvec.to_int, cases sign v; simp,
norm_cast, exact to_nat_lt_pow2 _
end
theorem to_int_inj {n v₁ v₂}
(h : @bitvec.to_int n v₁ = bitvec.to_int v₂) : v₁ = v₂ :=
begin
have : sign v₁ = sign v₂,
{ apply bool.coe_bool_iff.1,
rw [sign_iff_neg, sign_iff_neg, h] },
revert h,
unfold bitvec.to_int,
rw this, cases sign v₂; simp; exact to_nat_inj
end
theorem pow2_eq_zero {n} : (2 ^ n : bitvec n) = 0 :=
begin
suffices : ((2 ^ n : ℕ) : bitvec n) = 0, {exact_mod_cast this},
have := to_nat_of_nat n (2^n),
apply to_nat_inj,
rw [coe_eq_of_nat, to_nat_of_nat, nat.mod_self, to_nat_zero],
end
theorem coe_to_int {n} (v : bitvec n) : (to_int v : bitvec n) = v :=
by unfold to_int; cases sign v; simp [coe_to_nat, pow2_eq_zero]
@[class] def reify {n} (v : bitvec n) (l : out_param (list bool)) : Prop :=
from_bits_fill ff l = v
theorem reify.mk {n} (v) {l} [h : @reify n v l] :
from_bits_fill ff l = v := h
theorem reify_eq {n v l l'} [@reify n v l] (h : l' = v.1) :
l' = (@from_bits_fill ff l n).1 := by rwa reify.mk v
theorem reify_eq' {n v l l'} [@reify n v l] (h : l' = v) :
l' = @from_bits_fill ff l n := by rwa reify.mk v
theorem reify_eq₂ {n v₁ l₁ v₂ l₂}
[@reify n v₁ l₁] [@reify n v₂ l₂] (h : v₁ = v₂) :
@from_bits_fill ff l₁ n = from_bits_fill ff l₂ :=
by rwa [reify.mk v₁, reify.mk v₂]
theorem reify_iff {n v l} : @reify n v l ↔ bitvec.of_nat n (bits_to_nat l) = v :=
iff_of_eq $ congr_arg (= v) (of_nat_bits_to_nat _).symm
instance reify_0 {n} : @reify n 0 [] := rfl
instance reify_1 {n} : @reify n 1 [tt] :=
by cases n; exact rfl
instance reify_bit0 {n} (v l) [h : @reify n v l] :
reify (bit0 v) (ff :: l) :=
reify_iff.2 $
by have := of_nat_bit0 n (bits_to_nat l);
rwa [reify_iff.1 h] at this
instance reify_bit1 {n} (v l) [h : @reify n v l] :
reify (bit1 v) (tt :: l) :=
reify_iff.2 $
by have := of_nat_bit1 n (bits_to_nat l);
rwa [reify_iff.1 h] at this
end bitvec
namespace x86
def split_bits_spec : list (Σ n, bitvec n) → list bool → Prop
| [] l := list.all l bnot
| (⟨n, v⟩ :: s) l := let ⟨l₁, l₂⟩ := l.split_at n in
(@bitvec.from_bits_fill ff l₁ n).1 = v.1 ∧ split_bits_spec s l₂
theorem split_bits_ok {l s} : split_bits (bitvec.bits_to_nat l) s → split_bits_spec s l :=
begin
generalize e₁ : bitvec.bits_to_nat l = n,
induction s generalizing l n, rintro ⟨⟩,
{ induction l, constructor,
cases l_hd,
{ exact bool.band_intro rfl (l_ih (not_imp_not.1 (nat.bit_ne_zero _) e₁)) },
{ cases nat.bit1_ne_zero _ e₁ } },
{ rcases s_hd with ⟨i, l', e₂⟩,
unfold split_bits_spec,
generalize e₃ : l.split_at i = p, cases p with l₁ l₂,
dsimp [split_bits_spec],
induction i with i generalizing l' l₁ l₂ e₂ l n; cases l'; injection e₂,
{ rintro ⟨⟩, cases e₃, exact ⟨rfl, s_ih _ e₁ a_a⟩ },
{ generalize e₄ : (⟨l'_hd :: l'_tl, e₂⟩ : bitvec _) = f,
rintro ⟨⟩, cases a_bs with _ pr, injection e₄, cases h_2,
generalize e₅ : l.tail.split_at i = p, cases p with l₁' l₂',
have : bitvec.bits_to_nat l.tail = nat.div2 n,
{ subst e₁, cases l, refl, exact (nat.div2_bit _ _).symm },
rcases i_ih _ _ _ h_1 _ this e₅ a_a with ⟨e₆, h'⟩,
replace e₆ : bitvec.from_bits_fill ff l₁' = ⟨l'_tl, pr⟩ := subtype.eq e₆,
cases l,
{ cases e₃,
have : (l₁', l₂') = ([], []), {cases i; cases e₅; refl}, cases this,
simp [bitvec.from_bits_fill, h', vector.repeat] at e₆ ⊢,
cases e₁, exact ⟨rfl, e₆⟩ },
{ rw [list.split_at, show l_tl.split_at i = (l₁', l₂'), from e₅] at e₃,
cases e₃, rw [bitvec.from_bits_fill, ← e₁, e₆],
refine ⟨_, h'⟩, simp [vector.cons], exact (nat.bodd_bit _ _).symm } } }
end
theorem split_bits.determ_l {n₁ n₂ l} (h₁ : split_bits n₁ l) (h₂ : split_bits n₂ l) : n₁ = n₂ :=
begin
induction l generalizing n₁ n₂, {cases h₁, cases h₂, refl},
rcases l_hd with ⟨_, l', rfl⟩,
induction l' generalizing n₁ n₂,
{ cases h₁, cases h₂, exact l_ih h₁_a h₂_a },
{ have : ∀ {n l'},
split_bits n l' →
l' = ⟨_, l'_hd :: l'_tl, rfl⟩ :: l_tl →
l'_hd = nat.bodd n ∧
split_bits (nat.div2 n) (⟨_, l'_tl, rfl⟩ :: l_tl),
{ intros, cases a; try {cases a_1},
rcases a_bs with ⟨l₂, rfl⟩,
injection a_1, cases h_2,
cases congr_arg (λ v : Σ n, bitvec n, v.2.1) h_1,
exact ⟨rfl, a_a⟩ },
rcases this h₁ rfl with ⟨rfl, h₁'⟩,
rcases this h₂ rfl with ⟨e, h₂'⟩,
rw [← nat.bit_decomp n₁, e, l'_ih h₁' h₂', nat.bit_decomp] }
end
theorem split_bits.determ {n l₁ l₂} (h₁ : split_bits n l₁) (h₂ : split_bits n l₂)
(h : l₁.map sigma.fst = l₂.map sigma.fst) : l₁ = l₂ :=
begin
induction l₁ generalizing n l₂; cases l₂; injection h, refl,
cases l₁_hd with i v₁, cases l₂_hd with _ v₂, cases h_1,
clear h h_1, induction i with i generalizing v₁ v₂ n,
{ cases h₁, cases h₂, rw l₁_ih h₁_a h₂_a h_2 },
{ cases h₁, cases h₂, cases i_ih _ _ h₁_a h₂_a, refl }
end
theorem bits_to_byte.determ_l {n m w1 w2 l} :
@bits_to_byte n m w1 l → @bits_to_byte n m w2 l → w1 = w2
| ⟨e₁, h₁⟩ ⟨_, h₂⟩ := bitvec.to_nat_inj $ split_bits.determ_l h₁ h₂
theorem bits_to_byte.determ_l_aux {n m w1 w2 l l'} :
@bits_to_byte n m w1 l → @bits_to_byte n m w2 (l ++ l') → (w1, l') = (w2, [])
| ⟨e₁, h₁⟩ ⟨e₂, h₂⟩ := begin
simp, suffices, refine ⟨_, this⟩, swap,
{ apply list.length_eq_zero.1,
apply @add_left_cancel _ _ l.length,
rw [add_zero, ← list.length_append, e₁, e₂] },
clear bits_to_byte.determ_l_aux, subst this,
rw list.append_nil at h₂,
exact bitvec.to_nat_inj (split_bits.determ_l h₁ h₂)
end
theorem bits_to_byte.determ {n m w l1 l2} :
@bits_to_byte n m w l1 → @bits_to_byte n m w l2 → l1 = l2
| ⟨e₁, h₁⟩ ⟨e₂, h₂⟩ := list.map_injective_iff.2
(by rintro x y ⟨⟩; refl)
(split_bits.determ h₁ h₂
(by rw [list.map_map, list.map_map, (_ : _∘_ = _),
list.map_const _ 8, e₁, list.map_const, e₂]; refl))
theorem read_prefixes.determ {r₁ r₂ l} : read_prefixes r₁ l → read_prefixes r₂ l → r₁ = r₂ :=
begin
intros h₁ h₂, cases h₁; cases h₂; congr,
cases split_bits.determ h₁_a h₂_a rfl, refl,
end
@[elab_as_eliminator] theorem byte_split {C : byte → Sort*}
: ∀ b : byte, (∀ b0 b1 b2 b3 b4 b5 b6 b7,
C ⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩) → C b
| ⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩ H := H _ _ _ _ _ _ _ _
def binop.from_bits : ∀ (b0 b1 b2 b3 : bool), binop
| ff ff ff ff := binop.add
| tt ff ff ff := binop.or
| ff tt ff ff := binop.adc
| tt tt ff ff := binop.sbb
| ff ff tt ff := binop.and
| tt ff tt ff := binop.sub
| ff tt tt ff := binop.xor
| tt tt tt ff := binop.cmp
| ff ff ff tt := binop.rol
| tt ff ff tt := binop.ror
| ff tt ff tt := binop.rcl
| tt tt ff tt := binop.rcr
| ff ff tt tt := binop.shl
| tt ff tt tt := binop.shr
| ff tt tt tt := binop.tst
| tt tt tt tt := binop.sar
theorem binop.bits_eq {b0 b1 b2 b3 e op} :
binop.bits op ⟨[b0, b1, b2, b3], e⟩ → op = binop.from_bits b0 b1 b2 b3 :=
begin
generalize e' : (⟨[b0, b1, b2, b3], e⟩ : bitvec 4) = v,
intro h, induction h;
{ cases bitvec.reify_eq (congr_arg subtype.val e'), refl }
end
theorem binop.bits.determ : ∀ {op1 op2 v},
binop.bits op1 v → binop.bits op2 v → op1 = op2
| op1 op2 ⟨[b0, b1, b2, b3], _⟩ h1 h2 :=
(binop.bits_eq h1).trans (binop.bits_eq h2).symm
def basic_cond.from_bits : ∀ (b0 b1 b2 : bool), option basic_cond
| ff ff ff := some basic_cond.o
| tt ff ff := some basic_cond.b
| ff tt ff := some basic_cond.e
| tt tt ff := some basic_cond.na
| ff ff tt := some basic_cond.s
| tt ff tt := none
| ff tt tt := some basic_cond.l
| tt tt tt := some basic_cond.ng
theorem basic_cond.bits_eq {b0 b1 b2 e c} :
basic_cond.bits c ⟨[b0, b1, b2], e⟩ → basic_cond.from_bits b0 b1 b2 = some c :=
begin
generalize e' : (⟨[b0, b1, b2], e⟩ : bitvec 3) = v,
intro h, induction h;
{ cases bitvec.reify_eq (congr_arg subtype.val e'), refl }
end
def cond_code.from_bits (b0 b1 b2 b3 : bool) : option cond_code :=
option.map (cond_code.mk b0) (basic_cond.from_bits b1 b2 b3)
theorem cond_code.bits_eq {b0 b1 b2 b3 e c} :
cond_code.bits c ⟨[b0, b1, b2, b3], e⟩ → cond_code.from_bits b0 b1 b2 b3 = some c :=
begin
rintro ⟨⟩,
rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩,
cases subtype.eq h₁,
rw [cond_code.from_bits, basic_cond.bits_eq a_a_1], refl
end
theorem cond_code.bits.determ : ∀ {c1 c2 v},
cond_code.bits c1 v → cond_code.bits c2 v → c1 = c2
| c1 c2 ⟨[b0, b1, b2, b3], _⟩ h1 h2 := option.some_inj.1 $
(cond_code.bits_eq h1).symm.trans (cond_code.bits_eq h2)
theorem read_displacement_ne_3 {mod disp l} :
read_displacement mod disp l → mod ≠ 3 :=
by rintro ⟨⟩ ⟨⟩
theorem read_displacement.determ_aux {mod disp1 disp2 l l'}
(h₁ : read_displacement mod disp1 l)
(h₂ : read_displacement mod disp2 (l ++ l')) : (disp1, l') = (disp2, []) :=
begin
cases h₁; cases h₂; try {refl},
cases bits_to_byte.determ_l_aux h₁_a h₂_a, refl
end
theorem read_displacement.determ {mod disp1 disp2 l}
(h₁ : read_displacement mod disp1 l)
(h₂ : read_displacement mod disp2 l) : disp1 = disp2 :=
by cases read_displacement.determ_aux h₁
(by rw list.append_nil; exact h₂); refl
theorem read_sib_displacement_ne_3 {mod bbase w Base l} :
read_sib_displacement mod bbase w Base l → mod ≠ 3 :=
by rw [read_sib_displacement]; split_ifs; [
{rcases h with ⟨_, rfl⟩; rintro _ ⟨⟩},
exact λ h, read_displacement_ne_3 h.1]
theorem read_sib_displacement.determ_aux {mod bbase w1 w2 Base1 Base2 l l'}
(h₁ : read_sib_displacement mod bbase w1 Base1 l)
(h₂ : read_sib_displacement mod bbase w2 Base2 (l ++ l')) : (w1, Base1, l') = (w2, Base2, []) :=
begin
rw read_sib_displacement at h₁ h₂, split_ifs at h₁ h₂,
{ rcases h₁ with ⟨w, rfl, rfl, h1⟩,
rcases h₂ with ⟨_, rfl, rfl, h2⟩,
cases bits_to_byte.determ_l_aux h1 h2, refl },
{ rcases h₁ with ⟨h1, rfl⟩,
rcases h₂ with ⟨h2, rfl⟩,
cases read_displacement.determ_aux h1 h2, refl },
end
theorem read_sib_displacement.determ {mod bbase w1 w2 Base1 Base2 l}
(h₁ : read_sib_displacement mod bbase w1 Base1 l)
(h₂ : read_sib_displacement mod bbase w2 Base2 l) : (w1, Base1) = (w2, Base2) :=
by cases read_sib_displacement.determ_aux h₁
(by rw list.append_nil; exact h₂); refl
theorem read_SIB_ne_3 {rex mod rm l} :
read_SIB rex mod rm l → mod ≠ 3 :=
by rintro ⟨⟩; exact read_sib_displacement_ne_3 a_a_1
theorem read_SIB.determ_aux {rex mod rm1 rm2 l l'}
(h₁ : read_SIB rex mod rm1 l)
(h₂ : read_SIB rex mod rm2 (l ++ l')) : (rm1, l') = (rm2, []) :=
begin
cases h₁, cases h₂,
cases split_bits.determ h₁_a h₂_a rfl,
cases read_sib_displacement.determ_aux h₁_a_1 h₂_a_1, refl
end
theorem read_SIB.determ {rex mod rm1 rm2 l}
(h₁ : read_SIB rex mod rm1 l)
(h₂ : read_SIB rex mod rm2 l) : rm1 = rm2 :=
by cases read_SIB.determ_aux h₁
(by rw list.append_nil; exact h₂); refl
theorem read_ModRM_nil {rex reg r} : ¬ read_ModRM rex reg r [] :=
by rintro ⟨⟩
def read_ModRM' (rex : REX) (r : RM)
(rm : bitvec 3) (mod : bitvec 2) (l : list byte) : Prop :=
if mod = 3 then
r = RM.reg (rex_reg rex.B rm) ∧
l = []
else if rm = 4 then
read_SIB rex mod r l
else if rm = 5 ∧ mod = 0 then ∃ i : word,
i.to_list_byte l ∧
r = RM.mem none base.rip (EXTS i)
else ∃ disp,
read_displacement mod disp l ∧
r = RM.mem none (base.reg (rex_reg rex.B rm)) disp
theorem read_ModRM_ModRM' {rex : REX} {reg : regnum} {r : RM}
{rm reg_opc : bitvec 3} {mod : bitvec 2} {b : byte} {l : list byte}
(h₁ : split_bits b.to_nat [⟨3, rm⟩, ⟨3, reg_opc⟩, ⟨2, mod⟩])
(h₂ : read_ModRM rex reg r (b :: l)) :
reg = rex_reg rex.R reg_opc ∧ read_ModRM' rex r rm mod l :=
begin
generalize_hyp e : list.cons b l = l' at h₂,
induction h₂; cases e;
cases split_bits.determ h₁ h₂_a rfl;
refine ⟨rfl, _⟩,
{ rw [read_ModRM', if_neg, if_neg, if_pos],
exact ⟨_, h₂_a_1, rfl⟩,
all_goals {exact dec_trivial} },
{ rw [read_ModRM', if_pos],
exact ⟨rfl, rfl⟩, exact dec_trivial },
{ rw [read_ModRM', if_neg (read_SIB_ne_3 h₂_a_1), if_pos],
exact h₂_a_1, refl },
{ rw [read_ModRM', if_neg (read_displacement_ne_3 h₂_a_3),
if_neg h₂_a_1, if_neg h₂_a_2],
exact ⟨_, h₂_a_3, rfl⟩ },
end
theorem read_ModRM_split {rex reg r b l}
(h : read_ModRM rex reg r (b :: l)) :
∃ rm reg_opc mod,
split_bits b.to_nat [⟨3, rm⟩, ⟨3, reg_opc⟩, ⟨2, mod⟩] :=
by cases h; exact ⟨_, _, _, by assumption⟩
theorem read_ModRM.determ_aux {rex reg1 r1 reg2 r2 l l'}
(h₁ : read_ModRM rex reg1 r1 l)
(h₂ : read_ModRM rex reg2 r2 (l ++ l')) :
(reg1, r1, l') = (reg2, r2, []) :=
begin
simp,
cases l with b l, {cases read_ModRM_nil h₁},
rcases read_ModRM_split h₁ with ⟨rm, reg_opc, r, s⟩,
rcases read_ModRM_ModRM' s h₁ with ⟨rfl, h₁'⟩,
rcases read_ModRM_ModRM' s h₂ with ⟨rfl, h₂'⟩,
refine ⟨rfl, _⟩,
clear h₁ h₂ s, unfold read_ModRM' at h₁' h₂',
split_ifs at h₁' h₂',
{ rw h₁'.2 at h₂', exact ⟨h₁'.1.trans h₂'.1.symm, h₂'.2⟩ },
{ cases read_SIB.determ_aux h₁' h₂', exact ⟨rfl, rfl⟩ },
{ rcases h₁' with ⟨i1, h11, h12⟩,
rcases h₂' with ⟨i2, h21, h22⟩,
cases bits_to_byte.determ_l_aux h11 h21,
exact ⟨h12.trans h22.symm, rfl⟩ },
{ rcases h₁' with ⟨i1, h11, h12⟩,
rcases h₂' with ⟨i2, h21, h22⟩,
cases read_displacement.determ_aux h11 h21,
exact ⟨h12.trans h22.symm, rfl⟩ },
end
theorem read_ModRM.determ {rex reg1 r1 reg2 r2 l}
(h₁ : read_ModRM rex reg1 r1 l)
(h₂ : read_ModRM rex reg2 r2 l) : (reg1, r1) = (reg2, r2) :=
by cases read_ModRM.determ_aux h₁
(by rw list.append_nil; exact h₂); refl
theorem read_ModRM.determ₂ {rex reg1 r1 reg2 r2 l1 l2 l1' l2'}
(h₁ : read_ModRM rex reg1 r1 l1)
(h₂ : read_ModRM rex reg2 r2 l2)
(e : l1 ++ l1' = l2 ++ l2') : (reg1, r1, l1, l1') = (reg2, r2, l2, l2') :=
begin
have : ∀ {reg1 r1 reg2 r2 l1 l2 l1' l2'}
(h₁ : read_ModRM rex reg1 r1 l1)
(h₂ : read_ModRM rex reg2 r2 l2)
(e : ∃ a', l2 = l1 ++ a' ∧ l1' = a' ++ l2'),
(l1, l1') = (l2, l2'),
{ intros, rcases e_1 with ⟨l3, rfl, rfl⟩,
cases read_ModRM.determ_aux h₁_1 h₂_1, simp },
cases (list.append_eq_append_iff.1 e).elim
(λ h, this h₁ h₂ h)
(λ h, (this h₂ h₁ h).symm),
cases read_ModRM.determ h₁ h₂, refl,
end
theorem read_opcode_ModRM.determ_aux {rex v1 r1 v2 r2 l l'}
(h₁ : read_opcode_ModRM rex v1 r1 l)
(h₂ : read_opcode_ModRM rex v2 r2 (l ++ l')) : (v1, r1, l') = (v2, r2, []) :=
begin
cases h₁, cases h₂,
cases read_ModRM.determ_aux h₁_a h₂_a,
cases split_bits.determ h₁_a_1 h₂_a_1 rfl, refl,
end
theorem read_opcode_ModRM.determ {rex v1 r1 v2 r2 l}
(h₁ : read_opcode_ModRM rex v1 r1 l)
(h₂ : read_opcode_ModRM rex v2 r2 l) : (v1, r1) = (v2, r2) :=
by cases read_opcode_ModRM.determ_aux h₁
(by rw list.append_nil; exact h₂); refl
theorem read_opcode_ModRM.determ₂_aux {rex v1 r1 v2 r2 l1 l2 l1' l2' l'}
(h₁ : read_opcode_ModRM rex v1 r1 l1)
(h₂ : read_opcode_ModRM rex v2 r2 l2)
(e : l1 ++ l1' ++ l' = l2 ++ l2') : (v1, r1, l1, l1' ++ l') = (v2, r2, l2, l2') :=
begin
cases h₁, cases h₂,
rw [list.append_assoc, list.append_eq_append_iff] at e,
rcases e with ⟨x, rfl, e⟩ | ⟨x, rfl, rfl⟩,
{ cases read_ModRM.determ_aux h₁_a h₂_a, cases e,
cases split_bits.determ h₁_a_1 h₂_a_1 rfl,
rw list.append_nil, refl },
{ cases read_ModRM.determ_aux h₂_a h₁_a,
cases split_bits.determ h₁_a_1 h₂_a_1 rfl,
rw list.append_nil, refl },
end
theorem read_opcode_ModRM.determ₂ {rex v1 r1 v2 r2 l1 l2 l1' l2'}
(h₁ : read_opcode_ModRM rex v1 r1 l1)
(h₂ : read_opcode_ModRM rex v2 r2 l2) :
l1 ++ l1' = l2 ++ l2' → (v1, r1, l1, l1') = (v2, r2, l2, l2') :=
by simpa using @read_opcode_ModRM.determ₂_aux _ _ _ _ _ _ _ l1' l2' [] h₁ h₂
theorem read_imm8.determ_aux {w1 w2 l l'}
(h₁ : read_imm8 w1 l) (h₂ : read_imm8 w2 (l ++ l')) : (w1, l') = (w2, []) :=
by cases h₁; cases h₂; refl
theorem read_imm16.determ_aux {w1 w2 l l'}
(h₁ : read_imm16 w1 l) (h₂ : read_imm16 w2 (l ++ l')) : (w1, l') = (w2, []) :=
by cases h₁; cases h₂; cases bits_to_byte.determ_l_aux h₁_a h₂_a; refl
theorem read_imm32.determ_aux {w1 w2 l l'}
(h₁ : read_imm32 w1 l) (h₂ : read_imm32 w2 (l ++ l')) : (w1, l') = (w2, []) :=
by cases h₁; cases h₂; cases bits_to_byte.determ_l_aux h₁_a h₂_a; refl
theorem read_imm8.determ {w1 w2 l}
(h₁ : read_imm8 w1 l) (h₂ : read_imm8 w2 l) : w1 = w2 :=
by cases h₁; cases h₂; refl
theorem read_imm16.determ {w1 w2 l}
(h₁ : read_imm16 w1 l) (h₂ : read_imm16 w2 l) : w1 = w2 :=
by cases h₁; cases h₂; cases bits_to_byte.determ_l h₁_a h₂_a; refl
theorem read_imm32.determ {w1 w2 l}
(h₁ : read_imm32 w1 l) (h₂ : read_imm32 w2 l) : w1 = w2 :=
by cases h₁; cases h₂; cases bits_to_byte.determ_l h₁_a h₂_a; refl
theorem read_imm.determ_aux : ∀ {sz w1 w2 l l'},
read_imm sz w1 l → read_imm sz w2 (l ++ l') → (w1, l') = (w2, [])
| (wsize.Sz8 _) _ _ _ _ := read_imm8.determ_aux
| wsize.Sz16 _ _ _ _ := read_imm16.determ_aux
| wsize.Sz32 _ _ _ _ := read_imm32.determ_aux
| wsize.Sz64 _ _ _ _ := read_imm32.determ_aux
theorem read_full_imm.determ_aux : ∀ {sz w1 w2 l l'},
read_full_imm sz w1 l → read_full_imm sz w2 (l ++ l') → (w1, l') = (w2, [])
| (wsize.Sz8 _) _ _ _ _ := read_imm8.determ_aux
| wsize.Sz16 _ _ _ _ := read_imm16.determ_aux
| wsize.Sz32 _ _ _ _ := read_imm32.determ_aux
| wsize.Sz64 _ _ _ _ := bits_to_byte.determ_l_aux
theorem read_imm.determ {sz w1 w2 l}
(h₁ : read_imm sz w1 l) (h₂ : read_imm sz w2 l) : w1 = w2 :=
by cases read_imm.determ_aux h₁
(by rw list.append_nil; exact h₂); refl
theorem read_full_imm.determ {sz w1 w2 l}
(h₁ : read_full_imm sz w1 l) (h₂ : read_full_imm sz w2 l) : w1 = w2 :=
by cases read_full_imm.determ_aux h₁
(by rw list.append_nil; exact h₂); refl
def decode_two' (rex : REX) (a : ast) (b0 b1 b2 b3 b4 b5 b6 b7 : bool) (l : list byte) : Prop :=
cond b7
(cond b6
( -- xadd
[b1, b2, b3, b4, b5] = [ff, ff, ff, ff, ff] ∧
let v := b0, sz := op_size_W rex v in
∃ reg r,
read_ModRM rex reg r l ∧
a = ast.xadd sz r reg)
(cond b5
(cond b2
( -- movsx
[b1, b4] = [tt, tt] ∧
let sz2 := op_size_W rex tt,
sz := if b0 then wsize.Sz16 else wsize.Sz8 rex.is_some in
∃ reg r,
read_ModRM rex reg r l ∧
a = (if b3 then ast.movsx else ast.movzx) sz (dest_src.R_rm reg r) sz2)
( -- cmpxchg
[b1, b4] = [ff, tt] ∧
let v := b0, sz := op_size_W rex v in
∃ reg r,
read_ModRM rex reg r l ∧
a = ast.cmpxchg sz r reg))
(cond b4
( -- setcc
∃ reg r code,
read_ModRM rex reg r l ∧
cond_code.from_bits b0 b1 b2 b3 = some code ∧
a = ast.setcc code rex.is_some r)
( -- jcc
∃ imm code,
read_imm32 imm l ∧
cond_code.from_bits b0 b1 b2 b3 = some code ∧
a = ast.jcc code imm))))
(cond b6
( -- cmov
[b4, b5] = [ff, ff] ∧
let sz := op_size tt rex.W tt in
∃ reg r code,
read_ModRM rex reg r l ∧
cond_code.from_bits b0 b1 b2 b3 = some code ∧
a = ast.cmov code sz (dest_src.R_rm reg r))
( -- syscall
[b0, b1, b2, b3, b4, b5] = [tt, ff, tt, ff, ff, ff] ∧
a = ast.syscall ∧
l = []))
theorem decode_two_two' {rex a b0 b1 b2 b3 b4 b5 b6 b7 l} :
decode_two rex a (⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩ :: l) →
decode_two' rex a b0 b1 b2 b3 b4 b5 b6 b7 l :=
begin
generalize e : (⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩ :: l : list byte) = l',
intro a, cases a,
{ cases e, rcases split_bits_ok a_a with ⟨h₁, h₂, _⟩,
cases subtype.eq h₁,
cases bitvec.reify_eq h₂,
exact ⟨rfl, _, _, _, a_a_1, cond_code.bits_eq a_a_2, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨h₁, h₂, _⟩,
cases subtype.eq h₁,
cases bitvec.reify_eq h₂,
exact ⟨_, _, a_a_1, cond_code.bits_eq a_a_2, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨h₁, h₂, _⟩,
cases subtype.eq h₁,
cases bitvec.reify_eq h₂,
exact ⟨_, _, _, a_a_1, cond_code.bits_eq a_a_2, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩,
cases bitvec.reify_eq h₁,
exact ⟨rfl, _, _, a_a_1, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, ⟨⟩, h₂, _⟩,
cases bitvec.reify_eq h₁,
cases bitvec.reify_eq h₂,
exact ⟨rfl, _, _, a_a_1, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩,
cases bitvec.reify_eq h₁,
exact ⟨rfl, _, _, a_a_1, rfl⟩ },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact ⟨rfl, rfl, rfl⟩ },
end
theorem decode_two_nil {rex a} : ¬ decode_two rex a [].
theorem decode_two.determ_aux {rex a₁ a₂ l l'} :
decode_two rex a₁ l → decode_two rex a₂ (l ++ l') → (a₁, l') = (a₂, []) :=
begin
cases l with b l, {exact decode_two_nil.elim},
apply byte_split b, introv h1 h2,
replace h1 := decode_two_two' h1,
replace h2 := decode_two_two' h2,
unfold decode_two' at h1 h2,
repeat { do
`(cond %%e _ _) ← tactic.get_local `h1 >>= tactic.infer_type,
tactic.cases e $> (); `[dsimp only [cond] at h1 h2] },
{ rcases h1.2 with ⟨rfl, rfl⟩,
rcases h2.2 with ⟨rfl, ⟨⟩⟩, refl },
{ rcases h1.2 with ⟨reg1, r1, h11, h12, h13, rfl⟩,
rcases h2.2 with ⟨reg2, r2, h21, h22, h23, rfl⟩,
cases read_ModRM.determ_aux h12 h22,
cases h13.symm.trans h23, refl },
{ rcases h1 with ⟨imm1, code1, h11, h12, rfl⟩,
rcases h2 with ⟨imm2, code2, h21, h22, rfl⟩,
cases read_imm32.determ_aux h11 h21,
cases h12.symm.trans h22, refl },
{ rcases h1 with ⟨reg1, r1, code1, h11, h12, rfl⟩,
rcases h2 with ⟨reg2, r2, code2, h21, h22, rfl⟩,
cases read_ModRM.determ_aux h11 h21,
cases h12.symm.trans h22, refl },
{ rcases h1 with ⟨reg1, r1, code1, h11, h12, rfl⟩,
rcases h2 with ⟨reg2, r2, code2, h21, h22, rfl⟩,
cases read_ModRM.determ_aux h11 h21, refl },
{ rcases h1.2 with ⟨reg1, r1, h11, rfl⟩,
rcases h2.2 with ⟨reg2, r2, h21, rfl⟩,
cases read_ModRM.determ_aux h11 h21, refl },
{ rcases h1.2 with ⟨reg1, r1, h11, rfl⟩,
rcases h2.2 with ⟨reg2, r2, h21, rfl⟩,
cases read_ModRM.determ_aux h11 h21, refl },
end
theorem decode_two.determ {rex a₁ a₂ l}
(h₁ : decode_two rex a₁ l) (h₂ : decode_two rex a₂ l) : a₁ = a₂ :=
by cases decode_two.determ_aux h₁
(by rw list.append_nil; exact h₂); refl
def decode_hi' (v : bool) (sz : wsize) (r : RM) :
∀ (b0 b1 b2 x : bool), ast → list byte → Prop
| ff ff ff ff a l := ∃ imm,
read_imm sz imm l ∧
a = ast.binop binop.tst sz (dest_src.Rm_i r imm)
| ff tt ff ff a l := a = ast.unop unop.not sz r ∧ l = []
| tt tt ff ff a l := a = ast.unop unop.neg sz r ∧ l = []
| ff ff tt ff a l := a = ast.mul sz r ∧ l = []
| ff tt tt ff a l := a = ast.div sz r ∧ l = []
| ff ff ff tt a l := a = ast.unop unop.inc sz r ∧ l = []
| tt ff ff tt a l := a = ast.unop unop.dec sz r ∧ l = []
| ff tt ff tt a l := a = ast.call (imm_rm.rm r) ∧ l = []
| ff ff tt tt a l := a = ast.jump r ∧ l = []
| ff tt tt tt a l := a = ast.push (imm_rm.rm r) ∧ l = []
| _ _ _ _ a l := false
theorem decode_hi_hi' {v sz r x b0 b1 b2 a l}
(h : decode_hi v sz r x ⟨[b0, b1, b2], rfl⟩ a l) : decode_hi' v sz r b0 b1 b2 x a l :=
begin
generalize_hyp e : (⟨[b0, b1, b2], rfl⟩ : bitvec 3) = opc at h,
induction h; cases congr_arg subtype.val (bitvec.reify_eq' e),
exact ⟨_, h_a, rfl⟩, all_goals { exact ⟨rfl, rfl⟩ }
end
theorem decode_hi.determ_aux {v sz r x a₁ a₂ l l'} : ∀ {opc},
decode_hi v sz r x opc a₁ l → decode_hi v sz r x opc a₂ (l ++ l') → (a₁, l') = (a₂, [])
| ⟨[b0, b1, b2], _⟩ h1 h2 := begin
replace h1 := decode_hi_hi' h1,
replace h2 := decode_hi_hi' h2, clear decode_hi.determ_aux,
cases b0; cases b1; cases b2; cases x; cases h1; cases h2,
{ cases read_imm.determ_aux h1_h.1 h2_h.1,
cases h1_h.2.trans h2_h.2.symm, refl },
all_goals {
rw [h1_left, ← h2_left],
cases h1_right, cases h2_right, refl }
end
theorem decode_hi.determ {v sz r x opc a₁ a₂ l}
(h₁ : decode_hi v sz r x opc a₁ l) (h₂ : decode_hi v sz r x opc a₂ l) : a₁ = a₂ :=
by cases decode_hi.determ_aux h₁
(by rw list.append_nil; exact h₂); refl
def decode_aux' (rex : REX) (a : ast) (b0 b1 b2 b3 b4 b5 b6 b7 : bool) (l : list byte) : Prop :=
cond b7
(cond b6
(cond b5
(cond b4
(cond b2
(cond b1
( -- hi
let v := b0, sz := op_size_W rex v in
∃ opc r l1 l2,
read_opcode_ModRM rex opc r l1 ∧
decode_hi v sz r b3 opc a l2 ∧
l = l1 ++ l2)
( -- cmc
b0 = tt ∧
a = ast.cmc ∧
l = []))
( -- clc, stc
[b1, b3] = [ff, tt] ∧
a = cond b0 ast.stc ast.clc ∧
l = []))
(cond b0
( -- jump
[b2, b3] = [ff, tt] ∧
∃ imm,
(if b1 then read_imm8 imm l else read_imm32 imm l) ∧
a = ast.jcc cond_code.always imm)
( -- call
[b2, b3] = [ff, tt] ∧
∃ imm,
read_imm32 imm l ∧
a = ast.call (imm_rm.imm imm))))
( let v := b0, sz := op_size_W rex v in
cond b4
( -- binop_hi_reg
[b2, b3] = [ff, ff] ∧
∃ opc r op,
read_opcode_ModRM rex opc r l ∧ opc ≠ 6 ∧
binop.bits op (rex_reg tt opc) ∧
let src_dst := if b1 then dest_src.Rm_r r RCX else dest_src.Rm_i r 1 in
a = ast.binop op sz src_dst)
(cond b3
( -- leave
[b0, b1, b2] = [tt, ff, ff] ∧
a = ast.leave ∧
l = [])
(cond b2
( -- mov_imm
b1 = tt ∧
∃ opc r imm l1 l2,
read_opcode_ModRM rex opc r l1 ∧
read_imm sz imm l2 ∧
a = ast.mov sz (dest_src.Rm_i r imm) ∧
l = l1 ++ l2)
(cond b1
( -- ret
∃ imm,
(if v then imm = 0 ∧ l = [] else read_imm16 imm l) ∧
a = ast.ret imm)
( -- binop_hi
∃ opc r imm op l1 l2,
read_opcode_ModRM rex opc r l1 ∧ opc ≠ 6 ∧
binop.bits op (rex_reg tt opc) ∧
read_imm8 imm l2 ∧
a = ast.binop op sz (dest_src.Rm_i r imm) ∧
l = l1 ++ l2))))))
(cond b5
(cond b4
( -- mov64
let v := b3, sz := op_size_W rex v in
∃ imm,
read_full_imm sz imm l ∧
a = ast.mov sz (dest_src.Rm_i (RM.reg ⟨[b0, b1, b2, rex.B], rfl⟩) imm))
( -- test_rax
[b1, b2, b3] = [ff, ff, tt] ∧
let v := b0, sz := op_size tt rex.W v in
∃ imm,
read_imm sz imm l ∧
a = ast.binop binop.tst sz (dest_src.Rm_i (RM.reg RAX) imm)))
(cond b4
( -- xchg_rax
b3 = ff ∧
let sz := op_size tt rex.W tt in
a = ast.xchg sz (RM.reg RAX) ⟨[b0, b1, b2, rex.B], rfl⟩ ∧
l = [])
(cond b3
(cond b2
(cond b1
( -- pop_rm
b0 = tt ∧
∃ r,
read_opcode_ModRM rex 0 r l ∧
a = ast.pop r)
( -- lea
b0 = tt ∧
∃ reg r,
let sz := op_size tt rex.W tt in
read_ModRM rex reg r l ∧ RM.is_mem r ∧
a = ast.lea sz (dest_src.R_rm reg r)))
( -- mov
let v := b0, sz := op_size_W rex v in
∃ reg r,
read_ModRM rex reg r l ∧
let src_dst := if b1 then dest_src.R_rm reg r else dest_src.Rm_r r reg in
a = ast.mov sz src_dst))
(cond b2
( let v := b0, sz := op_size_W rex v in
-- xchg, test
∃ reg r,
read_ModRM rex reg r l ∧
a = cond b1 (ast.xchg sz r reg)
(ast.binop binop.tst sz (dest_src.Rm_r r reg)))
( -- binop_imm, binop_imm8
let sz := op_size_W rex (cond b1 tt b0) in
∃ opc r l1 imm l2 op,
read_opcode_ModRM rex opc r l1 ∧
binop.bits op (EXTZ opc) ∧
cond b1 (read_imm8 imm l2) (read_imm sz imm l2) ∧
a = ast.binop op sz (dest_src.Rm_i r imm) ∧
l = l1 ++ l2))))))
(cond b6
(cond b5
(cond b4
( -- jcc8
∃ code imm,
cond_code.from_bits b0 b1 b2 b3 = some code ∧
read_imm8 imm l ∧
a = ast.jcc code imm)
(cond b3
( -- push_imm
[b0, b2] = [ff, ff] ∧
∃ imm,
read_imm (if b1 then wsize.Sz8 ff else wsize.Sz32) imm l ∧
a = ast.push (imm_rm.imm imm))
( -- movsx
[b0, b1, b2] = [tt, tt, ff] ∧
∃ reg r,
read_ModRM rex reg r l ∧
a = ast.movsx wsize.Sz32 (dest_src.R_rm reg r) wsize.Sz64)))
(cond b4
( -- pop, push_rm
let reg := RM.reg ⟨[b0, b1, b2, rex.B], rfl⟩ in
a = cond b3 (ast.pop reg) (ast.push (imm_rm.rm reg)) ∧
l = [])
( -- prefix byte
false)))
(cond b2
(cond b1
( -- decode_two
[b0, b3, b4, b5] = [tt, tt, ff, ff] ∧
decode_two rex a l)
( -- binop_imm_rax
let v := b0, sz := op_size_W rex v,
op := binop.from_bits b3 b4 b5 ff in
∃ imm, read_imm sz imm l ∧
a = ast.binop op sz (dest_src.Rm_i (RM.reg RAX) imm)))
( -- binop1
let v := b0, d := b1, sz := op_size_W rex v,
op := binop.from_bits b3 b4 b5 ff in
∃ reg r, read_ModRM rex reg r l ∧
let src_dst := if d then dest_src.R_rm reg r else dest_src.Rm_r r reg in
a = ast.binop op sz src_dst)))
theorem decode_aux_aux' {rex a b0 b1 b2 b3 b4 b5 b6 b7 l} :
decode_aux rex a (⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩ :: l) →
decode_aux' rex a b0 b1 b2 b3 b4 b5 b6 b7 l :=
begin
generalize e : (⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩ :: l : list byte) = l',
intro a, cases a,
{ cases e, rcases split_bits_ok a_a with ⟨⟨⟩, ⟨⟩, ⟨⟩, h₁, h₂, _⟩,
cases subtype.eq h₁,
cases bitvec.reify_eq h₂,
cases binop.bits_eq a_a_2,
exact ⟨_, _, a_a_1, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, h₂, h₃, _⟩,
cases bitvec.reify_eq h₁,
cases subtype.eq h₂,
cases bitvec.reify_eq h₃,
cases binop.bits_eq a_a_1,
exact ⟨_, a_a_2, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩,
cases bitvec.reify_eq h₁,
exact ⟨_, _, _, _, _, _, a_a_1, a_a_3, a_a_2, rfl, rfl⟩ },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
exact ⟨_, _, _, _, _, _, a_a, a_a_1, a_a_2, rfl, h_2⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩,
cases bitvec.reify_eq h₁,
exact ⟨_, _, _, _, _, _, a_a_1, a_a_2, a_a_3, a_a_4, rfl, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨⟨⟩, ⟨⟩, h₁, _⟩,
cases bitvec.reify_eq h₁,
exact ⟨rfl, _, _, _, a_a_1, a_a_2, a_a_3, rfl⟩ },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact ⟨rfl, a_a_1⟩ },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact ⟨rfl, _, _, a_a, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨⟨⟩, ⟨⟩, h₁, _⟩,
cases bitvec.reify_eq h₁,
exact ⟨_, _, a_a_1, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨h₁, ⟨⟩, h₂, _⟩,
cases subtype.eq h₁,
cases bitvec.reify_eq h₂,
exact ⟨_, a_a_1, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩,
cases bitvec.reify_eq h₁,
exact ⟨rfl, _, _, _, _, _, a_a_1, a_a_2, rfl, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩,
cases bitvec.reify_eq h₁,
exact ⟨_, _, a_a_1, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨h₁, h₂, _⟩,
cases subtype.eq h₁,
cases bitvec.reify_eq h₂,
exact ⟨rfl, rfl, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨⟨⟩, ⟨⟩, h₁, _⟩,
cases bitvec.reify_eq h₁,
exact ⟨rfl, _, a_a_1, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨h₁, h₂, _⟩,
cases subtype.eq h₁,
cases bitvec.reify_eq h₂,
exact ⟨rfl, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨h₁, h₂, _⟩,
cases subtype.eq h₁,
cases bitvec.reify_eq h₂,
exact ⟨rfl, rfl⟩ },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact ⟨rfl, _, a_a, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨⟨⟩, ⟨⟩, h₁, _⟩,
cases bitvec.reify_eq h₁,
exact ⟨rfl, _, a_a_1, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨h₁, h₂, _⟩,
cases subtype.eq h₁,
cases bitvec.reify_eq h₂,
exact ⟨_, _, cond_code.bits_eq a_a_1, a_a_2, rfl⟩ },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact ⟨rfl, _, a_a, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩,
cases bitvec.reify_eq h₁,
exact ⟨_, a_a_1, rfl⟩ },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact ⟨rfl, rfl, rfl⟩ },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact ⟨rfl, _, _, a_a, a_a_1, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩,
cases bitvec.reify_eq h₁,
exact ⟨_, _, a_a_1, rfl⟩ },
{ cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩,
cases bitvec.reify_eq h₁,
exact ⟨rfl, _, a_a_1, rfl⟩ },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact ⟨rfl, rfl, rfl⟩ },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact ⟨rfl, rfl, rfl⟩ },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact ⟨rfl, rfl, rfl⟩ },
{ cases e, rcases split_bits_ok a_a_1 with ⟨⟨⟩, h₁, ⟨⟩, h₂, _⟩,
cases bitvec.reify_eq h₁,
cases bitvec.reify_eq h₂,
exact ⟨_, _, _, _, a_a_2, a_a_3, rfl⟩ },
end
theorem decode_aux_nil {rex a} : ¬ decode_aux rex a [].
theorem decode_aux.determ_aux {rex a₁ a₂ l l'} :
decode_aux rex a₁ l → decode_aux rex a₂ (l ++ l') → (a₁, l') = (a₂, []) :=
begin
cases l with b l, {exact decode_aux_nil.elim},
apply byte_split b, introv h1 h2,
replace h1 := decode_aux_aux' h1,
replace h2 := decode_aux_aux' h2,
unfold decode_aux' at h1 h2,
repeat { do
`(cond %%e _ _) ← tactic.get_local `h1 >>= tactic.infer_type,
tactic.cases e $> (); `[dsimp only [cond] at h1 h2] },
{ rcases h1 with ⟨reg1, r1, h11, rfl⟩,
rcases h2 with ⟨reg2, r2, h21, rfl⟩,
cases read_ModRM.determ_aux h11 h21, refl },
{ rcases h1 with ⟨imm1, h11, rfl⟩,
rcases h2 with ⟨imm2, h21, rfl⟩,
cases read_imm.determ_aux h11 h21, refl },
{ exact decode_two.determ_aux h1.2 h2.2 },
{ cases h2 },
{ rcases h1 with ⟨rfl, rfl⟩,
rcases h2 with ⟨rfl, ⟨⟩⟩, refl },
{ rcases h1.2 with ⟨reg1, r1, h11, rfl⟩,
rcases h2.2 with ⟨reg2, r2, h21, rfl⟩,
cases read_ModRM.determ_aux h11 h21, refl },
{ rcases h1.2 with ⟨imm1, h11, rfl⟩,
rcases h2.2 with ⟨imm2, h21, rfl⟩,
cases read_imm.determ_aux h11 h21, refl },
{ rcases h1 with ⟨code1, imm1, h11, h12, rfl⟩,
rcases h2 with ⟨code2, imm2, h21, h22, rfl⟩,
cases h11.symm.trans h21,
cases read_imm8.determ_aux h12 h22, refl },
{ rcases h1 with ⟨opc1, r1, l11, imm1, l12, op1, h11, h12, h13, rfl, rfl⟩,
rcases h2 with ⟨opc2, r2, l21, imm2, l22, op2, h21, h22, h23, rfl, e⟩,
cases read_opcode_ModRM.determ₂_aux h11 h21 e,
cases binop.bits.determ h12 h22,
cases b1,
{ cases read_imm.determ_aux h13 h23, refl },
{ cases read_imm8.determ_aux h13 h23, refl } },
{ rcases h1 with ⟨reg1, r1, h11, rfl⟩,
rcases h2 with ⟨reg2, r2, h21, rfl⟩,
cases read_ModRM.determ_aux h11 h21, refl },
{ rcases h1 with ⟨reg1, r1, h11, rfl⟩,
rcases h2 with ⟨reg2, r2, h21, rfl⟩,
cases read_ModRM.determ_aux h11 h21, refl },
{ rcases h1.2 with ⟨reg1, r1, h11, h12, rfl⟩,
rcases h2.2 with ⟨reg2, r2, h21, h22, rfl⟩,
cases read_ModRM.determ_aux h11 h21, refl },
{ rcases h1.2 with ⟨r1, h11, h12, rfl⟩,
rcases h2.2 with ⟨r2, h21, h22, rfl⟩,
cases read_opcode_ModRM.determ_aux h11 h21, refl },
{ rcases h1.2 with ⟨rfl, rfl⟩,
rcases h2.2 with ⟨rfl, ⟨⟩⟩, refl },
{ rcases h1.2 with ⟨imm1, h11, rfl⟩,
rcases h2.2 with ⟨imm2, h21, rfl⟩,
cases read_imm.determ_aux h11 h21, refl },
{ rcases h1 with ⟨imm1, h11, rfl⟩,
rcases h2 with ⟨imm2, h21, rfl⟩,
cases read_full_imm.determ_aux h11 h21, refl },
{ rcases h1 with ⟨opc1, r1, imm1, op1, l11, l12, h11, _, h12, h13, rfl, rfl⟩,
rcases h2 with ⟨opc2, r2, imm2, op2, l21, l22, h21, _, h22, h23, rfl, e⟩,
cases read_opcode_ModRM.determ₂_aux h11 h21 e,
cases binop.bits.determ h12 h22,
cases read_imm8.determ_aux h13 h23, refl },
{ rcases h1 with ⟨imm1, h11, rfl⟩,
rcases h2 with ⟨imm2, h21, rfl⟩,
split_ifs at h11 h21,
{ rcases h11 with ⟨rfl, rfl⟩,
rcases h21 with ⟨rfl, ⟨⟩⟩, refl },
{ cases read_imm16.determ_aux h11 h21, refl } },
{ rcases h1 with ⟨opc1, r1, imm1, op1, l11, l12, h11, h12, rfl, rfl⟩,
rcases h2 with ⟨opc2, r2, imm2, op2, l21, l22, h21, h22, rfl, e⟩,
cases read_opcode_ModRM.determ₂_aux h11 h21 e,
cases read_imm.determ_aux h12 h22, refl },
{ rcases h1.2 with ⟨rfl, rfl⟩,
rcases h2.2 with ⟨rfl, ⟨⟩⟩, refl },
{ rcases h1.2 with ⟨opc1, r1, op1, h11, _, h12, rfl⟩,
rcases h2.2 with ⟨opc2, r2, op2, h21, _, h22, rfl⟩,
cases read_opcode_ModRM.determ_aux h11 h21,
cases binop.bits.determ h12 h22, refl },
{ rcases h1.2 with ⟨imm1, h11, rfl⟩,
rcases h2.2 with ⟨imm2, h21, rfl⟩,
cases read_imm32.determ_aux h11 h21, refl },
{ rcases h1.2 with ⟨imm1, h11, rfl⟩,
rcases h2.2 with ⟨imm2, h21, rfl⟩,
split_ifs at h11 h21,
{ cases read_imm8.determ_aux h11 h21, refl },
{ cases read_imm32.determ_aux h11 h21, refl } },
{ rcases h1.2 with ⟨rfl, rfl⟩,
rcases h2.2 with ⟨rfl, ⟨⟩⟩, refl },
{ rcases h1.2 with ⟨rfl, rfl⟩,
rcases h2.2 with ⟨rfl, ⟨⟩⟩, refl },
{ rcases h1 with ⟨opc1, r1, l11, l12, h11, h12, rfl⟩,
rcases h2 with ⟨opc2, r2, l21, l22, h21, h22, e⟩,
cases read_opcode_ModRM.determ₂_aux h11 h21 e,
exact decode_hi.determ_aux h12 h22 },
end
theorem decode_aux.determ {rex a₁ a₂ l}
(h₁ : decode_aux rex a₁ l) (h₂ : decode_aux rex a₂ l) : a₁ = a₂ :=
by cases decode_aux.determ_aux h₁
(by rw list.append_nil; exact h₂); refl
theorem decode.no_prefix {rex rex' a l b l'} :
read_prefixes rex l → b ∈ l → ¬ decode_aux rex' a (b :: l') :=
begin
rintro ⟨⟩ (rfl|⟨⟨⟩⟩),
-- generalize e : b :: l' = l₂,
revert a_1_a, apply byte_split b, intros,
rcases split_bits_ok a_1_a with ⟨_, ⟨⟩, _⟩,
exact decode_aux_aux'
end
theorem decode_nil {a} : ¬ decode a [] :=
begin
generalize e : [] = l, rintro ⟨⟩,
cases a_1_l1; cases e,
exact decode_aux_nil a_1_a_2
end
theorem decode.determ_aux {a₁ a₂ l l'}
(h₁ : decode a₁ l) (h₂ : decode a₂ (l ++ l')) : (a₁, l') = (a₂, []) :=
begin
generalize_hyp e : l ++ l' = x at h₂,
induction h₁, induction h₂,
rw [list.append_assoc, list.append_eq_append_iff] at e,
rcases e with ⟨_|⟨b, x⟩, rfl, e⟩ | ⟨_|⟨b, x⟩, rfl, rfl⟩,
{ rw list.append_nil at h₂_a_1, cases e,
cases read_prefixes.determ h₁_a_1 h₂_a_1,
exact decode_aux.determ_aux h₁_a_2 h₂_a_2 },
{ cases h₁_l2 with b' l2, cases decode_aux_nil h₁_a_2,
injection e, subst b',
cases decode.no_prefix h₂_a_1 (list.mem_append_right _ (or.inl rfl)) h₁_a_2 },
{ rw list.append_nil at h₁_a_1,
cases read_prefixes.determ h₁_a_1 h₂_a_1,
exact decode_aux.determ_aux h₁_a_2 h₂_a_2 },
{ cases decode.no_prefix h₁_a_1 (list.mem_append_right _ (or.inl rfl)) h₂_a_2 },
end
theorem decode.determ {a₁ a₂ l}
(h₁ : decode a₁ l) (h₂ : decode a₂ l) : a₁ = a₂ :=
by cases decode.determ_aux h₁
(by rw list.append_nil; exact h₂); refl
instance : add_comm_monoid perm :=
{ zero := ⟨ff, ff, ff⟩,
add_assoc := λ a b c,
show perm.mk (_||_||_) (_||_||_) (_||_||_) = _,
by repeat {rw bool.bor_assoc}; refl,
zero_add := λ ⟨r, w, x⟩,
show perm.mk (ff||_) (ff||_) (ff||_) = _,
by repeat {rw ff_bor},
add_zero := λ ⟨r, w, x⟩,
show perm.mk (_||ff) (_||ff) (_||ff) = _,
by repeat {rw bor_ff},
add_comm := λ a b,
show perm.mk (_||_) (_||_) (_||_) = _,
by rw [bool.bor_comm, bool.bor_comm a.isW, bool.bor_comm a.isX]; refl,
..perm.has_add }
theorem perm.add_self : ∀ p : perm, p + p = p
| ⟨r, w, x⟩ :=
show perm.mk (r||r) (w||w) (x||x) = _,
by repeat {rw bor_self}
instance : partial_order perm :=
{ le_refl := perm.add_self,
le_trans := λ a b c (h₁ : a + b = b) (h₂ : b + c = c),
show a + c = c, by rw [← h₂, ← add_assoc, h₁],
le_antisymm := λ a b (h₁ : a + b = b) (h₂ : b + a = a),
by rw [← h₂, add_comm, h₁],
..perm.has_le }
theorem perm.le_add_left {p₁ p₂ : perm} : p₁ ≤ p₁ + p₂ :=
show _=_, by rw [← add_assoc, perm.add_self]
theorem mem.read1.determ {p1 p2 m a b1 b2} :
mem.read1 p1 m a b1 → mem.read1 p2 m a b2 → b1 = b2 :=
by rintro ⟨_, rfl, _⟩ ⟨_, rfl, _⟩; refl
theorem mem.read'.determ_aux {p1 p2 m a l1 l2}
(h₁ : mem.read' p1 m a l1) (h₂ : mem.read' p2 m a l2) :
l1 <+: l2 ∨ l2 <+: l1 :=
begin
induction h₁ generalizing l2,
{ exact or.inl (list.nil_prefix _) },
cases h₂,
{ exact or.inr (list.nil_prefix _) },
cases h₁_a.determ h₂_a,
rw [list.prefix_cons_inj, list.prefix_cons_inj],
exact h₁_ih h₂_a_1,
end
theorem mem.read'.determ_len {p1 p2 m a l1 l2}
(h₁ : mem.read' p1 m a l1) (h₂ : mem.read' p2 m a l2)
(h : l1.length = l2.length) : l1 = l2 :=
(mem.read'.determ_aux h₁ h₂).elim
(λ h', list.eq_of_prefix_of_length_eq h' h)
(λ h', (list.eq_of_prefix_of_length_eq h' h.symm).symm)
theorem mem_decode.determ {p1 p2 m a l1 l2 ast1 ast2}
(m₁ : mem.read' p1 m a l1) (h₁ : decode ast1 l1)
(m₂ : mem.read' p2 m a l2) (h₂ : decode ast2 l2) :
(ast1, l1) = (ast2, l2) :=
begin
rcases mem.read'.determ_aux m₁ m₂ with ⟨x, rfl⟩ | ⟨x, rfl⟩,
{ cases decode.determ_aux h₁ h₂, simp },
{ cases decode.determ_aux h₂ h₁, simp },
end
theorem config.step_noIO {k k₁ k₂} :
config.step k k₁ → ¬ config.isIO k k₂ :=
λ h₁ h₂, begin
cases h₁, cases h₂,
cases mem_decode.determ h₁_a_1 h₁_a_2 h₂_a h₂_a_1,
rcases h₁_a_3 with ⟨_, s₁, _, ⟨⟩, _⟩
end
theorem mem.write1.determ {m a b m₁ m₂}
(h₁ : mem.write1 m a b m₁)
(h₂ : mem.write1 m a b m₂) : m₁ = m₂ :=
by cases h₁; cases h₂; refl
theorem mem.write.determ {m a l m₁ m₂}
(h₁ : mem.write m a l m₁)
(h₂ : mem.write m a l m₂) : m₁ = m₂ :=
begin
induction h₁ generalizing m₂; cases h₂, refl,
cases mem.write1.determ h₁_a h₂_a,
cases h₁_ih h₂_a_1, refl
end
theorem config.write_mem.determ {k a l k₁ k₂}
(h₁ : config.write_mem k a l k₁)
(h₂ : config.write_mem k a l k₂) : k₁ = k₂ :=
by cases h₁; cases h₂; cases mem.write.determ h₁_a_1 h₂_a_1; refl
theorem EA.write.determ {k ea sz v k₁ k₂}
(h₁ : EA.write k ea sz v k₁)
(h₂ : EA.write k ea sz v k₂) : k₁ = k₂ :=
begin
cases h₁; cases h₂, refl,
cases bits_to_byte.determ h₁_a_1 h₂_a_1,
exact config.write_mem.determ h₁_a_2 h₂_a_2
end
theorem config.isIO.determ {k k₁ k₂} :
config.isIO k k₁ → config.isIO k k₂ →
∃ k' v₁ v₂,
k₁ = config.set_reg k' 11 v₁ ∧
k₂ = config.set_reg k' 11 v₂ :=
begin
rintro ⟨l₁, _, m₁, d₁, _, _, ⟨⟩, ⟨⟩, k', a₁, q₁, _, ⟨⟨⟩, rfl⟩, h₁⟩
⟨l₂, _, m₂, d₂, _, _, ⟨⟩, ⟨⟩, k'', a₂, q₂, _, ⟨⟨⟩, rfl⟩, h₂⟩,
cases mem_decode.determ m₁ d₁ m₂ d₂,
cases EA.write.determ a₁ a₂,
cases h₁, cases h₂,
exact ⟨_, _, _, rfl, rfl⟩
end
theorem config.step.no_exit {k k₁ r} :
config.step k k₁ → ¬ config.exit k r :=
λ h ⟨k', h', _⟩, config.step_noIO h h'
theorem set_reg_ne {k r r' q} (h : r' ≠ r) :
(config.set_reg k r q).regs r' = k.regs r' :=
if_neg h
theorem config.set_reg_11_exec_exit {k v r} :
exec_exit (config.set_reg k 11 v) r ↔ exec_exit k r :=
begin
split; rintro ⟨e⟩; split,
{ rwa set_reg_ne at e, rintro ⟨⟩ },
{ rwa set_reg_ne, rintro ⟨⟩ },
end
theorem config.isIO.determ_exec {k k₁ k₂ r}
(h₁ : config.isIO k k₁) (h₂ : config.isIO k k₂) :
exec_exit k₁ r ↔ exec_exit k₂ r :=
begin
rcases h₁.determ h₂ with ⟨k', v₁, v₂, rfl, rfl⟩,
simp [config.set_reg_11_exec_exit],
end
theorem exec_io.no_exit {i o k i' o' k' ret r} :
exec_io i o k (k.regs RAX) i' o' k' ret → ¬ exec_exit k r :=
begin
rintro h ⟨e⟩, rw e at h,
rcases h with ⟨_, _, _, _, e⟩ | ⟨_, _, _, _, _, _, _, e⟩;
cases bitvec.reify_eq₂ e,
end
theorem read_from_fd.io_part {fd i H_dat i'}
(H : read_from_fd fd i H_dat i') : i' <:+ i :=
begin
cases H, apply list.suffix_refl,
exact ⟨_, rfl⟩
end
theorem exec_read.io_part {i k fd count i' k' ret}
(H : exec_read i k fd count i' k' ret) : i' <:+ i :=
begin
cases H, apply list.suffix_refl,
exact read_from_fd.io_part H_a_2
end
theorem exec_io.io_part {k₁ i₁ o₁ k₂ i₂ o₂ call ret}
(H : exec_io i₁ o₁ k₁ call i₂ o₂ k₂ ret) :
i₂ <:+ i₁ ∧ o₁ <+: o₂ :=
begin
induction H, exact ⟨list.suffix_refl _, list.prefix_refl _⟩,
exact ⟨exec_read.io_part H_a_2, list.prefix_refl _⟩,
end
theorem kcfg.step.no_exit {k k' r} :
kcfg.step k k' → ¬ config.exit k.k r :=
begin
rintro (⟨_, _, _, _, h⟩ | ⟨_, _, k₁, k₂, _, _, _, _, h₁, h⟩),
{ exact h.no_exit },
{ rintro ⟨k₃, h₂, e⟩,
exact h.no_exit ((h₁.determ_exec h₂).2 e) },
end
theorem kcfg.step.io_part {k₁ i₁ o₁ k₂ i₂ o₂}
(H : kcfg.step ⟨i₁, o₁, k₁⟩ ⟨i₂, o₂, k₂⟩) :
i₂ <:+ i₁ ∧ o₁ <+: o₂ :=
begin
cases H, exact ⟨list.suffix_refl _, list.prefix_refl _⟩,
exact exec_io.io_part H_a_1
end
@[simp] theorem EXTZ_id {n} (w : bitvec n) : EXTZ w = w :=
begin
suffices : ∀ l n, list.length l = n → (@EXTZ_aux l n).to_list = l,
{ exact subtype.eq (this w.1 _ w.2) },
intro l, induction l; intros n e; cases e, {refl},
unfold EXTZ_aux, rw [vector.to_list_cons, l_ih _ rfl],
end
@[simp] theorem EXTS_id {n} (w : bitvec n) : EXTS w = w :=
begin
suffices : ∀ l a n, list.length l = n → (@EXTS_aux l a n).to_list = l,
{ exact subtype.eq (this w.1 _ _ w.2) },
intro l, induction l; intros n a e; cases e, {refl},
unfold EXTS_aux, rw [vector.to_list_cons, l_ih _ _ rfl],
end
theorem EA.read_reg_64 {r k q} :
(EA.r r).read k wsize.Sz64 q ↔ q = k.regs r :=
by simp [EA.read]
theorem EA.readq_reg_64 {r k q} :
(EA.r r).readq k wsize.Sz64 q ↔ q = k.regs r :=
by simp [EA.readq, EA.read_reg_64]
theorem EA.write_reg_64 {r k q k'} :
(EA.r r).write k wsize.Sz64 q k' ↔ k' = k.set_reg r q :=
by split; [{rintro ⟨⟩, refl}, {rintro rfl, constructor}]
theorem EA.writeq_reg_64 {r k q k'} :
(EA.r r).writeq k wsize.Sz64 q k' ↔ k' = k.set_reg r q :=
by simp [EA.writeq, EA.write_reg_64]
theorem mem.set.read'_exists {p m q w b v}
(h1 : mem.read' p m q v) : ∃ v', mem.read' p (m.set w b) q v' :=
begin
induction h1, {exact ⟨_, mem.read'.nil _⟩},
cases h1_ih with v1 ih,
rcases h1_a with ⟨_, rfl, h1⟩,
exact ⟨_, mem.read'.cons ⟨_, rfl, h1⟩ ih⟩,
end
theorem mem.write.read'_exists {p m q a v v2 m'}
(h1 : mem.read' p m q v) (h2 : mem.write m a v2 m') :
∃ v', mem.read' p m' q v' :=
begin
induction h2 generalizing v, {exact ⟨_, h1⟩},
cases h2_a with h3 h4,
cases mem.set.read'_exists h1 with v1 h1,
exact h2_ih h1,
end
theorem EA.read.determ {k ea sz w1 w2}
(h1 : EA.read k ea sz w1) (h2 : EA.read k ea sz w2) : w1 = w2 :=
begin
cases ea,
{ exact h1.trans h2.symm },
{ cases sz, cases sz, all_goals {exact h1.trans h2.symm} },
{ rcases h1 with ⟨_, a1, b1⟩,
rcases h2 with ⟨_, a2, b2⟩,
cases a1.determ_len a2 (b1.1.trans b2.1.symm),
exact bits_to_byte.determ_l b1 b2 },
end
theorem EA.readq.determ {k ea sz q1 q2} :
EA.readq k ea sz q1 → EA.readq k ea sz q2 → q1 = q2
| ⟨a1, b1, e1⟩ ⟨a2, b2, e2⟩ :=
by cases b1.determ b2; exact e1.trans e2.symm
theorem hoare_p.bind {P P' : kcfg → Prop}
(H : ∀ {{k}}, P k → hoare_p P' k) {k} : hoare_p P k → hoare_p P' k :=
begin
intro h, induction h,
exact H h_a,
exact hoare_p.step h_a (λ k', h_ih _),
by_cases h_ret = 0,
{ cases H (h_a_1 h),
{ exact hoare_p.zero a },
{ cases a with k' h, cases h.no_exit h_a },
{ exact hoare_p.exit _ _ a a_1 } },
{ exact hoare_p.exit _ _ h_a h.elim },
end
theorem hoare_p.mono {P P' : kcfg → Prop}
(H : ∀ {{k}}, P k → P' k) {k} : hoare_p P k → hoare_p P' k :=
hoare_p.bind (λ k h, hoare_p.zero (H h))
end x86
|
e8813162b0500c789389bc167933d111217fe428
|
649957717d58c43b5d8d200da34bf374293fe739
|
/src/category_theory/limits/limits.lean
|
58959b1adc003455918c443c8da79c7b3c86e090
|
[
"Apache-2.0"
] |
permissive
|
Vtec234/mathlib
|
b50c7b21edea438df7497e5ed6a45f61527f0370
|
fb1848bbbfce46152f58e219dc0712f3289d2b20
|
refs/heads/master
| 1,592,463,095,113
| 1,562,737,749,000
| 1,562,737,749,000
| 196,202,858
| 0
| 0
|
Apache-2.0
| 1,562,762,338,000
| 1,562,762,337,000
| null |
UTF-8
|
Lean
| false
| false
| 31,729
|
lean
|
-- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Reid Barton, Mario Carneiro, Scott Morrison, Floris van Doorn
import category_theory.whiskering
import category_theory.yoneda
import category_theory.limits.cones
import category_theory.eq_to_hom
open category_theory category_theory.category category_theory.functor opposite
namespace category_theory.limits
universes v u u' u'' w -- declare the `v`'s first; see `category_theory.category` for an explanation
-- See the notes at the top of cones.lean, explaining why we can't allow `J : Prop` here.
variables {J K : Type v} [small_category J] [small_category K]
variables {C : Type u} [𝒞 : category.{v+1} C]
include 𝒞
variables {F : J ⥤ C}
/-- A cone `t` on `F` is a limit cone if each cone on `F` admits a unique
cone morphism to `t`. -/
structure is_limit (t : cone F) :=
(lift : Π (s : cone F), s.X ⟶ t.X)
(fac' : ∀ (s : cone F) (j : J), lift s ≫ t.π.app j = s.π.app j . obviously)
(uniq' : ∀ (s : cone F) (m : s.X ⟶ t.X) (w : ∀ j : J, m ≫ t.π.app j = s.π.app j),
m = lift s . obviously)
restate_axiom is_limit.fac'
attribute [simp] is_limit.fac
restate_axiom is_limit.uniq'
attribute [class] is_limit
namespace is_limit
instance subsingleton {t : cone F} : subsingleton (is_limit t) :=
⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩
/- Repackaging the definition in terms of cone morphisms. -/
def lift_cone_morphism {t : cone F} (h : is_limit t) (s : cone F) : s ⟶ t :=
{ hom := h.lift s }
lemma uniq_cone_morphism {s t : cone F} (h : is_limit t) {f f' : s ⟶ t} :
f = f' :=
have ∀ {g : s ⟶ t}, g = h.lift_cone_morphism s, by intro g; ext; exact h.uniq _ _ g.w,
this.trans this.symm
def mk_cone_morphism {t : cone F}
(lift : Π (s : cone F), s ⟶ t)
(uniq' : ∀ (s : cone F) (m : s ⟶ t), m = lift s) : is_limit t :=
{ lift := λ s, (lift s).hom,
uniq' := λ s m w,
have cone_morphism.mk m w = lift s, by apply uniq',
congr_arg cone_morphism.hom this }
/-- Limit cones on `F` are unique up to isomorphism. -/
def unique {s t : cone F} (P : is_limit s) (Q : is_limit t) : s ≅ t :=
{ hom := Q.lift_cone_morphism s,
inv := P.lift_cone_morphism t,
hom_inv_id' := P.uniq_cone_morphism,
inv_hom_id' := Q.uniq_cone_morphism }
def of_iso_limit {r t : cone F} (P : is_limit r) (i : r ≅ t) : is_limit t :=
is_limit.mk_cone_morphism
(λ s, P.lift_cone_morphism s ≫ i.hom)
(λ s m, by rw ←i.comp_inv_eq; apply P.uniq_cone_morphism)
variables {t : cone F}
lemma hom_lift (h : is_limit t) {W : C} (m : W ⟶ t.X) :
m = h.lift { X := W, π := { app := λ b, m ≫ t.π.app b } } :=
h.uniq { X := W, π := { app := λ b, m ≫ t.π.app b } } m (λ b, rfl)
/-- Two morphisms into a limit are equal if their compositions with
each cone morphism are equal. -/
lemma hom_ext (h : is_limit t) {W : C} {f f' : W ⟶ t.X}
(w : ∀ j, f ≫ t.π.app j = f' ≫ t.π.app j) : f = f' :=
by rw [h.hom_lift f, h.hom_lift f']; congr; exact funext w
/-- The universal property of a limit cone: a map `W ⟶ X` is the same as
a cone on `F` with vertex `W`. -/
def hom_iso (h : is_limit t) (W : C) : (W ⟶ t.X) ≅ ((const J).obj W ⟶ F) :=
{ hom := λ f, (t.extend f).π,
inv := λ π, h.lift { X := W, π := π },
hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl }
@[simp] lemma hom_iso_hom (h : is_limit t) {W : C} (f : W ⟶ t.X) :
(is_limit.hom_iso h W).hom f = (t.extend f).π := rfl
/-- The limit of `F` represents the functor taking `W` to
the set of cones on `F` with vertex `W`. -/
def nat_iso (h : is_limit t) : yoneda.obj t.X ≅ F.cones :=
nat_iso.of_components (λ W, is_limit.hom_iso h (unop W)) (by tidy)
def hom_iso' (h : is_limit t) (W : C) :
((W ⟶ t.X) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j'} (f : j ⟶ j'), p j ≫ F.map f = p j' } :=
h.hom_iso W ≪≫
{ hom := λ π,
⟨λ j, π.app j, λ j j' f,
by convert ←(π.naturality f).symm; apply id_comp⟩,
inv := λ p,
{ app := λ j, p.1 j,
naturality' := λ j j' f, begin dsimp, rw [id_comp], exact (p.2 f).symm end } }
/-- If G : C → D is a faithful functor which sends t to a limit cone,
then it suffices to check that the induced maps for the image of t
can be lifted to maps of C. -/
def of_faithful {t : cone F} {D : Type u'} [category.{v+1} D] (G : C ⥤ D) [faithful G]
(ht : is_limit (G.map_cone t)) (lift : Π (s : cone F), s.X ⟶ t.X)
(h : ∀ s, G.map (lift s) = ht.lift (G.map_cone s)) : is_limit t :=
{ lift := lift,
fac' := λ s j, by apply G.injectivity; rw [G.map_comp, h]; apply ht.fac,
uniq' := λ s m w, begin
apply G.injectivity, rw h,
refine ht.uniq (G.map_cone s) _ (λ j, _),
convert ←congr_arg (λ f, G.map f) (w j),
apply G.map_comp
end }
end is_limit
def is_limit_iso_unique_cone_morphism {t : cone F} :
is_limit t ≅ Π s, unique (s ⟶ t) :=
{ hom := λ h s,
{ default := h.lift_cone_morphism s,
uniq := λ _, h.uniq_cone_morphism },
inv := λ h,
{ lift := λ s, (h s).default.hom,
uniq' := λ s f w, congr_arg cone_morphism.hom ((h s).uniq ⟨f, w⟩) } }
/-- A cocone `t` on `F` is a colimit cocone if each cocone on `F` admits a unique
cocone morphism from `t`. -/
structure is_colimit (t : cocone F) :=
(desc : Π (s : cocone F), t.X ⟶ s.X)
(fac' : ∀ (s : cocone F) (j : J), t.ι.app j ≫ desc s = s.ι.app j . obviously)
(uniq' : ∀ (s : cocone F) (m : t.X ⟶ s.X) (w : ∀ j : J, t.ι.app j ≫ m = s.ι.app j),
m = desc s . obviously)
restate_axiom is_colimit.fac'
attribute [simp] is_colimit.fac
restate_axiom is_colimit.uniq'
attribute [class] is_colimit
namespace is_colimit
instance subsingleton {t : cocone F} : subsingleton (is_colimit t) :=
⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩
/- Repackaging the definition in terms of cone morphisms. -/
def desc_cocone_morphism {t : cocone F} (h : is_colimit t) (s : cocone F) : t ⟶ s :=
{ hom := h.desc s }
lemma uniq_cocone_morphism {s t : cocone F} (h : is_colimit t) {f f' : t ⟶ s} :
f = f' :=
have ∀ {g : t ⟶ s}, g = h.desc_cocone_morphism s, by intro g; ext; exact h.uniq _ _ g.w,
this.trans this.symm
def mk_cocone_morphism {t : cocone F}
(desc : Π (s : cocone F), t ⟶ s)
(uniq' : ∀ (s : cocone F) (m : t ⟶ s), m = desc s) : is_colimit t :=
{ desc := λ s, (desc s).hom,
uniq' := λ s m w,
have cocone_morphism.mk m w = desc s, by apply uniq',
congr_arg cocone_morphism.hom this }
/-- Limit cones on `F` are unique up to isomorphism. -/
def unique {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : s ≅ t :=
{ hom := P.desc_cocone_morphism t,
inv := Q.desc_cocone_morphism s,
hom_inv_id' := P.uniq_cocone_morphism,
inv_hom_id' := Q.uniq_cocone_morphism }
def of_iso_colimit {r t : cocone F} (P : is_colimit r) (i : r ≅ t) : is_colimit t :=
is_colimit.mk_cocone_morphism
(λ s, i.inv ≫ P.desc_cocone_morphism s)
(λ s m, by rw i.eq_inv_comp; apply P.uniq_cocone_morphism)
variables {t : cocone F}
lemma hom_desc (h : is_colimit t) {W : C} (m : t.X ⟶ W) :
m = h.desc { X := W, ι := { app := λ b, t.ι.app b ≫ m,
naturality' := by intros; erw [←assoc, t.ι.naturality, comp_id, comp_id] } } :=
h.uniq { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := _ } } m (λ b, rfl)
/-- Two morphisms out of a colimit are equal if their compositions with
each cocone morphism are equal. -/
lemma hom_ext (h : is_colimit t) {W : C} {f f' : t.X ⟶ W}
(w : ∀ j, t.ι.app j ≫ f = t.ι.app j ≫ f') : f = f' :=
by rw [h.hom_desc f, h.hom_desc f']; congr; exact funext w
/-- The universal property of a colimit cocone: a map `X ⟶ W` is the same as
a cocone on `F` with vertex `W`. -/
def hom_iso (h : is_colimit t) (W : C) : (t.X ⟶ W) ≅ (F ⟶ (const J).obj W) :=
{ hom := λ f, (t.extend f).ι,
inv := λ ι, h.desc { X := W, ι := ι },
hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl }
@[simp] lemma hom_iso_hom (h : is_colimit t) {W : C} (f : t.X ⟶ W) :
(is_colimit.hom_iso h W).hom f = (t.extend f).ι := rfl
/-- The colimit of `F` represents the functor taking `W` to
the set of cocones on `F` with vertex `W`. -/
def nat_iso (h : is_colimit t) : coyoneda.obj (op t.X) ≅ F.cocones :=
nat_iso.of_components (is_colimit.hom_iso h) (by intros; ext; dsimp; rw ←assoc; refl)
def hom_iso' (h : is_colimit t) (W : C) :
((t.X ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j' : J} (f : j ⟶ j'), F.map f ≫ p j' = p j } :=
h.hom_iso W ≪≫
{ hom := λ ι,
⟨λ j, ι.app j, λ j j' f,
by convert ←(ι.naturality f); apply comp_id⟩,
inv := λ p,
{ app := λ j, p.1 j,
naturality' := λ j j' f, begin dsimp, rw [comp_id], exact (p.2 f) end } }
/-- If G : C → D is a faithful functor which sends t to a colimit cocone,
then it suffices to check that the induced maps for the image of t
can be lifted to maps of C. -/
def of_faithful {t : cocone F} {D : Type u'} [category.{v+1} D] (G : C ⥤ D) [faithful G]
(ht : is_colimit (G.map_cocone t)) (desc : Π (s : cocone F), t.X ⟶ s.X)
(h : ∀ s, G.map (desc s) = ht.desc (G.map_cocone s)) : is_colimit t :=
{ desc := desc,
fac' := λ s j, by apply G.injectivity; rw [G.map_comp, h]; apply ht.fac,
uniq' := λ s m w, begin
apply G.injectivity, rw h,
refine ht.uniq (G.map_cocone s) _ (λ j, _),
convert ←congr_arg (λ f, G.map f) (w j),
apply G.map_comp
end }
end is_colimit
def is_colimit_iso_unique_cocone_morphism {t : cocone F} :
is_colimit t ≅ Π s, unique (t ⟶ s) :=
{ hom := λ h s,
{ default := h.desc_cocone_morphism s,
uniq := λ _, h.uniq_cocone_morphism },
inv := λ h,
{ desc := λ s, (h s).default.hom,
uniq' := λ s f w, congr_arg cocone_morphism.hom ((h s).uniq ⟨f, w⟩) } }
section limit
/-- `has_limit F` represents a particular chosen limit of the diagram `F`. -/
class has_limit (F : J ⥤ C) :=
(cone : cone F)
(is_limit : is_limit cone . tactic.apply_instance)
variables (J C)
/-- `C` has limits of shape `J` if we have chosen a particular limit of
every functor `F : J ⥤ C`. -/
class has_limits_of_shape :=
(has_limit : Π F : J ⥤ C, has_limit F)
/-- `C` has all (small) limits if it has limits of every shape. -/
class has_limits :=
(has_limits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_limits_of_shape J C)
variables {J C}
instance has_limit_of_has_limits_of_shape
{J : Type v} [small_category J] [H : has_limits_of_shape J C] (F : J ⥤ C) : has_limit F :=
has_limits_of_shape.has_limit F
instance has_limits_of_shape_of_has_limits
{J : Type v} [small_category J] [H : has_limits.{v} C] : has_limits_of_shape J C :=
has_limits.has_limits_of_shape C J
/- Interface to the `has_limit` class. -/
def limit.cone (F : J ⥤ C) [has_limit F] : cone F := has_limit.cone F
def limit (F : J ⥤ C) [has_limit F] := (limit.cone F).X
def limit.π (F : J ⥤ C) [has_limit F] (j : J) : limit F ⟶ F.obj j :=
(limit.cone F).π.app j
@[simp] lemma limit.cone_π {F : J ⥤ C} [has_limit F] (j : J) :
(limit.cone F).π.app j = limit.π _ j := rfl
@[simp] lemma limit.w (F : J ⥤ C) [has_limit F] {j j' : J} (f : j ⟶ j') :
limit.π F j ≫ F.map f = limit.π F j' := (limit.cone F).w f
instance limit.is_limit (F : J ⥤ C) [has_limit F] : is_limit (limit.cone F) :=
has_limit.is_limit.{v} F
def limit.lift (F : J ⥤ C) [has_limit F] (c : cone F) : c.X ⟶ limit F :=
(limit.is_limit F).lift c
@[simp] lemma limit.is_limit_lift {F : J ⥤ C} [has_limit F] (c : cone F) :
(limit.is_limit F).lift c = limit.lift F c := rfl
@[simp] lemma limit.lift_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) :
limit.lift F c ≫ limit.π F j = c.π.app j :=
is_limit.fac _ c j
def limit.cone_morphism {F : J ⥤ C} [has_limit F] (c : cone F) :
cone_morphism c (limit.cone F) :=
(limit.is_limit F).lift_cone_morphism c
@[simp] lemma limit.cone_morphism_hom {F : J ⥤ C} [has_limit F] (c : cone F) :
(limit.cone_morphism c).hom = limit.lift F c := rfl
@[simp] lemma limit.cone_morphism_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) :
(limit.cone_morphism c).hom ≫ limit.π F j = c.π.app j :=
by erw is_limit.fac
@[extensionality] lemma limit.hom_ext {F : J ⥤ C} [has_limit F] {X : C} {f f' : X ⟶ limit F}
(w : ∀ j, f ≫ limit.π F j = f' ≫ limit.π F j) : f = f' :=
(limit.is_limit F).hom_ext w
def limit.hom_iso (F : J ⥤ C) [has_limit F] (W : C) : (W ⟶ limit F) ≅ (F.cones.obj (op W)) :=
(limit.is_limit F).hom_iso W
@[simp] lemma limit.hom_iso_hom (F : J ⥤ C) [has_limit F] {W : C} (f : W ⟶ limit F) :
(limit.hom_iso F W).hom f = (const J).map f ≫ (limit.cone F).π :=
(limit.is_limit F).hom_iso_hom f
def limit.hom_iso' (F : J ⥤ C) [has_limit F] (W : C) :
((W ⟶ limit F) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j' : J} (f : j ⟶ j'), p j ≫ F.map f = p j' } :=
(limit.is_limit F).hom_iso' W
lemma limit.lift_extend {F : J ⥤ C} [has_limit F] (c : cone F) {X : C} (f : X ⟶ c.X) :
limit.lift F (c.extend f) = f ≫ limit.lift F c :=
by obviously
def has_limit_of_iso {F G : J ⥤ C} [has_limit F] (α : F ≅ G) : has_limit G :=
{ cone := (cones.postcompose α.hom).obj (limit.cone F),
is_limit :=
{ lift := λ s, limit.lift F ((cones.postcompose α.inv).obj s),
fac' := λ s j,
begin
rw [cones.postcompose_obj_π, nat_trans.comp_app, limit.cone_π],
rw [category.assoc_symm, limit.lift_π], simp
end,
uniq' := λ s m w,
begin
apply limit.hom_ext, intro j,
rw [limit.lift_π, cones.postcompose_obj_π, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_comp_inv],
simpa using w j
end } }
section pre
variables (F) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)]
def limit.pre : limit F ⟶ limit (E ⋙ F) :=
limit.lift (E ⋙ F)
{ X := limit F,
π := { app := λ k, limit.π F (E.obj k) } }
@[simp] lemma limit.pre_π (k : K) : limit.pre F E ≫ limit.π (E ⋙ F) k = limit.π F (E.obj k) :=
by erw is_limit.fac
@[simp] lemma limit.lift_pre (c : cone F) :
limit.lift F c ≫ limit.pre F E = limit.lift (E ⋙ F) (c.whisker E) :=
by ext; simp
variables {L : Type v} [small_category L]
variables (D : L ⥤ K) [has_limit (D ⋙ E ⋙ F)]
@[simp] lemma limit.pre_pre : limit.pre F E ≫ limit.pre (E ⋙ F) D = limit.pre F (D ⋙ E) :=
by ext j; erw [assoc, limit.pre_π, limit.pre_π, limit.pre_π]; refl
end pre
section post
variables {D : Type u'} [𝒟 : category.{v+1} D]
include 𝒟
variables (F) [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)]
def limit.post : G.obj (limit F) ⟶ limit (F ⋙ G) :=
limit.lift (F ⋙ G)
{ X := G.obj (limit F),
π :=
{ app := λ j, G.map (limit.π F j),
naturality' :=
by intros j j' f; erw [←G.map_comp, limits.cone.w, id_comp]; refl } }
@[simp] lemma limit.post_π (j : J) : limit.post F G ≫ limit.π (F ⋙ G) j = G.map (limit.π F j) :=
by erw is_limit.fac
@[simp] lemma limit.lift_post (c : cone F) :
G.map (limit.lift F c) ≫ limit.post F G = limit.lift (F ⋙ G) (G.map_cone c) :=
by ext; rw [assoc, limit.post_π, ←G.map_comp, limit.lift_π, limit.lift_π]; refl
@[simp] lemma limit.post_post
{E : Type u''} [category.{v+1} E] (H : D ⥤ E) [has_limit ((F ⋙ G) ⋙ H)] :
/- H G (limit F) ⟶ H (limit (F ⋙ G)) ⟶ limit ((F ⋙ G) ⋙ H) equals -/
/- H G (limit F) ⟶ limit (F ⋙ (G ⋙ H)) -/
H.map (limit.post F G) ≫ limit.post (F ⋙ G) H = limit.post F (G ⋙ H) :=
by ext; erw [assoc, limit.post_π, ←H.map_comp, limit.post_π, limit.post_π]; refl
end post
lemma limit.pre_post {D : Type u'} [category.{v+1} D]
(E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D)
[has_limit F] [has_limit (E ⋙ F)] [has_limit (F ⋙ G)] [has_limit ((E ⋙ F) ⋙ G)] :
/- G (limit F) ⟶ G (limit (E ⋙ F)) ⟶ limit ((E ⋙ F) ⋙ G) vs -/
/- G (limit F) ⟶ limit F ⋙ G ⟶ limit (E ⋙ (F ⋙ G)) or -/
G.map (limit.pre F E) ≫ limit.post (E ⋙ F) G = limit.post F G ≫ limit.pre (F ⋙ G) E :=
by ext; erw [assoc, limit.post_π, ←G.map_comp, limit.pre_π, assoc, limit.pre_π, limit.post_π]; refl
open category_theory.equivalence
instance has_limit_equivalence_comp (e : K ≌ J) [has_limit F] : has_limit (e.functor ⋙ F) :=
{ cone := cone.whisker e.functor (limit.cone F),
is_limit :=
let e' := cones.postcompose (e.inv_fun_id_assoc F).hom in
{ lift := λ s, limit.lift F (e'.obj (cone.whisker e.inverse s)),
fac' := λ s j,
begin
dsimp, rw [limit.lift_π], dsimp [e'],
erw [inv_fun_id_assoc_hom_app, counit_functor, ←s.π.naturality, id_comp]
end,
uniq' := λ s m w,
begin
apply limit.hom_ext, intro j,
erw [limit.lift_π, ←limit.w F (e.counit_iso.hom.app j)],
slice_lhs 1 2 { erw [w (e.inverse.obj j)] }, simp
end } }
def has_limit_of_equivalence_comp (e : K ≌ J) [has_limit (e.functor ⋙ F)] : has_limit F :=
begin
haveI : has_limit (e.inverse ⋙ e.functor ⋙ F) := limits.has_limit_equivalence_comp e.symm,
apply has_limit_of_iso (e.inv_fun_id_assoc F),
end
-- `has_limit_comp_equivalence` and `has_limit_of_comp_equivalence`
-- are proved in `category_theory/adjunction/limits.lean`.
section lim_functor
variables [has_limits_of_shape J C]
/-- `limit F` is functorial in `F`, when `C` has all limits of shape `J`. -/
def lim : (J ⥤ C) ⥤ C :=
{ obj := λ F, limit F,
map := λ F G α, limit.lift G
{ X := limit F,
π :=
{ app := λ j, limit.π F j ≫ α.app j,
naturality' := λ j j' f,
by erw [id_comp, assoc, ←α.naturality, ←assoc, limit.w] } },
map_comp' := λ F G H α β,
by ext; erw [assoc, is_limit.fac, is_limit.fac, ←assoc, is_limit.fac, assoc]; refl }
variables {F} {G : J ⥤ C} (α : F ⟶ G)
@[simp] lemma lim.map_π (j : J) : lim.map α ≫ limit.π G j = limit.π F j ≫ α.app j :=
by apply is_limit.fac
@[simp] lemma limit.lift_map (c : cone F) :
limit.lift F c ≫ lim.map α = limit.lift G ((cones.postcompose α).obj c) :=
by ext; rw [assoc, lim.map_π, ←assoc, limit.lift_π, limit.lift_π]; refl
lemma limit.map_pre [has_limits_of_shape K C] (E : K ⥤ J) :
lim.map α ≫ limit.pre G E = limit.pre F E ≫ lim.map (whisker_left E α) :=
by ext; rw [assoc, limit.pre_π, lim.map_π, assoc, lim.map_π, ←assoc, limit.pre_π]; refl
lemma limit.map_pre' [has_limits_of_shape.{v} K C]
(F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) :
limit.pre F E₂ = limit.pre F E₁ ≫ lim.map (whisker_right α F) :=
by ext1; simp [(category.assoc _ _ _ _).symm]
lemma limit.id_pre (F : J ⥤ C) :
limit.pre F (functor.id _) = lim.map (functor.left_unitor F).inv := by tidy
lemma limit.map_post {D : Type u'} [category.{v+1} D] [has_limits_of_shape J D] (H : C ⥤ D) :
/- H (limit F) ⟶ H (limit G) ⟶ limit (G ⋙ H) vs
H (limit F) ⟶ limit (F ⋙ H) ⟶ limit (G ⋙ H) -/
H.map (lim.map α) ≫ limit.post G H = limit.post F H ≫ lim.map (whisker_right α H) :=
begin
ext,
rw [assoc, limit.post_π, ←H.map_comp, lim.map_π, H.map_comp],
rw [assoc, lim.map_π, ←assoc, limit.post_π],
refl
end
def lim_yoneda : lim ⋙ yoneda ≅ category_theory.cones J C :=
nat_iso.of_components (λ F, nat_iso.of_components (λ W, limit.hom_iso F (unop W)) (by tidy))
(by tidy)
end lim_functor
def has_limits_of_shape_of_equivalence {J' : Type v} [small_category J']
(e : J ≌ J') [has_limits_of_shape J C] : has_limits_of_shape J' C :=
by { constructor, intro F, apply has_limit_of_equivalence_comp e, apply_instance }
end limit
section colimit
/-- `has_colimit F` represents a particular chosen colimit of the diagram `F`. -/
class has_colimit (F : J ⥤ C) :=
(cocone : cocone F)
(is_colimit : is_colimit cocone . tactic.apply_instance)
variables (J C)
/-- `C` has colimits of shape `J` if we have chosen a particular colimit of
every functor `F : J ⥤ C`. -/
class has_colimits_of_shape :=
(has_colimit : Π F : J ⥤ C, has_colimit F)
/-- `C` has all (small) colimits if it has colimits of every shape. -/
class has_colimits :=
(has_colimits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_colimits_of_shape J C)
variables {J C}
instance has_colimit_of_has_colimits_of_shape
{J : Type v} [small_category J] [H : has_colimits_of_shape J C] (F : J ⥤ C) : has_colimit F :=
has_colimits_of_shape.has_colimit F
instance has_colimits_of_shape_of_has_colimits
{J : Type v} [small_category J] [H : has_colimits.{v} C] : has_colimits_of_shape J C :=
has_colimits.has_colimits_of_shape C J
/- Interface to the `has_colimit` class. -/
def colimit.cocone (F : J ⥤ C) [has_colimit F] : cocone F := has_colimit.cocone F
def colimit (F : J ⥤ C) [has_colimit F] := (colimit.cocone F).X
def colimit.ι (F : J ⥤ C) [has_colimit F] (j : J) : F.obj j ⟶ colimit F :=
(colimit.cocone F).ι.app j
@[simp] lemma colimit.cocone_ι {F : J ⥤ C} [has_colimit F] (j : J) :
(colimit.cocone F).ι.app j = colimit.ι _ j := rfl
@[simp] lemma colimit.w (F : J ⥤ C) [has_colimit F] {j j' : J} (f : j ⟶ j') :
F.map f ≫ colimit.ι F j' = colimit.ι F j := (colimit.cocone F).w f
instance colimit.is_colimit (F : J ⥤ C) [has_colimit F] : is_colimit (colimit.cocone F) :=
has_colimit.is_colimit.{v} F
def colimit.desc (F : J ⥤ C) [has_colimit F] (c : cocone F) : colimit F ⟶ c.X :=
(colimit.is_colimit F).desc c
@[simp] lemma colimit.is_colimit_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) :
(colimit.is_colimit F).desc c = colimit.desc F c := rfl
@[simp] lemma colimit.ι_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) :
colimit.ι F j ≫ colimit.desc F c = c.ι.app j :=
is_colimit.fac _ c j
/--
We have lots of lemmas describing how to simplify `colimit.ι F j ≫ _`,
and combined with `colimit.ext` we rely on these lemmas for many calculations.
However, since `category.assoc` is a `@[simp]` lemma, often expressions are
right associated, and it's hard to apply these lemmas about `colimit.ι`.
We thus define some additional `@[simp]` lemmas, with an arbitrary extra morphism.
-/
@[simp] lemma colimit.ι_desc_assoc {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) {Y : C} (f : c.X ⟶ Y) :
colimit.ι F j ≫ colimit.desc F c ≫ f = c.ι.app j ≫ f :=
by rw [←category.assoc, colimit.ι_desc]
def colimit.cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) :
cocone_morphism (colimit.cocone F) c :=
(colimit.is_colimit F).desc_cocone_morphism c
@[simp] lemma colimit.cocone_morphism_hom {F : J ⥤ C} [has_colimit F] (c : cocone F) :
(colimit.cocone_morphism c).hom = colimit.desc F c := rfl
@[simp] lemma colimit.ι_cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) :
colimit.ι F j ≫ (colimit.cocone_morphism c).hom = c.ι.app j :=
by erw is_colimit.fac
@[extensionality] lemma colimit.hom_ext {F : J ⥤ C} [has_colimit F] {X : C} {f f' : colimit F ⟶ X}
(w : ∀ j, colimit.ι F j ≫ f = colimit.ι F j ≫ f') : f = f' :=
(colimit.is_colimit F).hom_ext w
def colimit.hom_iso (F : J ⥤ C) [has_colimit F] (W : C) : (colimit F ⟶ W) ≅ (F.cocones.obj W) :=
(colimit.is_colimit F).hom_iso W
@[simp] lemma colimit.hom_iso_hom (F : J ⥤ C) [has_colimit F] {W : C} (f : colimit F ⟶ W) :
(colimit.hom_iso F W).hom f = (colimit.cocone F).ι ≫ (const J).map f :=
(colimit.is_colimit F).hom_iso_hom f
def colimit.hom_iso' (F : J ⥤ C) [has_colimit F] (W : C) :
((colimit F ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j'} (f : j ⟶ j'), F.map f ≫ p j' = p j } :=
(colimit.is_colimit F).hom_iso' W
lemma colimit.desc_extend (F : J ⥤ C) [has_colimit F] (c : cocone F) {X : C} (f : c.X ⟶ X) :
colimit.desc F (c.extend f) = colimit.desc F c ≫ f :=
begin
ext1, rw [←category.assoc], simp
end
def has_colimit_of_iso {F G : J ⥤ C} [has_colimit F] (α : G ≅ F) : has_colimit G :=
{ cocone := (cocones.precompose α.hom).obj (colimit.cocone F),
is_colimit :=
{ desc := λ s, colimit.desc F ((cocones.precompose α.inv).obj s),
fac' := λ s j,
begin
rw [cocones.precompose_obj_ι, nat_trans.comp_app, colimit.cocone_ι],
rw [category.assoc, colimit.ι_desc, ←nat_iso.app_hom, ←iso.eq_inv_comp], refl
end,
uniq' := λ s m w,
begin
apply colimit.hom_ext, intro j,
rw [colimit.ι_desc, cocones.precompose_obj_ι, nat_trans.comp_app, ←nat_iso.app_inv,
iso.eq_inv_comp],
simpa using w j
end } }
section pre
variables (F) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)]
def colimit.pre : colimit (E ⋙ F) ⟶ colimit F :=
colimit.desc (E ⋙ F)
{ X := colimit F,
ι := { app := λ k, colimit.ι F (E.obj k) } }
@[simp] lemma colimit.ι_pre (k : K) : colimit.ι (E ⋙ F) k ≫ colimit.pre F E = colimit.ι F (E.obj k) :=
by erw is_colimit.fac
@[simp] lemma colimit.ι_pre_assoc (k : K) {Z : C} (f : colimit F ⟶ Z) :
colimit.ι (E ⋙ F) k ≫ (colimit.pre F E) ≫ f = ((colimit.ι F (E.obj k)) : (E ⋙ F).obj k ⟶ colimit F) ≫ f :=
by rw [←category.assoc, colimit.ι_pre]
@[simp] lemma colimit.pre_desc (c : cocone F) :
colimit.pre F E ≫ colimit.desc F c = colimit.desc (E ⋙ F) (c.whisker E) :=
by ext; rw [←assoc, colimit.ι_pre]; simp
variables {L : Type v} [small_category L]
variables (D : L ⥤ K) [has_colimit (D ⋙ E ⋙ F)]
@[simp] lemma colimit.pre_pre : colimit.pre (E ⋙ F) D ≫ colimit.pre F E = colimit.pre F (D ⋙ E) :=
begin
ext j,
rw [←assoc, colimit.ι_pre, colimit.ι_pre],
letI : has_colimit ((D ⋙ E) ⋙ F) := show has_colimit (D ⋙ E ⋙ F), by apply_instance,
exact (colimit.ι_pre F (D ⋙ E) j).symm
end
end pre
section post
variables {D : Type u'} [𝒟 : category.{v+1} D]
include 𝒟
variables (F) [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)]
def colimit.post : colimit (F ⋙ G) ⟶ G.obj (colimit F) :=
colimit.desc (F ⋙ G)
{ X := G.obj (colimit F),
ι :=
{ app := λ j, G.map (colimit.ι F j),
naturality' :=
by intros j j' f; erw [←G.map_comp, limits.cocone.w, comp_id]; refl } }
@[simp] lemma colimit.ι_post (j : J) : colimit.ι (F ⋙ G) j ≫ colimit.post F G = G.map (colimit.ι F j) :=
by erw is_colimit.fac
@[simp] lemma colimit.ι_post_assoc (j : J) {Y : D} (f : G.obj (colimit F) ⟶ Y) :
colimit.ι (F ⋙ G) j ≫ colimit.post F G ≫ f = G.map (colimit.ι F j) ≫ f :=
by rw [←category.assoc, colimit.ι_post]
@[simp] lemma colimit.post_desc (c : cocone F) :
colimit.post F G ≫ G.map (colimit.desc F c) = colimit.desc (F ⋙ G) (G.map_cocone c) :=
by ext; rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_desc, colimit.ι_desc]; refl
@[simp] lemma colimit.post_post
{E : Type u''} [category.{v+1} E] (H : D ⥤ E) [has_colimit ((F ⋙ G) ⋙ H)] :
/- H G (colimit F) ⟶ H (colimit (F ⋙ G)) ⟶ colimit ((F ⋙ G) ⋙ H) equals -/
/- H G (colimit F) ⟶ colimit (F ⋙ (G ⋙ H)) -/
colimit.post (F ⋙ G) H ≫ H.map (colimit.post F G) = colimit.post F (G ⋙ H) :=
begin
ext,
rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_post],
exact (colimit.ι_post F (G ⋙ H) j).symm
end
end post
lemma colimit.pre_post {D : Type u'} [category.{v+1} D]
(E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D)
[has_colimit F] [has_colimit (E ⋙ F)] [has_colimit (F ⋙ G)] [has_colimit ((E ⋙ F) ⋙ G)] :
/- G (colimit F) ⟶ G (colimit (E ⋙ F)) ⟶ colimit ((E ⋙ F) ⋙ G) vs -/
/- G (colimit F) ⟶ colimit F ⋙ G ⟶ colimit (E ⋙ (F ⋙ G)) or -/
colimit.post (E ⋙ F) G ≫ G.map (colimit.pre F E) = colimit.pre (F ⋙ G) E ≫ colimit.post F G :=
begin
ext,
rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_pre, ←assoc],
letI : has_colimit (E ⋙ F ⋙ G) := show has_colimit ((E ⋙ F) ⋙ G), by apply_instance,
erw [colimit.ι_pre (F ⋙ G) E j, colimit.ι_post]
end
open category_theory.equivalence
instance has_colimit_equivalence_comp (e : K ≌ J) [has_colimit F] : has_colimit (e.functor ⋙ F) :=
{ cocone := cocone.whisker e.functor (colimit.cocone F),
is_colimit := let e' := cocones.precompose (e.inv_fun_id_assoc F).inv in
{ desc := λ s, colimit.desc F (e'.obj (cocone.whisker e.inverse s)),
fac' := λ s j,
begin
dsimp, rw [colimit.ι_desc], dsimp [e'],
erw [inv_fun_id_assoc_inv_app, ←functor_unit, s.ι.naturality, comp_id], refl
end,
uniq' := λ s m w,
begin
apply colimit.hom_ext, intro j,
erw [colimit.ι_desc],
have := w (e.inverse.obj j), simp at this, erw [←colimit.w F (e.counit_iso.hom.app j)] at this,
erw [assoc, ←iso.eq_inv_comp (F.map_iso $ e.counit_iso.app j)] at this, erw [this], simp
end } }
def has_colimit_of_equivalence_comp (e : K ≌ J) [has_colimit (e.functor ⋙ F)] : has_colimit F :=
begin
haveI : has_colimit (e.inverse ⋙ e.functor ⋙ F) := limits.has_colimit_equivalence_comp e.symm,
apply has_colimit_of_iso (e.inv_fun_id_assoc F).symm,
end
section colim_functor
variables [has_colimits_of_shape J C]
/-- `colimit F` is functorial in `F`, when `C` has all colimits of shape `J`. -/
def colim : (J ⥤ C) ⥤ C :=
{ obj := λ F, colimit F,
map := λ F G α, colimit.desc F
{ X := colimit G,
ι :=
{ app := λ j, α.app j ≫ colimit.ι G j,
naturality' := λ j j' f,
by erw [comp_id, ←assoc, α.naturality, assoc, colimit.w] } },
map_comp' := λ F G H α β,
by ext; erw [←assoc, is_colimit.fac, is_colimit.fac, assoc, is_colimit.fac, ←assoc]; refl }
variables {F} {G : J ⥤ C} (α : F ⟶ G)
@[simp] lemma colim.ι_map (j : J) : colimit.ι F j ≫ colim.map α = α.app j ≫ colimit.ι G j :=
by apply is_colimit.fac
@[simp] lemma colim.ι_map_assoc (j : J) {Y : C} (f : colimit G ⟶ Y) :
colimit.ι F j ≫ colim.map α ≫ f = α.app j ≫ colimit.ι G j ≫ f :=
by rw [←category.assoc, colim.ι_map, category.assoc]
@[simp] lemma colimit.map_desc (c : cocone G) :
colim.map α ≫ colimit.desc G c = colimit.desc F ((cocones.precompose α).obj c) :=
by ext; rw [←assoc, colim.ι_map, assoc, colimit.ι_desc, colimit.ι_desc]; refl
lemma colimit.pre_map [has_colimits_of_shape K C] (E : K ⥤ J) :
colimit.pre F E ≫ colim.map α = colim.map (whisker_left E α) ≫ colimit.pre G E :=
by ext; rw [←assoc, colimit.ι_pre, colim.ι_map, ←assoc, colim.ι_map, assoc, colimit.ι_pre]; refl
lemma colimit.pre_map' [has_colimits_of_shape.{v} K C]
(F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) :
colimit.pre F E₁ = colim.map (whisker_right α F) ≫ colimit.pre F E₂ :=
by ext1; simp [(category.assoc _ _ _ _).symm]
lemma colimit.pre_id (F : J ⥤ C) :
colimit.pre F (functor.id _) = colim.map (functor.left_unitor F).hom := by tidy
lemma colimit.map_post {D : Type u'} [category.{v+1} D] [has_colimits_of_shape J D] (H : C ⥤ D) :
/- H (colimit F) ⟶ H (colimit G) ⟶ colimit (G ⋙ H) vs
H (colimit F) ⟶ colimit (F ⋙ H) ⟶ colimit (G ⋙ H) -/
colimit.post F H ≫ H.map (colim.map α) = colim.map (whisker_right α H) ≫ colimit.post G H:=
begin
ext,
rw [←assoc, colimit.ι_post, ←H.map_comp, colim.ι_map, H.map_comp],
rw [←assoc, colim.ι_map, assoc, colimit.ι_post],
refl
end
def colim_coyoneda : colim.op ⋙ coyoneda ≅ category_theory.cocones J C :=
nat_iso.of_components (λ F, nat_iso.of_components (colimit.hom_iso (unop F)) (by tidy))
(by tidy)
end colim_functor
def has_colimits_of_shape_of_equivalence {J' : Type v} [small_category J']
(e : J ≌ J') [has_colimits_of_shape J C] : has_colimits_of_shape J' C :=
by { constructor, intro F, apply has_colimit_of_equivalence_comp e, apply_instance }
end colimit
end category_theory.limits
|
de683555eaff70c2d14f1ed25131fd83e8f67b7e
|
4727251e0cd73359b15b664c3170e5d754078599
|
/src/linear_algebra/affine_space/midpoint.lean
|
8072c8c35a2fa3367bf38b4eafe90faca5c101ff
|
[
"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
| 8,339
|
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 algebra.char_p.invertible
import linear_algebra.affine_space.affine_equiv
/-!
# Midpoint of a segment
## Main definitions
* `midpoint R x y`: midpoint of the segment `[x, y]`. We define it for `x` and `y`
in a module over a ring `R` with invertible `2`.
* `add_monoid_hom.of_map_midpoint`: construct an `add_monoid_hom` given a map `f` such that
`f` sends zero to zero and midpoints to midpoints.
## Main theorems
* `midpoint_eq_iff`: `z` is the midpoint of `[x, y]` if and only if `x + y = z + z`,
* `midpoint_unique`: `midpoint R x y` does not depend on `R`;
* `midpoint x y` is linear both in `x` and `y`;
* `point_reflection_midpoint_left`, `point_reflection_midpoint_right`:
`equiv.point_reflection (midpoint R x y)` swaps `x` and `y`.
We do not mark most lemmas as `@[simp]` because it is hard to tell which side is simpler.
## Tags
midpoint, add_monoid_hom
-/
open affine_map affine_equiv
section
variables (R : Type*) {V V' P P' : Type*} [ring R] [invertible (2:R)]
[add_comm_group V] [module R V] [add_torsor V P]
[add_comm_group V'] [module R V'] [add_torsor V' P']
include V
/-- `midpoint x y` is the midpoint of the segment `[x, y]`. -/
def midpoint (x y : P) : P := line_map x y (⅟2:R)
variables {R} {x y z : P}
include V'
@[simp] lemma affine_map.map_midpoint (f : P →ᵃ[R] P') (a b : P) :
f (midpoint R a b) = midpoint R (f a) (f b) :=
f.apply_line_map a b _
@[simp] lemma affine_equiv.map_midpoint (f : P ≃ᵃ[R] P') (a b : P) :
f (midpoint R a b) = midpoint R (f a) (f b) :=
f.apply_line_map a b _
omit V'
@[simp] lemma affine_equiv.point_reflection_midpoint_left (x y : P) :
point_reflection R (midpoint R x y) x = y :=
by rw [midpoint, point_reflection_apply, line_map_apply, vadd_vsub,
vadd_vadd, ← add_smul, ← two_mul, mul_inv_of_self, one_smul, vsub_vadd]
lemma midpoint_comm (x y : P) : midpoint R x y = midpoint R y x :=
by rw [midpoint, ← line_map_apply_one_sub, one_sub_inv_of_two, midpoint]
@[simp] lemma affine_equiv.point_reflection_midpoint_right (x y : P) :
point_reflection R (midpoint R x y) y = x :=
by rw [midpoint_comm, affine_equiv.point_reflection_midpoint_left]
lemma midpoint_vsub_midpoint (p₁ p₂ p₃ p₄ : P) :
midpoint R p₁ p₂ -ᵥ midpoint R p₃ p₄ = midpoint R (p₁ -ᵥ p₃) (p₂ -ᵥ p₄) :=
line_map_vsub_line_map _ _ _ _ _
lemma midpoint_vadd_midpoint (v v' : V) (p p' : P) :
midpoint R v v' +ᵥ midpoint R p p' = midpoint R (v +ᵥ p) (v' +ᵥ p') :=
line_map_vadd_line_map _ _ _ _ _
lemma midpoint_eq_iff {x y z : P} : midpoint R x y = z ↔ point_reflection R z x = y :=
eq_comm.trans ((injective_point_reflection_left_of_module R x).eq_iff'
(affine_equiv.point_reflection_midpoint_left x y)).symm
@[simp] lemma midpoint_vsub_left (p₁ p₂ : P) : midpoint R p₁ p₂ -ᵥ p₁ = (⅟2:R) • (p₂ -ᵥ p₁) :=
line_map_vsub_left _ _ _
@[simp] lemma midpoint_vsub_right (p₁ p₂ : P) : midpoint R p₁ p₂ -ᵥ p₂ = (⅟2:R) • (p₁ -ᵥ p₂) :=
by rw [midpoint_comm, midpoint_vsub_left]
@[simp] lemma left_vsub_midpoint (p₁ p₂ : P) : p₁ -ᵥ midpoint R p₁ p₂ = (⅟2:R) • (p₁ -ᵥ p₂) :=
left_vsub_line_map _ _ _
@[simp] lemma right_vsub_midpoint (p₁ p₂ : P) : p₂ -ᵥ midpoint R p₁ p₂ = (⅟2:R) • (p₂ -ᵥ p₁) :=
by rw [midpoint_comm, left_vsub_midpoint]
@[simp] lemma midpoint_sub_left (v₁ v₂ : V) : midpoint R v₁ v₂ - v₁ = (⅟2:R) • (v₂ - v₁) :=
midpoint_vsub_left v₁ v₂
@[simp] lemma midpoint_sub_right (v₁ v₂ : V) : midpoint R v₁ v₂ - v₂ = (⅟2:R) • (v₁ - v₂) :=
midpoint_vsub_right v₁ v₂
@[simp] lemma left_sub_midpoint (v₁ v₂ : V) : v₁ - midpoint R v₁ v₂ = (⅟2:R) • (v₁ - v₂) :=
left_vsub_midpoint v₁ v₂
@[simp] lemma right_sub_midpoint (v₁ v₂ : V) : v₂ - midpoint R v₁ v₂ = (⅟2:R) • (v₂ - v₁) :=
right_vsub_midpoint v₁ v₂
variable (R)
lemma midpoint_eq_midpoint_iff_vsub_eq_vsub {x x' y y' : P} :
midpoint R x y = midpoint R x' y' ↔ x -ᵥ x' = y' -ᵥ y :=
by rw [← @vsub_eq_zero_iff_eq V, midpoint_vsub_midpoint, midpoint_eq_iff, point_reflection_apply,
vsub_eq_sub, zero_sub, vadd_eq_add, add_zero, neg_eq_iff_neg_eq, neg_vsub_eq_vsub_rev, eq_comm]
lemma midpoint_eq_iff' {x y z : P} : midpoint R x y = z ↔ equiv.point_reflection z x = y :=
midpoint_eq_iff
/-- `midpoint` does not depend on the ring `R`. -/
lemma midpoint_unique (R' : Type*) [ring R'] [invertible (2:R')] [module R' V] (x y : P) :
midpoint R x y = midpoint R' x y :=
(midpoint_eq_iff' R).2 $ (midpoint_eq_iff' R').1 rfl
@[simp] lemma midpoint_self (x : P) : midpoint R x x = x :=
line_map_same_apply _ _
@[simp] lemma midpoint_add_self (x y : V) : midpoint R x y + midpoint R x y = x + y :=
calc midpoint R x y +ᵥ midpoint R x y = midpoint R x y +ᵥ midpoint R y x : by rw midpoint_comm
... = x + y : by rw [midpoint_vadd_midpoint, vadd_eq_add, vadd_eq_add, add_comm, midpoint_self]
lemma midpoint_zero_add (x y : V) : midpoint R 0 (x + y) = midpoint R x y :=
(midpoint_eq_midpoint_iff_vsub_eq_vsub R).2 $ by simp [sub_add_eq_sub_sub_swap]
lemma midpoint_eq_smul_add (x y : V) : midpoint R x y = (⅟2 : R) • (x + y) :=
by rw [midpoint_eq_iff, point_reflection_apply, vsub_eq_sub, vadd_eq_add, sub_add_eq_add_sub,
← two_smul R, smul_smul, mul_inv_of_self, one_smul, add_sub_cancel']
@[simp] lemma midpoint_self_neg (x : V) :
midpoint R x (-x) = 0 :=
by rw [midpoint_eq_smul_add, add_neg_self, smul_zero]
@[simp] lemma midpoint_neg_self (x : V) :
midpoint R (-x) x = 0 :=
by simpa using midpoint_self_neg R (-x)
@[simp] lemma midpoint_sub_add (x y : V) :
midpoint R (x - y) (x + y) = x :=
by rw [sub_eq_add_neg, ← vadd_eq_add, ← vadd_eq_add, ← midpoint_vadd_midpoint]; simp
@[simp] lemma midpoint_add_sub (x y : V) :
midpoint R (x + y) (x - y) = x :=
by rw midpoint_comm; simp
end
lemma line_map_inv_two {R : Type*} {V P : Type*} [division_ring R] [char_zero R]
[add_comm_group V] [module R V] [add_torsor V P] (a b : P) :
line_map a b (2⁻¹:R) = midpoint R a b :=
rfl
lemma line_map_one_half {R : Type*} {V P : Type*} [division_ring R] [char_zero R]
[add_comm_group V] [module R V] [add_torsor V P] (a b : P) :
line_map a b (1/2:R) = midpoint R a b :=
by rw [one_div, line_map_inv_two]
lemma homothety_inv_of_two {R : Type*} {V P : Type*} [comm_ring R] [invertible (2:R)]
[add_comm_group V] [module R V] [add_torsor V P] (a b : P) :
homothety a (⅟2:R) b = midpoint R a b :=
rfl
lemma homothety_inv_two {k : Type*} {V P : Type*} [field k] [char_zero k]
[add_comm_group V] [module k V] [add_torsor V P] (a b : P) :
homothety a (2⁻¹:k) b = midpoint k a b :=
rfl
lemma homothety_one_half {k : Type*} {V P : Type*} [field k] [char_zero k]
[add_comm_group V] [module k V] [add_torsor V P] (a b : P) :
homothety a (1/2:k) b = midpoint k a b :=
by rw [one_div, homothety_inv_two]
@[simp] lemma pi_midpoint_apply {k ι : Type*} {V : Π i : ι, Type*} {P : Π i : ι, Type*} [field k]
[invertible (2:k)] [Π i, add_comm_group (V i)] [Π i, module k (V i)]
[Π i, add_torsor (V i) (P i)] (f g : Π i, P i) (i : ι) :
midpoint k f g i = midpoint k (f i) (g i) := rfl
namespace add_monoid_hom
variables (R R' : Type*) {E F : Type*}
[ring R] [invertible (2:R)] [add_comm_group E] [module R E]
[ring R'] [invertible (2:R')] [add_comm_group F] [module R' F]
/-- A map `f : E → F` sending zero to zero and midpoints to midpoints is an `add_monoid_hom`. -/
def of_map_midpoint (f : E → F) (h0 : f 0 = 0)
(hm : ∀ x y, f (midpoint R x y) = midpoint R' (f x) (f y)) :
E →+ F :=
{ to_fun := f,
map_zero' := h0,
map_add' := λ x y,
calc f (x + y) = f 0 + f (x + y) : by rw [h0, zero_add]
... = midpoint R' (f 0) (f (x + y)) + midpoint R' (f 0) (f (x + y)) :
(midpoint_add_self _ _ _).symm
... = f (midpoint R x y) + f (midpoint R x y) : by rw [← hm, midpoint_zero_add]
... = f x + f y : by rw [hm, midpoint_add_self] }
@[simp] lemma coe_of_map_midpoint (f : E → F) (h0 : f 0 = 0)
(hm : ∀ x y, f (midpoint R x y) = midpoint R' (f x) (f y)) :
⇑(of_map_midpoint R R' f h0 hm) = f := rfl
end add_monoid_hom
|
19dde77ca056c0a2f66922e6f5f07364a65de33b
|
510e96af568b060ed5858226ad954c258549f143
|
/data/list/sort.lean
|
0c654be1c80e57e1fd0f6f48f9d1afa43912453b
|
[] |
no_license
|
Shamrock-Frost/library_dev
|
cb6d1739237d81e17720118f72ba0a6db8a5906b
|
0245c71e4931d3aceeacf0aea776454f6ee03c9c
|
refs/heads/master
| 1,609,481,034,595
| 1,500,165,215,000
| 1,500,165,347,000
| 97,350,162
| 0
| 0
| null | 1,500,164,969,000
| 1,500,164,969,000
| null |
UTF-8
|
Lean
| false
| false
| 15,953
|
lean
|
/-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
Insertion sort and merge sort.
-/
import .perm
-- TODO(Jeremy): move this
namespace nat
theorem add_pos_left {m : ℕ} (h : m > 0) (n : ℕ) : m + n > 0 :=
calc
m + n > 0 + n : nat.add_lt_add_right h n
... = n : nat.zero_add n
... ≥ 0 : zero_le n
theorem add_pos_right (m : ℕ) {n : ℕ} (h : n > 0) : m + n > 0 :=
begin rw add_comm, exact add_pos_left h m end
theorem add_pos_iff_pos_or_pos (m n : ℕ) : m + n > 0 ↔ m > 0 ∨ n > 0 :=
iff.intro
begin
intro h,
cases m with m,
{simp [zero_add] at h, exact or.inr h},
exact or.inl (succ_pos _)
end
begin
intro h, cases h with mpos npos,
{ apply add_pos_left mpos },
apply add_pos_right _ npos
end
lemma succ_le_succ_iff (m n : ℕ) : succ m ≤ succ n ↔ m ≤ n :=
⟨le_of_succ_le_succ, succ_le_succ⟩
lemma lt_succ_iff_le (m n : ℕ) : m < succ n ↔ m ≤ n :=
succ_le_succ_iff m n
end nat
namespace list
section sorted
universe variable uu
variables {α : Type uu} (r : α → α → Prop)
def sorted : list α → Prop
| [] := true
| (a :: l) := sorted l ∧ ∀ b ∈ l, r a b
theorem sorted_nil : sorted r nil := trivial
theorem sorted_singleton (a : α) : sorted r [a] :=
⟨sorted_nil r, λ b h, absurd h (not_mem_nil b)⟩
theorem sorted_of_sorted_cons {a : α} {l : list α} (h : sorted r (a :: l)) : sorted r l :=
h^.left
theorem forall_mem_rel_of_sorted_cons {a : α} {l : list α} (h : sorted r (a :: l)) :
∀ b ∈ l, r a b :=
h^.right
theorem sorted_cons {a : α} {l : list α} (h₁ : sorted r l) (h₂ : ∀ b ∈ l, r a b) :
sorted r (a :: l) :=
⟨h₁, h₂⟩
end sorted
/-
sorting procedures
-/
section sort
universe variable uu
parameters {α : Type uu} (r : α → α → Prop) [decidable_rel r]
local infix `≼` : 50 := r
/- insertion sort -/
section insertion_sort
def ordered_insert (a : α) : list α → list α
| [] := [a]
| (b :: l) := if a ≼ b then a :: (b :: l) else b :: ordered_insert l
--@[simp]
--theorem ordered_insert_nil (a : α) : ordered_insert a [] = [a] := rfl
--@[simp]
--theorem ordered_insert_cons (a b : α) (l : list α) :
-- ordered_insert a (b :: l) = if a ≼ b then a :: (b :: l) else b :: ordered_insert a l :=
--rfl
def insertion_sort : list α → list α
| [] := []
| (b :: l) := ordered_insert b (insertion_sort l)
--attribute [simp] insertion_sort.equations.eqn_1 insertion_sort.equations.eqn_2
section correctness
parameter [deceqα : decidable_eq α]
include deceqα
open perm
-- TODO(Jeremy): anonymous type class parameters don't work well
theorem count_ordered_insert_eq (b a : α) : ∀ l, count b (ordered_insert a l) = count b (a :: l)
| [] := by simp [ordered_insert]
| (c :: l) := if h : a ≼ c then begin unfold ordered_insert, simp [if_pos, h] end
else by simp [ordered_insert, if_neg, h, count_cons', count_ordered_insert_eq]
theorem mem_ordered_insert_iff (b a : α) (l : list α) : b ∈ ordered_insert a l ↔ b ∈ a :: l :=
begin repeat {rw mem_iff_count_pos}, simp [count_ordered_insert_eq] end
theorem perm_insertion_sort : ∀ l : list α, insertion_sort l ~ l
| [] := perm.nil
| (b :: l) := perm_of_forall_count_eq (assume a,
by simp [insertion_sort, count_ordered_insert_eq, count_cons',
count_eq_count_of_perm (perm_insertion_sort l) a])
section total_and_transitive
variables (totr : total r) (transr : transitive r)
include totr transr
theorem sorted_ordered_insert (a : α) : ∀ l, sorted r l → sorted r (ordered_insert a l)
| [] := assume h, sorted_singleton r a
| (b :: l) :=
assume h,
have sorted r l, from sorted_of_sorted_cons r h,
have h₀ : ∀ c ∈ l, b ≼ c, from forall_mem_rel_of_sorted_cons r h,
if h' : a ≼ b then
begin
simp [ordered_insert, if_pos, h'],
exact have ∀ c ∈ b :: l, a ≼ c, from
assume c, suppose c ∈ b :: l,
or.elim (eq_or_mem_of_mem_cons this)
(suppose c = b, this^.symm ▸ ‹a ≼ b›)
(suppose c ∈ l, transr ‹a ≼ b› (h₀ _ this)),
show sorted r (a :: b :: l), from sorted_cons r h this
end
else
have b ≼ a, from or.resolve_left (totr a b) h',
begin
simp [ordered_insert, if_neg, ‹¬ a ≼ b›],
exact have h₁ : sorted r (ordered_insert r a l), from sorted_ordered_insert l ‹sorted r l›,
have h₂ : ∀ c ∈ ordered_insert r a l, b ≼ c, from
assume c,
suppose c ∈ ordered_insert r a l,
have c ∈ a :: l, from (mem_ordered_insert_iff r c a l)^.mp this,
or.elim (eq_or_mem_of_mem_cons this)
(suppose c = a, begin rw this, exact ‹b ≼ a› end)
(suppose c ∈ l, h₀ c this),
show sorted r (b :: ordered_insert r a l), from sorted_cons r h₁ h₂
end
theorem sorted_insert_sort : ∀ l, sorted r (insertion_sort l)
| [] := sorted_nil r
| (a :: l) := sorted_ordered_insert totr transr a _ (sorted_insert_sort l)
end total_and_transitive
end correctness
end insertion_sort
/- merge sort -/
section merge_sort
-- TODO(Jeremy): observation: if instead we write (a :: (split l).1, b :: (split l).2), the
-- equation compiler can't prove the third equation
def split : list α → list α × list α
| [] := ([], [])
| [a] := ([a], [])
| (a :: b :: l) := match split l with
| (l₁, l₂) := (a :: l₁, b :: l₂)
end
-- TODO(Jeremy): the cases is needed because the internal split_match gets a pair
private theorem split_cons_cons_aux (a b : α) (l : list α) :
split (a :: b :: l) = match split l with
| (l₁, l₂) := (a :: l₁, b :: l₂)
end := rfl
@[simp]
theorem split_cons_cons (a b : α) (l : list α) :
split (a :: b :: l) = (a :: (split l).1, b :: (split l).2) :=
begin rw [split_cons_cons_aux], cases split l, reflexivity end
theorem length_split_fst_le : ∀ l : list α, length ((split l).1) ≤ length l
| [] := nat.le_refl 0
| [a] := nat.le_refl 1
| (a :: b :: l) := begin
simp [split_cons_cons, -add_comm],
exact nat.succ_le_succ (nat.le_succ_of_le (length_split_fst_le l))
end
theorem length_split_snd_le : ∀ l : list α, length ((split l).2) ≤ length l
| [] := nat.le_refl 0
| [a] := nat.zero_le 1
| (a :: b :: l) := begin
simp [-add_comm],
transitivity,
{ apply add_le_add_right (length_split_snd_le l) },
simp [nat.one_add, nat.le_succ]
end
theorem length_split_cons_cons_fst_lt (a b : α) (l : list α) :
length (split (a :: b :: l)).1 < length (a :: b :: l) :=
begin
simp [-add_comm],
exact add_lt_add_of_le_of_lt (length_split_fst_le l) (nat.le_refl _)
end
theorem length_split_cons_cons_snd_lt (a b : α) (l : list α) :
length (split (a :: b :: l)).2 < length (a :: b :: l) :=
begin
simp [-add_comm],
exact add_lt_add_of_le_of_lt (length_split_snd_le l) (nat.le_refl _)
end
-- Do the well-founded recursion by hand, until the function definition system supports it.
private def merge.F :
Π p : list α × list α,
(Π p₁ : list α × list α, length p₁.1 + length p₁.2 < length p.1 + length p.2 → list α) →
list α
| ([], l) f := l
| (a :: l, []) f := a :: l
| (a :: l, b :: l') f := if a ≼ b then
a :: f (l, b :: l') begin simp [-add_comm], apply nat.le_refl end
else
b :: f (a :: l, l') begin apply nat.le_refl end
def merge := well_founded.fix (inv_image.wf _ nat.lt_wf) merge.F
theorem merge.def (p : list α × list α) : merge p = merge.F p (λ p h, merge p) :=
well_founded.fix_eq (inv_image.wf _ nat.lt_wf) merge.F p
@[simp]
theorem merge.equations.eq_1 (l : list α) : merge ([], l) = l :=
begin rw merge.def, reflexivity end
@[simp]
theorem merge.equations.eq_2 (a : α) (l : list α) : merge (a :: l, []) = a :: l :=
begin rw merge.def, reflexivity end
@[simp]
theorem merge.equations.eq_3 (a b : α) (l l' : list α) :
merge (a :: l, b :: l') = if a ≼ b then
a :: merge (l, b :: l')
else
b :: merge (a :: l, l') :=
begin rw merge.def, reflexivity end
private def merge_sort.F :
Π l : list α, (Π l₁ : list α, length l₁ < length l → list α) → list α
| [] f := []
| [a] f := [a]
| (a :: b :: l) f := let p := split (a :: b :: l),
l₁ := f p.1 (length_split_cons_cons_fst_lt a b l),
l₂ := f p.2 (length_split_cons_cons_snd_lt a b l) in
merge (l₁, l₂)
def merge_sort := well_founded.fix (inv_image.wf _ nat.lt_wf) merge_sort.F
theorem merge_sort.def (l : list α) : merge_sort l = merge_sort.F l (λ l h, merge_sort l) :=
well_founded.fix_eq (inv_image.wf _ nat.lt_wf) merge_sort.F l
@[simp]
theorem merge_sort.equations.eq_1 : merge_sort [] = [] :=
begin rw merge_sort.def, reflexivity end
@[simp]
theorem merge_sort.equations.eq_2 (a : α) : merge_sort [a] = [a] :=
begin rw merge_sort.def, reflexivity end
@[simp]
theorem merge_sort.equations.eq_3 (a b : α) (l : list α) :
merge_sort (a :: b :: l) = let p := split (a :: b :: l) in
merge (merge_sort p.1, merge_sort p.2) :=
begin rw merge_sort.def, reflexivity end
section correctness
parameter [deceqα : decidable_eq α]
include deceqα
theorem count_split (a : α) : ∀ l : list α, count a (split l).1 + count a (split l).2 = count a l
| [] := rfl
| [a] := rfl
| (a :: b :: l) := begin simp [count_cons'], rw [←count_split l], simp end
private def count_merge.F (c : α) :
Π p : list α × list α,
(Π p₁ : list α × list α, length p₁.1 + length p₁.2 < length p.1 + length p.2 →
count c (merge p₁) = count c p₁.1 + count c p₁.2) →
count c (merge p) = count c p.1 + count c p.2
| ([], l) f := by simp
| (a :: l, []) f := by simp
| (a :: l, b :: l') f := if h : a ≼ b then
begin
have hrec := f (l, b :: l') begin simp [-add_comm], apply nat.le_refl end,
simp [if_pos, h, count_cons', hrec]
end
else
begin
have hrec := f (a :: l, l') begin apply nat.le_refl end,
simp [if_neg, h, count_cons', hrec]
end
theorem count_merge (c : α) :
∀ p : list α × list α, count c (merge p) = count c p.1 + count c p.2 :=
well_founded.fix (inv_image.wf _ nat.lt_wf) (count_merge.F c)
theorem mem_merge_iff (a : α) (p : list α × list α) : a ∈ merge p ↔ a ∈ p.1 ∨ a ∈ p.2 :=
begin repeat { rw mem_iff_count_pos }, simp [count_merge, nat.add_pos_iff_pos_or_pos] end
private def perm_merge_sort.F :
Π l : list α, (Π l₁ : list α, length l₁ < length l → merge_sort l₁ ~ l₁) →
merge_sort l ~ l
| [] f := by simp; exact perm.refl _
| [a] f := by simp; exact perm.refl _
| (a :: b :: l) f :=
perm.perm_of_forall_count_eq
begin
intro c,
let hrec₁ := perm.count_eq_count_of_perm (f _ (length_split_cons_cons_fst_lt a b l)) c,
let hrec₂ := perm.count_eq_count_of_perm (f _ (length_split_cons_cons_snd_lt a b l)) c,
simp at hrec₁,
simp at hrec₂,
simp [hrec₁, hrec₂, count_merge, count_split, count_cons']
end
theorem perm_merge_sort : ∀ l : list α, merge_sort l ~ l :=
well_founded.fix (inv_image.wf _ nat.lt_wf) perm_merge_sort.F
section total_and_transitive
variables (totr : total r) (transr : transitive r)
include totr transr
private def sorted_merge.F :
Π p : list α × list α,
(Π p₁ : list α × list α, length p₁.1 + length p₁.2 < length p.1 + length p.2 →
(sorted r p₁.1 → sorted r p₁.2 → sorted r (merge p₁))) →
sorted r p.1 → sorted r p.2 → sorted r (merge p)
| ([], l) f h₁ h₂ := begin simp, exact h₂ end
| (a :: l, []) f h₁ h₂ := begin simp, exact h₁ end
| (a :: l, b :: l') f h₁ h₂ :=
have sorted r l, from sorted_of_sorted_cons r h₁,
have sorted r l', from sorted_of_sorted_cons r h₂,
have h₁₀ : ∀ c ∈ l, a ≼ c, from forall_mem_rel_of_sorted_cons r h₁,
have h₂₀ : ∀ c ∈ l', b ≼ c, from forall_mem_rel_of_sorted_cons r h₂,
if h : a ≼ b then
begin
have hrec := f (l, b :: l') begin simp [-add_comm], apply nat.le_refl end,
simp [if_pos, h],
exact have h₃ : sorted r (merge r (l, b :: l')), from hrec ‹sorted r l› h₂,
have h₄ : ∀ c ∈ merge r (l, b :: l'), a ≼ c,
begin
intros c hc,
rw mem_merge_iff at hc,
exact or.elim hc
(suppose c ∈ l, show a ≼ c, from h₁₀ c this)
(suppose c ∈ b :: l',
or.elim (eq_or_mem_of_mem_cons this)
(suppose c = b, show a ≼ c, from this^.symm ▸ ‹a ≼ b›)
(suppose c ∈ l', show a ≼ c, from transr ‹a ≼ b› (h₂₀ c this)))
end,
show sorted r (a :: merge r (l, b :: l')), from sorted_cons r h₃ h₄
end
else
have h' : b ≼ a, from or.resolve_left (totr a b) h,
begin
have hrec := f (a :: l, l') begin apply nat.le_refl end,
simp [if_neg, h],
exact have h₃ : sorted r (merge r (a :: l, l')), from hrec h₁ ‹sorted r l'›,
have h₄ : ∀ c ∈ merge r (a :: l, l'), b ≼ c,
begin
intros c hc,
rw mem_merge_iff at hc,
exact or.elim hc
(suppose c ∈ a :: l,
or.elim (eq_or_mem_of_mem_cons this)
(suppose c = a, show b ≼ c, from this^.symm ▸ ‹b ≼ a›)
(suppose c ∈ l, show b ≼ c, from transr ‹b ≼ a› (h₁₀ c this)))
(suppose c ∈ l', show b ≼ c, from h₂₀ c this)
end,
show sorted r (b :: merge r (a :: l, l')), from sorted_cons r h₃ h₄
end
theorem sorted_merge : Π {p : list α × list α},
sorted r p.1 → sorted r p.2 → sorted r (merge p) :=
well_founded.fix (inv_image.wf _ nat.lt_wf) (sorted_merge.F totr transr)
/- elaboration of sorted_merge_sort.F takes forever
private def sorted_merge_sort.F :
Π l : list α, (Π l₁ : list α, length l₁ < length l → sorted r (merge_sort l₁)) →
sorted r (merge_sort l)
| [] f := by simp; exact sorted_nil r
| [a] f := by simp; exact sorted_singleton r a
| (a :: b :: l) f :=
begin
simp,
apply sorted_merge r totr transr,
-- this should be handled by the simplifier, i.e. cancel out +1 and rewrite _ < _ + 1 to _ <= _
{ dsimp,
apply f,
show length (split l)^.fst + (1 + 0) < length l + (1 + 1),
exact add_lt_add_of_le_of_lt (length_split_fst_le l) (add_lt_add_of_le_of_lt (le_refl 1) zero_lt_one) },
{ dsimp,
apply f,
show length (split l)^.snd + (1 + 0) < length l + (1 + 1),
exact add_lt_add_of_le_of_lt (length_split_snd_le l) (add_lt_add_of_le_of_lt (le_refl 1) zero_lt_one) }
end
theorem sorted_merge_sort : ∀ l : list α, sorted r (merge_sort l) :=
well_founded.fix (inv_image.wf _ nat.lt_wf) (sorted_merge_sort.F totr transr)
-/
end total_and_transitive
end correctness
end merge_sort
end sort
/- try them out! -/
--vm_eval insertion_sort (λ m n : ℕ, m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12]
--vm_eval merge_sort (λ m n : ℕ, m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12]
end list
|
8f240a299ecd45d48126e0f805307208150d5f40
|
4727251e0cd73359b15b664c3170e5d754078599
|
/src/data/set/lattice.lean
|
c9943dcd78cb7c83916d420171ee9432cf90d2a0
|
[
"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
| 65,709
|
lean
|
/-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Johannes Hölzl, Mario Carneiro
-/
import data.nat.basic
import order.complete_boolean_algebra
import order.directed
import order.galois_connection
/-!
# The set lattice
This file provides usual set notation for unions and intersections, a `complete_lattice` instance
for `set α`, and some more set constructions.
## Main declarations
* `set.Union`: Union of an indexed family of sets.
* `set.Inter`: Intersection of an indexed family of sets.
* `set.sInter`: **s**et **Inter**. Intersection of sets belonging to a set of sets.
* `set.sUnion`: **s**et **Union**. Union of sets belonging to a set of sets. This is actually
defined in core Lean.
* `set.sInter_eq_bInter`, `set.sUnion_eq_bInter`: Shows that `⋂₀ s = ⋂ x ∈ s, x` and
`⋃₀ s = ⋃ x ∈ s, x`.
* `set.complete_boolean_algebra`: `set α` is a `complete_boolean_algebra` with `≤ = ⊆`, `< = ⊂`,
`⊓ = ∩`, `⊔ = ∪`, `⨅ = ⋂`, `⨆ = ⋃` and `\` as the set difference. See `set.boolean_algebra`.
* `set.kern_image`: For a function `f : α → β`, `s.kern_image f` is the set of `y` such that
`f ⁻¹ y ⊆ s`.
* `set.seq`: Union of the image of a set under a **seq**uence of functions. `seq s t` is the union
of `f '' t` over all `f ∈ s`, where `t : set α` and `s : set (α → β)`.
* `set.Union_eq_sigma_of_disjoint`: Equivalence between `⋃ i, t i` and `Σ i, t i`, where `t` is an
indexed family of disjoint sets.
## Naming convention
In lemma names,
* `⋃ i, s i` is called `Union`
* `⋂ i, s i` is called `Inter`
* `⋃ i j, s i j` is called `Union₂`. This is a `Union` inside a `Union`.
* `⋂ i j, s i j` is called `Inter₂`. This is an `Inter` inside an `Inter`.
* `⋃ i ∈ s, t i` is called `bUnion` for "bounded `Union`". This is the special case of `Union₂`
where `j : i ∈ s`.
* `⋂ i ∈ s, t i` is called `bInter` for "bounded `Inter`". This is the special case of `Inter₂`
where `j : i ∈ s`.
## Notation
* `⋃`: `set.Union`
* `⋂`: `set.Inter`
* `⋃₀`: `set.sUnion`
* `⋂₀`: `set.sInter`
-/
open function tactic set
universes u
variables {α β γ : Type*} {ι ι' ι₂ : Sort*} {κ κ₁ κ₂ : ι → Sort*} {κ' : ι' → Sort*}
namespace set
/-! ### Complete lattice and complete Boolean algebra instances -/
instance : has_Inf (set α) := ⟨λ s, {a | ∀ t ∈ s, a ∈ t}⟩
instance : has_Sup (set α) := ⟨sUnion⟩
/-- Intersection of a set of sets. -/
def sInter (S : set (set α)) : set α := Inf S
prefix `⋂₀ `:110 := sInter
@[simp] theorem mem_sInter {x : α} {S : set (set α)} : x ∈ ⋂₀ S ↔ ∀ t ∈ S, x ∈ t := iff.rfl
/-- Indexed union of a family of sets -/
def Union (s : ι → set β) : set β := supr s
/-- Indexed intersection of a family of sets -/
def Inter (s : ι → set β) : set β := infi s
notation `⋃` binders `, ` r:(scoped f, Union f) := r
notation `⋂` binders `, ` r:(scoped f, Inter f) := r
@[simp] lemma Sup_eq_sUnion (S : set (set α)) : Sup S = ⋃₀ S := rfl
@[simp] lemma Inf_eq_sInter (S : set (set α)) : Inf S = ⋂₀ S := rfl
@[simp] lemma supr_eq_Union (s : ι → set α) : supr s = Union s := rfl
@[simp] lemma infi_eq_Inter (s : ι → set α) : infi s = Inter s := rfl
@[simp] lemma mem_Union {x : α} {s : ι → set α} : x ∈ (⋃ i, s i) ↔ ∃ i, x ∈ s i :=
⟨λ ⟨t, ⟨⟨a, (t_eq : s a = t)⟩, (h : x ∈ t)⟩⟩, ⟨a, t_eq.symm ▸ h⟩,
λ ⟨a, h⟩, ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩
@[simp] lemma mem_Inter {x : α} {s : ι → set α} : x ∈ (⋂ i, s i) ↔ ∀ i, x ∈ s i :=
⟨λ (h : ∀ a ∈ {a : set α | ∃ i, s i = a}, x ∈ a) a, h (s a) ⟨a, rfl⟩,
λ h t ⟨a, (eq : s a = t)⟩, eq ▸ h a⟩
lemma mem_Union₂ {x : γ} {s : Π i, κ i → set γ} : x ∈ (⋃ i j, s i j) ↔ ∃ i j, x ∈ s i j :=
by simp_rw mem_Union
lemma mem_Inter₂ {x : γ} {s : Π i, κ i → set γ} : x ∈ (⋂ i j, s i j) ↔ ∀ i j, x ∈ s i j :=
by simp_rw mem_Inter
lemma mem_Union_of_mem {s : ι → set α} {a : α} (i : ι) (ha : a ∈ s i) : a ∈ ⋃ i, s i :=
mem_Union.2 ⟨i, ha⟩
lemma mem_Union₂_of_mem {s : Π i, κ i → set α} {a : α} {i : ι} (j : κ i) (ha : a ∈ s i j) :
a ∈ ⋃ i j, s i j :=
mem_Union₂.2 ⟨i, j, ha⟩
lemma mem_Inter_of_mem {s : ι → set α} {a : α} (h : ∀ i, a ∈ s i) : a ∈ ⋂ i, s i := mem_Inter.2 h
lemma mem_Inter₂_of_mem {s : Π i, κ i → set α} {a : α} (h : ∀ i j, a ∈ s i j) : a ∈ ⋂ i j, s i j :=
mem_Inter₂.2 h
theorem mem_sUnion {x : α} {S : set (set α)} : x ∈ ⋃₀ S ↔ ∃ t ∈ S, x ∈ t := iff.rfl
instance : complete_boolean_algebra (set α) :=
{ Sup := Sup,
Inf := Inf,
le_Sup := λ s t t_in a a_in, ⟨t, ⟨t_in, a_in⟩⟩,
Sup_le := λ s t h a ⟨t', ⟨t'_in, a_in⟩⟩, h t' t'_in a_in,
le_Inf := λ s t h a a_in t' t'_in, h t' t'_in a_in,
Inf_le := λ s t t_in a h, h _ t_in,
infi_sup_le_sup_Inf := λ s S x, iff.mp $ by simp [forall_or_distrib_left],
inf_Sup_le_supr_inf := λ s S x, iff.mp $ by simp [exists_and_distrib_left],
.. set.boolean_algebra,
.. pi.complete_lattice }
/-- `set.image` is monotone. See `set.image_image` for the statement in terms of `⊆`. -/
lemma monotone_image {f : α → β} : monotone (image f) :=
λ s t, image_subset _
theorem _root_.monotone.inter [preorder β] {f g : β → set α}
(hf : monotone f) (hg : monotone g) : monotone (λ x, f x ∩ g x) :=
hf.inf hg
theorem _root_.antitone.inter [preorder β] {f g : β → set α}
(hf : antitone f) (hg : antitone g) : antitone (λ x, f x ∩ g x) :=
hf.inf hg
theorem _root_.monotone.union [preorder β] {f g : β → set α}
(hf : monotone f) (hg : monotone g) : monotone (λ x, f x ∪ g x) :=
hf.sup hg
theorem _root_.antitone.union [preorder β] {f g : β → set α}
(hf : antitone f) (hg : antitone g) : antitone (λ x, f x ∪ g x) :=
hf.sup hg
theorem monotone_set_of [preorder α] {p : α → β → Prop}
(hp : ∀ b, monotone (λ a, p a b)) : monotone (λ a, {b | p a b}) :=
λ a a' h b, hp b h
theorem antitone_set_of [preorder α] {p : α → β → Prop}
(hp : ∀ b, antitone (λ a, p a b)) : antitone (λ a, {b | p a b}) :=
λ a a' h b, hp b h
/-- Quantifying over a set is antitone in the set -/
lemma antitone_bforall {P : α → Prop} : antitone (λ s : set α, ∀ x ∈ s, P x) :=
λ s t hst h x hx, h x $ hst hx
section galois_connection
variables {f : α → β}
protected lemma image_preimage : galois_connection (image f) (preimage f) :=
λ a b, image_subset_iff
/-- `kern_image f s` is the set of `y` such that `f ⁻¹ y ⊆ s`. -/
def kern_image (f : α → β) (s : set α) : set β := {y | ∀ ⦃x⦄, f x = y → x ∈ s}
protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) :=
λ a b,
⟨ λ h x hx y hy, have f y ∈ a, from hy.symm ▸ hx, h this,
λ h x (hx : f x ∈ a), h hx rfl⟩
end galois_connection
/-! ### Union and intersection over an indexed family of sets -/
instance : order_top (set α) :=
{ top := univ,
le_top := by simp }
@[congr] theorem Union_congr_Prop {p q : Prop} {f₁ : p → set α} {f₂ : q → set α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : Union f₁ = Union f₂ :=
supr_congr_Prop pq f
@[congr] theorem Inter_congr_Prop {p q : Prop} {f₁ : p → set α} {f₂ : q → set α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : Inter f₁ = Inter f₂ :=
infi_congr_Prop pq f
lemma Union_eq_if {p : Prop} [decidable p] (s : set α) :
(⋃ h : p, s) = if p then s else ∅ :=
supr_eq_if _
lemma Union_eq_dif {p : Prop} [decidable p] (s : p → set α) :
(⋃ (h : p), s h) = if h : p then s h else ∅ :=
supr_eq_dif _
lemma Inter_eq_if {p : Prop} [decidable p] (s : set α) :
(⋂ h : p, s) = if p then s else univ :=
infi_eq_if _
lemma Infi_eq_dif {p : Prop} [decidable p] (s : p → set α) :
(⋂ (h : p), s h) = if h : p then s h else univ :=
infi_eq_dif _
lemma exists_set_mem_of_union_eq_top {ι : Type*} (t : set ι) (s : ι → set β)
(w : (⋃ i ∈ t, s i) = ⊤) (x : β) :
∃ (i ∈ t), x ∈ s i :=
begin
have p : x ∈ ⊤ := set.mem_univ x,
simpa only [←w, set.mem_Union] using p,
end
lemma nonempty_of_union_eq_top_of_nonempty
{ι : Type*} (t : set ι) (s : ι → set α) (H : nonempty α) (w : (⋃ i ∈ t, s i) = ⊤) :
t.nonempty :=
begin
obtain ⟨x, m, -⟩ := exists_set_mem_of_union_eq_top t s w H.some,
exact ⟨x, m⟩,
end
theorem set_of_exists (p : ι → β → Prop) : {x | ∃ i, p i x} = ⋃ i, {x | p i x} :=
ext $ λ i, mem_Union.symm
theorem set_of_forall (p : ι → β → Prop) : {x | ∀ i, p i x} = ⋂ i, {x | p i x} :=
ext $ λ i, mem_Inter.symm
lemma Union_subset {s : ι → set α} {t : set α} (h : ∀ i, s i ⊆ t) : (⋃ i, s i) ⊆ t :=
@supr_le (set α) _ _ _ _ h
lemma Union₂_subset {s : Π i, κ i → set α} {t : set α} (h : ∀ i j, s i j ⊆ t) :
(⋃ i j, s i j) ⊆ t :=
Union_subset $ λ x, Union_subset (h x)
theorem subset_Inter {t : set β} {s : ι → set β} (h : ∀ i, t ⊆ s i) : t ⊆ ⋂ i, s i :=
@le_infi (set β) _ _ _ _ h
lemma subset_Inter₂ {s : set α} {t : Π i, κ i → set α} (h : ∀ i j, s ⊆ t i j) : s ⊆ ⋂ i j, t i j :=
subset_Inter $ λ x, subset_Inter $ h x
@[simp] lemma Union_subset_iff {s : ι → set α} {t : set α} : (⋃ i, s i) ⊆ t ↔ ∀ i, s i ⊆ t :=
⟨λ h i, subset.trans (le_supr s _) h, Union_subset⟩
lemma Union₂_subset_iff {s : Π i, κ i → set α} {t : set α} :
(⋃ i j, s i j) ⊆ t ↔ ∀ i j, s i j ⊆ t :=
by simp_rw Union_subset_iff
@[simp] lemma subset_Inter_iff {s : set α} {t : ι → set α} : s ⊆ (⋂ i, t i) ↔ ∀ i, s ⊆ t i :=
@le_infi_iff (set α) _ _ _ _
@[simp] lemma subset_Inter₂_iff {s : set α} {t : Π i, κ i → set α} :
s ⊆ (⋂ i j, t i j) ↔ ∀ i j, s ⊆ t i j :=
by simp_rw subset_Inter_iff
lemma subset_Union : ∀ (s : ι → set β) (i : ι), s i ⊆ ⋃ i, s i := le_supr
lemma Inter_subset : ∀ (s : ι → set β) (i : ι), (⋂ i, s i) ⊆ s i := infi_le
lemma subset_Union₂ {s : Π i, κ i → set α} (i : ι) (j : κ i) : s i j ⊆ ⋃ i j, s i j :=
@le_supr₂ (set α) _ _ _ _ i j
lemma Inter₂_subset {s : Π i, κ i → set α} (i : ι) (j : κ i) : (⋂ i j, s i j) ⊆ s i j :=
@infi₂_le (set α) _ _ _ _ i j
/-- This rather trivial consequence of `subset_Union`is convenient with `apply`, and has `i`
explicit for this purpose. -/
lemma subset_Union_of_subset {s : set α} {t : ι → set α} (i : ι) (h : s ⊆ t i) : s ⊆ ⋃ i, t i :=
@le_supr_of_le (set α) _ _ _ _ i h
/-- This rather trivial consequence of `Inter_subset`is convenient with `apply`, and has `i`
explicit for this purpose. -/
lemma Inter_subset_of_subset {s : ι → set α} {t : set α} (i : ι) (h : s i ⊆ t) : (⋂ i, s i) ⊆ t :=
@infi_le_of_le (set α) _ _ _ _ i h
lemma Union_mono {s t : ι → set α} (h : ∀ i, s i ⊆ t i) : (⋃ i, s i) ⊆ ⋃ i, t i :=
@supr_mono (set α) _ _ s t h
lemma Union₂_mono {s t : Π i, κ i → set α} (h : ∀ i j, s i j ⊆ t i j) :
(⋃ i j, s i j) ⊆ ⋃ i j, t i j :=
@supr₂_mono (set α) _ _ _ s t h
lemma Inter_mono {s t : ι → set α} (h : ∀ i, s i ⊆ t i) : (⋂ i, s i) ⊆ ⋂ i, t i :=
@infi_mono (set α) _ _ s t h
lemma Inter₂_mono {s t : Π i, κ i → set α} (h : ∀ i j, s i j ⊆ t i j) :
(⋂ i j, s i j) ⊆ ⋂ i j, t i j :=
@infi₂_mono (set α) _ _ _ s t h
lemma Union_mono' {s : ι → set α} {t : ι₂ → set α} (h : ∀ i, ∃ j, s i ⊆ t j) :
(⋃ i, s i) ⊆ ⋃ i, t i :=
@supr_mono' (set α) _ _ _ s t h
lemma Union₂_mono' {s : Π i, κ i → set α} {t : Π i', κ' i' → set α}
(h : ∀ i j, ∃ i' j', s i j ⊆ t i' j') :
(⋃ i j, s i j) ⊆ ⋃ i' j', t i' j' :=
@supr₂_mono' (set α) _ _ _ _ _ s t h
lemma Inter_mono' {s : ι → set α} {t : ι' → set α} (h : ∀ j, ∃ i, s i ⊆ t j) :
(⋂ i, s i) ⊆ (⋂ j, t j) :=
set.subset_Inter $ λ j, let ⟨i, hi⟩ := h j in Inter_subset_of_subset i hi
lemma Inter₂_mono' {s : Π i, κ i → set α} {t : Π i', κ' i' → set α}
(h : ∀ i' j', ∃ i j, s i j ⊆ t i' j') :
(⋂ i j, s i j) ⊆ ⋂ i' j', t i' j' :=
subset_Inter₂_iff.2 $ λ i' j', let ⟨i, j, hst⟩ := h i' j' in (Inter₂_subset _ _).trans hst
lemma Union₂_subset_Union (κ : ι → Sort*) (s : ι → set α) : (⋃ i (j : κ i), s i) ⊆ ⋃ i, s i :=
Union_mono $ λ i, Union_subset $ λ h, subset.rfl
lemma Inter_subset_Inter₂ (κ : ι → Sort*) (s : ι → set α) : (⋂ i, s i) ⊆ ⋂ i (j : κ i), s i :=
Inter_mono $ λ i, subset_Inter $ λ h, subset.rfl
lemma Union_set_of (P : ι → α → Prop) : (⋃ i, {x : α | P i x}) = {x : α | ∃ i, P i x} :=
by { ext, exact mem_Union }
lemma Inter_set_of (P : ι → α → Prop) : (⋂ i, {x : α | P i x}) = {x : α | ∀ i, P i x} :=
by { ext, exact mem_Inter }
lemma Union_congr_of_surjective {f : ι → set α} {g : ι₂ → set α} (h : ι → ι₂)
(h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⋃ x, f x) = ⋃ y, g y :=
h1.supr_congr h h2
lemma Inter_congr_of_surjective {f : ι → set α} {g : ι₂ → set α} (h : ι → ι₂)
(h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⋂ x, f x) = ⋂ y, g y :=
h1.infi_congr h h2
theorem Union_const [nonempty ι] (s : set β) : (⋃ i : ι, s) = s := supr_const
theorem Inter_const [nonempty ι] (s : set β) : (⋂ i : ι, s) = s := infi_const
@[simp] theorem compl_Union (s : ι → set β) : (⋃ i, s i)ᶜ = (⋂ i, (s i)ᶜ) :=
compl_supr
lemma compl_Union₂ (s : Π i, κ i → set α) : (⋃ i j, s i j)ᶜ = ⋂ i j, (s i j)ᶜ :=
by simp_rw compl_Union
@[simp] theorem compl_Inter (s : ι → set β) : (⋂ i, s i)ᶜ = (⋃ i, (s i)ᶜ) :=
compl_infi
lemma compl_Inter₂ (s : Π i, κ i → set α) : (⋂ i j, s i j)ᶜ = ⋃ i j, (s i j)ᶜ :=
by simp_rw compl_Inter
-- classical -- complete_boolean_algebra
theorem Union_eq_compl_Inter_compl (s : ι → set β) : (⋃ i, s i) = (⋂ i, (s i)ᶜ)ᶜ :=
by simp only [compl_Inter, compl_compl]
-- classical -- complete_boolean_algebra
theorem Inter_eq_compl_Union_compl (s : ι → set β) : (⋂ i, s i) = (⋃ i, (s i)ᶜ)ᶜ :=
by simp only [compl_Union, compl_compl]
theorem inter_Union (s : set β) (t : ι → set β) :
s ∩ (⋃ i, t i) = ⋃ i, s ∩ t i :=
inf_supr_eq _ _
theorem Union_inter (s : set β) (t : ι → set β) :
(⋃ i, t i) ∩ s = ⋃ i, t i ∩ s :=
supr_inf_eq _ _
theorem Union_union_distrib (s : ι → set β) (t : ι → set β) :
(⋃ i, s i ∪ t i) = (⋃ i, s i) ∪ (⋃ i, t i) :=
supr_sup_eq
theorem Inter_inter_distrib (s : ι → set β) (t : ι → set β) :
(⋂ i, s i ∩ t i) = (⋂ i, s i) ∩ (⋂ i, t i) :=
infi_inf_eq
theorem union_Union [nonempty ι] (s : set β) (t : ι → set β) :
s ∪ (⋃ i, t i) = ⋃ i, s ∪ t i :=
sup_supr
theorem Union_union [nonempty ι] (s : set β) (t : ι → set β) :
(⋃ i, t i) ∪ s = ⋃ i, t i ∪ s :=
supr_sup
theorem inter_Inter [nonempty ι] (s : set β) (t : ι → set β) :
s ∩ (⋂ i, t i) = ⋂ i, s ∩ t i :=
inf_infi
theorem Inter_inter [nonempty ι] (s : set β) (t : ι → set β) :
(⋂ i, t i) ∩ s = ⋂ i, t i ∩ s :=
infi_inf
-- classical
theorem union_Inter (s : set β) (t : ι → set β) :
s ∪ (⋂ i, t i) = ⋂ i, s ∪ t i :=
sup_infi_eq _ _
theorem Union_diff (s : set β) (t : ι → set β) :
(⋃ i, t i) \ s = ⋃ i, t i \ s :=
Union_inter _ _
theorem diff_Union [nonempty ι] (s : set β) (t : ι → set β) :
s \ (⋃ i, t i) = ⋂ i, s \ t i :=
by rw [diff_eq, compl_Union, inter_Inter]; refl
theorem diff_Inter (s : set β) (t : ι → set β) :
s \ (⋂ i, t i) = ⋃ i, s \ t i :=
by rw [diff_eq, compl_Inter, inter_Union]; refl
lemma directed_on_Union {r} {f : ι → set α} (hd : directed (⊆) f)
(h : ∀ x, directed_on r (f x)) : directed_on r (⋃ x, f x) :=
by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact
λ a₁ b₁ fb₁ a₂ b₂ fb₂,
let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂,
⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in
⟨x, ⟨z, xf⟩, xa₁, xa₂⟩
lemma Union_inter_subset {ι α} {s t : ι → set α} : (⋃ i, s i ∩ t i) ⊆ (⋃ i, s i) ∩ (⋃ i, t i) :=
by { rintro x ⟨_, ⟨i, rfl⟩, xs, xt⟩, exact ⟨⟨_, ⟨i, rfl⟩, xs⟩, _, ⟨i, rfl⟩, xt⟩ }
lemma Union_inter_of_monotone {ι α} [semilattice_sup ι] {s t : ι → set α}
(hs : monotone s) (ht : monotone t) : (⋃ i, s i ∩ t i) = (⋃ i, s i) ∩ (⋃ i, t i) :=
begin
ext x, refine ⟨λ hx, Union_inter_subset hx, _⟩,
rintro ⟨⟨_, ⟨i, rfl⟩, xs⟩, _, ⟨j, rfl⟩, xt⟩,
exact ⟨_, ⟨i ⊔ j, rfl⟩, hs le_sup_left xs, ht le_sup_right xt⟩
end
/-- An equality version of this lemma is `Union_Inter_of_monotone` in `data.set.finite`. -/
lemma Union_Inter_subset {s : ι → ι' → set α} : (⋃ j, ⋂ i, s i j) ⊆ ⋂ i, ⋃ j, s i j :=
by { rintro x ⟨_, ⟨i, rfl⟩, hx⟩ _ ⟨j, rfl⟩, exact ⟨_, ⟨i, rfl⟩, hx _ ⟨j, rfl⟩⟩ }
lemma Union_option {ι} (s : option ι → set α) : (⋃ o, s o) = s none ∪ ⋃ i, s (some i) :=
supr_option s
lemma Inter_option {ι} (s : option ι → set α) : (⋂ o, s o) = s none ∩ ⋂ i, s (some i) :=
infi_option s
section
variables (p : ι → Prop) [decidable_pred p]
lemma Union_dite (f : Π i, p i → set α) (g : Π i, ¬p i → set α) :
(⋃ i, if h : p i then f i h else g i h) = (⋃ i (h : p i), f i h) ∪ (⋃ i (h : ¬ p i), g i h) :=
supr_dite _ _ _
lemma Union_ite (f g : ι → set α) :
(⋃ i, if p i then f i else g i) = (⋃ i (h : p i), f i) ∪ (⋃ i (h : ¬ p i), g i) :=
Union_dite _ _ _
lemma Inter_dite (f : Π i, p i → set α) (g : Π i, ¬p i → set α) :
(⋂ i, if h : p i then f i h else g i h) = (⋂ i (h : p i), f i h) ∩ (⋂ i (h : ¬ p i), g i h) :=
infi_dite _ _ _
lemma Inter_ite (f g : ι → set α) :
(⋂ i, if p i then f i else g i) = (⋂ i (h : p i), f i) ∩ (⋂ i (h : ¬ p i), g i) :=
Inter_dite _ _ _
end
lemma image_projection_prod {ι : Type*} {α : ι → Type*} {v : Π (i : ι), set (α i)}
(hv : (pi univ v).nonempty) (i : ι) :
(λ (x : Π (i : ι), α i), x i) '' (⋂ k, (λ (x : Π (j : ι), α j), x k) ⁻¹' v k) = v i:=
begin
classical,
apply subset.antisymm,
{ simp [Inter_subset] },
{ intros y y_in,
simp only [mem_image, mem_Inter, mem_preimage],
rcases hv with ⟨z, hz⟩,
refine ⟨function.update z i y, _, update_same i y z⟩,
rw @forall_update_iff ι α _ z i y (λ i t, t ∈ v i),
exact ⟨y_in, λ j hj, by simpa using hz j⟩ },
end
/-! ### Unions and intersections indexed by `Prop` -/
@[simp] theorem Inter_false {s : false → set α} : Inter s = univ := infi_false
@[simp] theorem Union_false {s : false → set α} : Union s = ∅ := supr_false
@[simp] theorem Inter_true {s : true → set α} : Inter s = s trivial := infi_true
@[simp] theorem Union_true {s : true → set α} : Union s = s trivial := supr_true
@[simp] theorem Inter_exists {p : ι → Prop} {f : Exists p → set α} :
(⋂ x, f x) = (⋂ i (h : p i), f ⟨i, h⟩) :=
infi_exists
@[simp] theorem Union_exists {p : ι → Prop} {f : Exists p → set α} :
(⋃ x, f x) = (⋃ i (h : p i), f ⟨i, h⟩) :=
supr_exists
@[simp] lemma Union_empty : (⋃ i : ι, ∅ : set α) = ∅ := supr_bot
@[simp] lemma Inter_univ : (⋂ i : ι, univ : set α) = univ := infi_top
section
variables {s : ι → set α}
@[simp] lemma Union_eq_empty : (⋃ i, s i) = ∅ ↔ ∀ i, s i = ∅ := supr_eq_bot
@[simp] lemma Inter_eq_univ : (⋂ i, s i) = univ ↔ ∀ i, s i = univ := infi_eq_top
@[simp] lemma nonempty_Union : (⋃ i, s i).nonempty ↔ ∃ i, (s i).nonempty :=
by simp [← ne_empty_iff_nonempty]
@[simp] lemma nonempty_bUnion {t : set α} {s : α → set β} :
(⋃ i ∈ t, s i).nonempty ↔ ∃ i ∈ t, (s i).nonempty :=
by simp [← ne_empty_iff_nonempty]
lemma Union_nonempty_index (s : set α) (t : s.nonempty → set β) :
(⋃ h, t h) = ⋃ x ∈ s, t ⟨x, ‹_›⟩ :=
supr_exists
end
@[simp] theorem Inter_Inter_eq_left {b : β} {s : Π x : β, x = b → set α} :
(⋂ x (h : x = b), s x h) = s b rfl :=
infi_infi_eq_left
@[simp] theorem Inter_Inter_eq_right {b : β} {s : Π x : β, b = x → set α} :
(⋂ x (h : b = x), s x h) = s b rfl :=
infi_infi_eq_right
@[simp] theorem Union_Union_eq_left {b : β} {s : Π x : β, x = b → set α} :
(⋃ x (h : x = b), s x h) = s b rfl :=
supr_supr_eq_left
@[simp] theorem Union_Union_eq_right {b : β} {s : Π x : β, b = x → set α} :
(⋃ x (h : b = x), s x h) = s b rfl :=
supr_supr_eq_right
theorem Inter_or {p q : Prop} (s : p ∨ q → set α) :
(⋂ h, s h) = (⋂ h : p, s (or.inl h)) ∩ (⋂ h : q, s (or.inr h)) :=
infi_or
theorem Union_or {p q : Prop} (s : p ∨ q → set α) :
(⋃ h, s h) = (⋃ i, s (or.inl i)) ∪ (⋃ j, s (or.inr j)) :=
supr_or
theorem Union_and {p q : Prop} (s : p ∧ q → set α) :
(⋃ h, s h) = ⋃ hp hq, s ⟨hp, hq⟩ :=
supr_and
theorem Inter_and {p q : Prop} (s : p ∧ q → set α) :
(⋂ h, s h) = ⋂ hp hq, s ⟨hp, hq⟩ :=
infi_and
theorem Union_comm (s : ι → ι' → set α) :
(⋃ i i', s i i') = ⋃ i' i, s i i' :=
supr_comm
theorem Inter_comm (s : ι → ι' → set α) :
(⋂ i i', s i i') = ⋂ i' i, s i i' :=
infi_comm
@[simp] theorem bUnion_and (p : ι → Prop) (q : ι → ι' → Prop) (s : Π x y, p x ∧ q x y → set α) :
(⋃ (x : ι) (y : ι') (h : p x ∧ q x y), s x y h) =
⋃ (x : ι) (hx : p x) (y : ι') (hy : q x y), s x y ⟨hx, hy⟩ :=
by simp only [Union_and, @Union_comm _ ι']
@[simp] theorem bUnion_and' (p : ι' → Prop) (q : ι → ι' → Prop) (s : Π x y, p y ∧ q x y → set α) :
(⋃ (x : ι) (y : ι') (h : p y ∧ q x y), s x y h) =
⋃ (y : ι') (hy : p y) (x : ι) (hx : q x y), s x y ⟨hy, hx⟩ :=
by simp only [Union_and, @Union_comm _ ι]
@[simp] theorem bInter_and (p : ι → Prop) (q : ι → ι' → Prop) (s : Π x y, p x ∧ q x y → set α) :
(⋂ (x : ι) (y : ι') (h : p x ∧ q x y), s x y h) =
⋂ (x : ι) (hx : p x) (y : ι') (hy : q x y), s x y ⟨hx, hy⟩ :=
by simp only [Inter_and, @Inter_comm _ ι']
@[simp] theorem bInter_and' (p : ι' → Prop) (q : ι → ι' → Prop) (s : Π x y, p y ∧ q x y → set α) :
(⋂ (x : ι) (y : ι') (h : p y ∧ q x y), s x y h) =
⋂ (y : ι') (hy : p y) (x : ι) (hx : q x y), s x y ⟨hy, hx⟩ :=
by simp only [Inter_and, @Inter_comm _ ι]
@[simp] theorem Union_Union_eq_or_left {b : β} {p : β → Prop} {s : Π x : β, (x = b ∨ p x) → set α} :
(⋃ x h, s x h) = s b (or.inl rfl) ∪ ⋃ x (h : p x), s x (or.inr h) :=
by simp only [Union_or, Union_union_distrib, Union_Union_eq_left]
@[simp] theorem Inter_Inter_eq_or_left {b : β} {p : β → Prop} {s : Π x : β, (x = b ∨ p x) → set α} :
(⋂ x h, s x h) = s b (or.inl rfl) ∩ ⋂ x (h : p x), s x (or.inr h) :=
by simp only [Inter_or, Inter_inter_distrib, Inter_Inter_eq_left]
/-! ### Bounded unions and intersections -/
/-- A specialization of `mem_Union₂`. -/
theorem mem_bUnion {s : set α} {t : α → set β} {x : α} {y : β} (xs : x ∈ s) (ytx : y ∈ t x) :
y ∈ ⋃ x ∈ s, t x :=
mem_Union₂_of_mem xs ytx
/-- A specialization of `mem_Inter₂`. -/
theorem mem_bInter {s : set α} {t : α → set β} {y : β} (h : ∀ x ∈ s, y ∈ t x) :
y ∈ ⋂ x ∈ s, t x :=
mem_Inter₂_of_mem h
/-- A specialization of `subset_Union₂`. -/
theorem subset_bUnion_of_mem {s : set α} {u : α → set β} {x : α} (xs : x ∈ s) :
u x ⊆ (⋃ x ∈ s, u x) :=
subset_Union₂ x xs
/-- A specialization of `Inter₂_subset`. -/
theorem bInter_subset_of_mem {s : set α} {t : α → set β} {x : α} (xs : x ∈ s) :
(⋂ x ∈ s, t x) ⊆ t x :=
Inter₂_subset x xs
theorem bUnion_subset_bUnion_left {s s' : set α} {t : α → set β}
(h : s ⊆ s') : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s', t x) :=
Union₂_subset $ λ x hx, subset_bUnion_of_mem $ h hx
theorem bInter_subset_bInter_left {s s' : set α} {t : α → set β}
(h : s' ⊆ s) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s', t x) :=
subset_Inter₂ $ λ x hx, bInter_subset_of_mem $ h hx
lemma bUnion_mono {s s' : set α} {t t' : α → set β} (hs : s' ⊆ s) (h : ∀ x ∈ s, t x ⊆ t' x) :
(⋃ x ∈ s', t x) ⊆ ⋃ x ∈ s, t' x :=
(bUnion_subset_bUnion_left hs).trans $ Union₂_mono h
lemma bInter_mono {s s' : set α} {t t' : α → set β} (hs : s ⊆ s') (h : ∀ x ∈ s, t x ⊆ t' x) :
(⋂ x ∈ s', t x) ⊆ (⋂ x ∈ s, t' x) :=
(bInter_subset_bInter_left hs).trans $ Inter₂_mono h
lemma Union_congr {s t : ι → set α} (h : ∀ i, s i = t i) : (⋃ i, s i) = ⋃ i, t i := supr_congr h
lemma Inter_congr {s t : ι → set α} (h : ∀ i, s i = t i) : (⋂ i, s i) = ⋂ i, t i := infi_congr h
lemma Union₂_congr {s t : Π i, κ i → set α} (h : ∀ i j, s i j = t i j) :
(⋃ i j, s i j) = ⋃ i j, t i j :=
Union_congr $ λ i, Union_congr $ h i
lemma Inter₂_congr {s t : Π i, κ i → set α} (h : ∀ i j, s i j = t i j) :
(⋂ i j, s i j) = ⋂ i j, t i j :=
Inter_congr $ λ i, Inter_congr $ h i
theorem bUnion_eq_Union (s : set α) (t : Π x ∈ s, set β) :
(⋃ x ∈ s, t x ‹_›) = (⋃ x : s, t x x.2) :=
supr_subtype'
theorem bInter_eq_Inter (s : set α) (t : Π x ∈ s, set β) :
(⋂ x ∈ s, t x ‹_›) = (⋂ x : s, t x x.2) :=
infi_subtype'
theorem Union_subtype (p : α → Prop) (s : {x // p x} → set β) :
(⋃ x : {x // p x}, s x) = ⋃ x (hx : p x), s ⟨x, hx⟩ :=
supr_subtype
theorem Inter_subtype (p : α → Prop) (s : {x // p x} → set β) :
(⋂ x : {x // p x}, s x) = ⋂ x (hx : p x), s ⟨x, hx⟩ :=
infi_subtype
theorem bInter_empty (u : α → set β) : (⋂ x ∈ (∅ : set α), u x) = univ :=
infi_emptyset
theorem bInter_univ (u : α → set β) : (⋂ x ∈ @univ α, u x) = ⋂ x, u x :=
infi_univ
@[simp] lemma bUnion_self (s : set α) : (⋃ x ∈ s, s) = s :=
subset.antisymm (Union₂_subset $ λ x hx, subset.refl s) (λ x hx, mem_bUnion hx hx)
@[simp] lemma Union_nonempty_self (s : set α) : (⋃ h : s.nonempty, s) = s :=
by rw [Union_nonempty_index, bUnion_self]
-- TODO(Jeremy): here is an artifact of the encoding of bounded intersection:
-- without dsimp, the next theorem fails to type check, because there is a lambda
-- in a type that needs to be contracted. Using simp [eq_of_mem_singleton xa] also works.
theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : set α), s x) = s a :=
infi_singleton
theorem bInter_union (s t : set α) (u : α → set β) :
(⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) :=
infi_union
theorem bInter_insert (a : α) (s : set α) (t : α → set β) :
(⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) :=
by simp
-- TODO(Jeremy): another example of where an annotation is needed
theorem bInter_pair (a b : α) (s : α → set β) :
(⋂ x ∈ ({a, b} : set α), s x) = s a ∩ s b :=
by rw [bInter_insert, bInter_singleton]
lemma bInter_inter {ι α : Type*} {s : set ι} (hs : s.nonempty) (f : ι → set α) (t : set α) :
(⋂ i ∈ s, f i ∩ t) = (⋂ i ∈ s, f i) ∩ t :=
begin
haveI : nonempty s := hs.to_subtype,
simp [bInter_eq_Inter, ← Inter_inter]
end
lemma inter_bInter {ι α : Type*} {s : set ι} (hs : s.nonempty) (f : ι → set α) (t : set α) :
(⋂ i ∈ s, t ∩ f i) = t ∩ ⋂ i ∈ s, f i :=
begin
rw [inter_comm, ← bInter_inter hs],
simp [inter_comm]
end
theorem bUnion_empty (s : α → set β) : (⋃ x ∈ (∅ : set α), s x) = ∅ :=
supr_emptyset
theorem bUnion_univ (s : α → set β) : (⋃ x ∈ @univ α, s x) = ⋃ x, s x :=
supr_univ
theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : set α), s x) = s a :=
supr_singleton
@[simp] theorem bUnion_of_singleton (s : set α) : (⋃ x ∈ s, {x}) = s :=
ext $ by simp
theorem bUnion_union (s t : set α) (u : α → set β) :
(⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) :=
supr_union
@[simp] lemma Union_coe_set {α β : Type*} (s : set α) (f : s → set β) :
(⋃ i, f i) = ⋃ i ∈ s, f ⟨i, ‹i ∈ s›⟩ :=
Union_subtype _ _
@[simp] lemma Inter_coe_set {α β : Type*} (s : set α) (f : s → set β) :
(⋂ i, f i) = ⋂ i ∈ s, f ⟨i, ‹i ∈ s›⟩ :=
Inter_subtype _ _
theorem bUnion_insert (a : α) (s : set α) (t : α → set β) :
(⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) :=
by simp
theorem bUnion_pair (a b : α) (s : α → set β) :
(⋃ x ∈ ({a, b} : set α), s x) = s a ∪ s b :=
by simp
lemma inter_Union₂ (s : set α) (t : Π i, κ i → set α) : s ∩ (⋃ i j, t i j) = ⋃ i j, s ∩ t i j :=
by simp only [inter_Union]
lemma Union₂_inter (s : Π i, κ i → set α) (t : set α) : (⋃ i j, s i j) ∩ t = ⋃ i j, s i j ∩ t :=
by simp_rw Union_inter
theorem mem_sUnion_of_mem {x : α} {t : set α} {S : set (set α)} (hx : x ∈ t) (ht : t ∈ S) :
x ∈ ⋃₀ S :=
⟨t, ht, hx⟩
-- is this theorem really necessary?
theorem not_mem_of_not_mem_sUnion {x : α} {t : set α} {S : set (set α)}
(hx : x ∉ ⋃₀ S) (ht : t ∈ S) : x ∉ t :=
λ h, hx ⟨t, ht, h⟩
theorem sInter_subset_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : ⋂₀ S ⊆ t :=
Inf_le tS
theorem subset_sUnion_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : t ⊆ ⋃₀ S :=
le_Sup tS
lemma subset_sUnion_of_subset {s : set α} (t : set (set α)) (u : set α) (h₁ : s ⊆ u)
(h₂ : u ∈ t) : s ⊆ ⋃₀ t :=
subset.trans h₁ (subset_sUnion_of_mem h₂)
theorem sUnion_subset {S : set (set α)} {t : set α} (h : ∀ t' ∈ S, t' ⊆ t) : (⋃₀ S) ⊆ t :=
Sup_le h
@[simp] theorem sUnion_subset_iff {s : set (set α)} {t : set α} : ⋃₀ s ⊆ t ↔ ∀ t' ∈ s, t' ⊆ t :=
@Sup_le_iff (set α) _ _ _
theorem subset_sInter {S : set (set α)} {t : set α} (h : ∀ t' ∈ S, t ⊆ t') : t ⊆ (⋂₀ S) :=
le_Inf h
@[simp] theorem subset_sInter_iff {S : set (set α)} {t : set α} : t ⊆ (⋂₀ S) ↔ ∀ t' ∈ S, t ⊆ t' :=
@le_Inf_iff (set α) _ _ _
theorem sUnion_subset_sUnion {S T : set (set α)} (h : S ⊆ T) : ⋃₀ S ⊆ ⋃₀ T :=
sUnion_subset $ λ s hs, subset_sUnion_of_mem (h hs)
theorem sInter_subset_sInter {S T : set (set α)} (h : S ⊆ T) : ⋂₀ T ⊆ ⋂₀ S :=
subset_sInter $ λ s hs, sInter_subset_of_mem (h hs)
@[simp] theorem sUnion_empty : ⋃₀ ∅ = (∅ : set α) := Sup_empty
@[simp] theorem sInter_empty : ⋂₀ ∅ = (univ : set α) := Inf_empty
@[simp] theorem sUnion_singleton (s : set α) : ⋃₀ {s} = s := Sup_singleton
@[simp] theorem sInter_singleton (s : set α) : ⋂₀ {s} = s := Inf_singleton
@[simp] theorem sUnion_eq_empty {S : set (set α)} : (⋃₀ S) = ∅ ↔ ∀ s ∈ S, s = ∅ := Sup_eq_bot
@[simp] theorem sInter_eq_univ {S : set (set α)} : (⋂₀ S) = univ ↔ ∀ s ∈ S, s = univ := Inf_eq_top
@[simp] theorem nonempty_sUnion {S : set (set α)} : (⋃₀ S).nonempty ↔ ∃ s ∈ S, set.nonempty s :=
by simp [← ne_empty_iff_nonempty]
lemma nonempty.of_sUnion {s : set (set α)} (h : (⋃₀ s).nonempty) : s.nonempty :=
let ⟨s, hs, _⟩ := nonempty_sUnion.1 h in ⟨s, hs⟩
lemma nonempty.of_sUnion_eq_univ [nonempty α] {s : set (set α)} (h : ⋃₀ s = univ) : s.nonempty :=
nonempty.of_sUnion $ h.symm ▸ univ_nonempty
theorem sUnion_union (S T : set (set α)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := Sup_union
theorem sInter_union (S T : set (set α)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := Inf_union
@[simp] theorem sUnion_insert (s : set α) (T : set (set α)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T :=
Sup_insert
@[simp] theorem sInter_insert (s : set α) (T : set (set α)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T :=
Inf_insert
theorem sUnion_pair (s t : set α) : ⋃₀ {s, t} = s ∪ t :=
Sup_pair
theorem sInter_pair (s t : set α) : ⋂₀ {s, t} = s ∩ t :=
Inf_pair
@[simp] theorem sUnion_image (f : α → set β) (s : set α) : ⋃₀ (f '' s) = ⋃ x ∈ s, f x := Sup_image
@[simp] theorem sInter_image (f : α → set β) (s : set α) : ⋂₀ (f '' s) = ⋂ x ∈ s, f x := Inf_image
@[simp] theorem sUnion_range (f : ι → set β) : ⋃₀ (range f) = ⋃ x, f x := rfl
@[simp] theorem sInter_range (f : ι → set β) : ⋂₀ (range f) = ⋂ x, f x := rfl
lemma Union_eq_univ_iff {f : ι → set α} : (⋃ i, f i) = univ ↔ ∀ x, ∃ i, x ∈ f i :=
by simp only [eq_univ_iff_forall, mem_Union]
lemma Union₂_eq_univ_iff {s : Π i, κ i → set α} : (⋃ i j, s i j) = univ ↔ ∀ a, ∃ i j, a ∈ s i j :=
by simp only [Union_eq_univ_iff, mem_Union]
lemma sUnion_eq_univ_iff {c : set (set α)} :
⋃₀ c = univ ↔ ∀ a, ∃ b ∈ c, a ∈ b :=
by simp only [eq_univ_iff_forall, mem_sUnion]
-- classical
lemma Inter_eq_empty_iff {f : ι → set α} : (⋂ i, f i) = ∅ ↔ ∀ x, ∃ i, x ∉ f i :=
by simp [set.eq_empty_iff_forall_not_mem]
-- classical
lemma Inter₂_eq_empty_iff {s : Π i, κ i → set α} : (⋂ i j, s i j) = ∅ ↔ ∀ a, ∃ i j, a ∉ s i j :=
by simp only [eq_empty_iff_forall_not_mem, mem_Inter, not_forall]
-- classical
lemma sInter_eq_empty_iff {c : set (set α)} :
⋂₀ c = ∅ ↔ ∀ a, ∃ b ∈ c, a ∉ b :=
by simp [set.eq_empty_iff_forall_not_mem]
-- classical
@[simp] theorem nonempty_Inter {f : ι → set α} : (⋂ i, f i).nonempty ↔ ∃ x, ∀ i, x ∈ f i :=
by simp [← ne_empty_iff_nonempty, Inter_eq_empty_iff]
-- classical
@[simp] lemma nonempty_Inter₂ {s : Π i, κ i → set α} :
(⋂ i j, s i j).nonempty ↔ ∃ a, ∀ i j, a ∈ s i j :=
by simp [← ne_empty_iff_nonempty, Inter_eq_empty_iff]
-- classical
@[simp] theorem nonempty_sInter {c : set (set α)}:
(⋂₀ c).nonempty ↔ ∃ a, ∀ b ∈ c, a ∈ b :=
by simp [← ne_empty_iff_nonempty, sInter_eq_empty_iff]
-- classical
theorem compl_sUnion (S : set (set α)) :
(⋃₀ S)ᶜ = ⋂₀ (compl '' S) :=
ext $ λ x, by simp
-- classical
theorem sUnion_eq_compl_sInter_compl (S : set (set α)) :
⋃₀ S = (⋂₀ (compl '' S))ᶜ :=
by rw [←compl_compl (⋃₀ S), compl_sUnion]
-- classical
theorem compl_sInter (S : set (set α)) :
(⋂₀ S)ᶜ = ⋃₀ (compl '' S) :=
by rw [sUnion_eq_compl_sInter_compl, compl_compl_image]
-- classical
theorem sInter_eq_compl_sUnion_compl (S : set (set α)) :
⋂₀ S = (⋃₀ (compl '' S))ᶜ :=
by rw [←compl_compl (⋂₀ S), compl_sInter]
theorem inter_empty_of_inter_sUnion_empty {s t : set α} {S : set (set α)} (hs : t ∈ S)
(h : s ∩ ⋃₀ S = ∅) :
s ∩ t = ∅ :=
eq_empty_of_subset_empty $ by rw ← h; exact
inter_subset_inter_right _ (subset_sUnion_of_mem hs)
theorem range_sigma_eq_Union_range {γ : α → Type*} (f : sigma γ → β) :
range f = ⋃ a, range (λ b, f ⟨a, b⟩) :=
set.ext $ by simp
theorem Union_eq_range_sigma (s : α → set β) : (⋃ i, s i) = range (λ a : Σ i, s i, a.2) :=
by simp [set.ext_iff]
theorem Union_image_preimage_sigma_mk_eq_self {ι : Type*} {σ : ι → Type*} (s : set (sigma σ)) :
(⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s)) = s :=
begin
ext x,
simp only [mem_Union, mem_image, mem_preimage],
split,
{ rintro ⟨i, a, h, rfl⟩, exact h },
{ intro h, cases x with i a, exact ⟨i, a, h, rfl⟩ }
end
lemma sigma.univ (X : α → Type*) : (set.univ : set (Σ a, X a)) = ⋃ a, range (sigma.mk a) :=
set.ext $ λ x, iff_of_true trivial ⟨range (sigma.mk x.1), set.mem_range_self _, x.2, sigma.eta x⟩
lemma sUnion_mono {s t : set (set α)} (h : s ⊆ t) : (⋃₀ s) ⊆ (⋃₀ t) :=
sUnion_subset $ λ t' ht', subset_sUnion_of_mem $ h ht'
lemma Union_subset_Union_const {s : set α} (h : ι → ι₂) : (⋃ i : ι, s) ⊆ (⋃ j : ι₂, s) :=
@supr_const_mono (set α) ι ι₂ _ s h
@[simp] lemma Union_singleton_eq_range {α β : Type*} (f : α → β) :
(⋃ (x : α), {f x}) = range f :=
by { ext x, simp [@eq_comm _ x] }
lemma Union_of_singleton (α : Type*) : (⋃ x, {x} : set α) = univ :=
by simp
lemma Union_of_singleton_coe (s : set α) :
(⋃ (i : s), {i} : set α) = s :=
by simp
lemma sUnion_eq_bUnion {s : set (set α)} : (⋃₀ s) = (⋃ (i : set α) (h : i ∈ s), i) :=
by rw [← sUnion_image, image_id']
lemma sInter_eq_bInter {s : set (set α)} : (⋂₀ s) = (⋂ (i : set α) (h : i ∈ s), i) :=
by rw [← sInter_image, image_id']
lemma sUnion_eq_Union {s : set (set α)} : (⋃₀ s) = (⋃ (i : s), i) :=
by simp only [←sUnion_range, subtype.range_coe]
lemma sInter_eq_Inter {s : set (set α)} : (⋂₀ s) = (⋂ (i : s), i) :=
by simp only [←sInter_range, subtype.range_coe]
lemma union_eq_Union {s₁ s₂ : set α} : s₁ ∪ s₂ = ⋃ b : bool, cond b s₁ s₂ :=
sup_eq_supr s₁ s₂
lemma inter_eq_Inter {s₁ s₂ : set α} : s₁ ∩ s₂ = ⋂ b : bool, cond b s₁ s₂ :=
inf_eq_infi s₁ s₂
lemma sInter_union_sInter {S T : set (set α)} :
(⋂₀ S) ∪ (⋂₀ T) = (⋂ p ∈ S ×ˢ T, (p : (set α) × (set α)).1 ∪ p.2) :=
Inf_sup_Inf
lemma sUnion_inter_sUnion {s t : set (set α)} :
(⋃₀ s) ∩ (⋃₀ t) = (⋃ p ∈ s ×ˢ t, (p : (set α) × (set α )).1 ∩ p.2) :=
Sup_inf_Sup
lemma bUnion_Union (s : ι → set α) (t : α → set β) :
(⋃ x ∈ ⋃ i, s i, t x) = ⋃ i (x ∈ s i), t x :=
by simp [@Union_comm _ ι]
lemma bInter_Union (s : ι → set α) (t : α → set β) :
(⋂ x ∈ ⋃ i, s i, t x) = ⋂ i (x ∈ s i), t x :=
by simp [@Inter_comm _ ι]
lemma sUnion_Union (s : ι → set (set α)) : ⋃₀ (⋃ i, s i) = ⋃ i, ⋃₀ (s i) :=
by simp only [sUnion_eq_bUnion, bUnion_Union]
theorem sInter_Union (s : ι → set (set α)) : ⋂₀ (⋃ i, s i) = ⋂ i, ⋂₀ s i :=
by simp only [sInter_eq_bInter, bInter_Union]
lemma Union_range_eq_sUnion {α β : Type*} (C : set (set α))
{f : ∀ (s : C), β → s} (hf : ∀ (s : C), surjective (f s)) :
(⋃ (y : β), range (λ (s : C), (f s y).val)) = ⋃₀ C :=
begin
ext x, split,
{ rintro ⟨s, ⟨y, rfl⟩, ⟨s, hs⟩, rfl⟩, refine ⟨_, hs, _⟩, exact (f ⟨s, hs⟩ y).2 },
{ rintro ⟨s, hs, hx⟩, cases hf ⟨s, hs⟩ ⟨x, hx⟩ with y hy, refine ⟨_, ⟨y, rfl⟩, ⟨s, hs⟩, _⟩,
exact congr_arg subtype.val hy }
end
lemma Union_range_eq_Union (C : ι → set α) {f : ∀ (x : ι), β → C x}
(hf : ∀ (x : ι), surjective (f x)) :
(⋃ (y : β), range (λ (x : ι), (f x y).val)) = ⋃ x, C x :=
begin
ext x, rw [mem_Union, mem_Union], split,
{ rintro ⟨y, i, rfl⟩, exact ⟨i, (f i y).2⟩ },
{ rintro ⟨i, hx⟩, cases hf i ⟨x, hx⟩ with y hy,
exact ⟨y, i, congr_arg subtype.val hy⟩ }
end
lemma union_distrib_Inter_left (s : ι → set α) (t : set α) : t ∪ (⋂ i, s i) = (⋂ i, t ∪ s i) :=
sup_infi_eq _ _
lemma union_distrib_Inter₂_left (s : set α) (t : Π i, κ i → set α) :
s ∪ (⋂ i j, t i j) = ⋂ i j, s ∪ t i j :=
by simp_rw union_distrib_Inter_left
lemma union_distrib_Inter_right (s : ι → set α) (t : set α) : (⋂ i, s i) ∪ t = (⋂ i, s i ∪ t) :=
infi_sup_eq _ _
lemma union_distrib_Inter₂_right (s : Π i, κ i → set α) (t : set α) :
(⋂ i j, s i j) ∪ t = ⋂ i j, s i j ∪ t :=
by simp_rw union_distrib_Inter_right
section function
/-! ### `maps_to` -/
lemma maps_to_sUnion {S : set (set α)} {t : set β} {f : α → β} (H : ∀ s ∈ S, maps_to f s t) :
maps_to f (⋃₀ S) t :=
λ x ⟨s, hs, hx⟩, H s hs hx
lemma maps_to_Union {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, maps_to f (s i) t) :
maps_to f (⋃ i, s i) t :=
maps_to_sUnion $ forall_range_iff.2 H
lemma maps_to_Union₂ {s : Π i, κ i → set α} {t : set β} {f : α → β}
(H : ∀ i j, maps_to f (s i j) t) :
maps_to f (⋃ i j, s i j) t :=
maps_to_Union $ λ i, maps_to_Union (H i)
lemma maps_to_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β}
(H : ∀ i, maps_to f (s i) (t i)) :
maps_to f (⋃ i, s i) (⋃ i, t i) :=
maps_to_Union $ λ i, (H i).mono (subset.refl _) (subset_Union t i)
lemma maps_to_Union₂_Union₂ {s : Π i, κ i → set α} {t : Π i, κ i → set β} {f : α → β}
(H : ∀ i j, maps_to f (s i j) (t i j)) :
maps_to f (⋃ i j, s i j) (⋃ i j, t i j) :=
maps_to_Union_Union $ λ i, maps_to_Union_Union (H i)
lemma maps_to_sInter {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, maps_to f s t) :
maps_to f s (⋂₀ T) :=
λ x hx t ht, H t ht hx
lemma maps_to_Inter {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f s (t i)) :
maps_to f s (⋂ i, t i) :=
λ x hx, mem_Inter.2 $ λ i, H i hx
lemma maps_to_Inter₂ {s : set α} {t : Π i, κ i → set β} {f : α → β}
(H : ∀ i j, maps_to f s (t i j)) :
maps_to f s (⋂ i j, t i j) :=
maps_to_Inter $ λ i, maps_to_Inter (H i)
lemma maps_to_Inter_Inter {s : ι → set α} {t : ι → set β} {f : α → β}
(H : ∀ i, maps_to f (s i) (t i)) :
maps_to f (⋂ i, s i) (⋂ i, t i) :=
maps_to_Inter $ λ i, (H i).mono (Inter_subset s i) (subset.refl _)
lemma maps_to_Inter₂_Inter₂ {s : Π i, κ i → set α} {t : Π i, κ i → set β} {f : α → β}
(H : ∀ i j, maps_to f (s i j) (t i j)) :
maps_to f (⋂ i j, s i j) (⋂ i j, t i j) :=
maps_to_Inter_Inter $ λ i, maps_to_Inter_Inter (H i)
lemma image_Inter_subset (s : ι → set α) (f : α → β) :
f '' (⋂ i, s i) ⊆ ⋂ i, f '' (s i) :=
(maps_to_Inter_Inter $ λ i, maps_to_image f (s i)).image_subset
lemma image_Inter₂_subset (s : Π i, κ i → set α) (f : α → β) :
f '' (⋂ i j, s i j) ⊆ ⋂ i j, f '' s i j :=
(maps_to_Inter₂_Inter₂ $ λ i hi, maps_to_image f (s i hi)).image_subset
lemma image_sInter_subset (S : set (set α)) (f : α → β) :
f '' (⋂₀ S) ⊆ ⋂ s ∈ S, f '' s :=
by { rw sInter_eq_bInter, apply image_Inter₂_subset }
/-! ### `inj_on` -/
lemma inj_on.image_inter {f : α → β} {s t u : set α} (hf : inj_on f u) (hs : s ⊆ u) (ht : t ⊆ u) :
f '' (s ∩ t) = f '' s ∩ f '' t :=
begin
apply subset.antisymm (image_inter_subset _ _ _),
rintros x ⟨⟨y, ys, hy⟩, ⟨z, zt, hz⟩⟩,
have : y = z,
{ apply hf (hs ys) (ht zt),
rwa ← hz at hy },
rw ← this at zt,
exact ⟨y, ⟨ys, zt⟩, hy⟩,
end
lemma inj_on.image_Inter_eq [nonempty ι] {s : ι → set α} {f : α → β} (h : inj_on f (⋃ i, s i)) :
f '' (⋂ i, s i) = ⋂ i, f '' (s i) :=
begin
inhabit ι,
refine subset.antisymm (image_Inter_subset s f) (λ y hy, _),
simp only [mem_Inter, mem_image_iff_bex] at hy,
choose x hx hy using hy,
refine ⟨x default, mem_Inter.2 $ λ i, _, hy _⟩,
suffices : x default = x i,
{ rw this, apply hx },
replace hx : ∀ i, x i ∈ ⋃ j, s j := λ i, (subset_Union _ _) (hx i),
apply h (hx _) (hx _),
simp only [hy]
end
lemma inj_on.image_bInter_eq {p : ι → Prop} {s : Π i (hi : p i), set α} (hp : ∃ i, p i) {f : α → β}
(h : inj_on f (⋃ i hi, s i hi)) :
f '' (⋂ i hi, s i hi) = ⋂ i hi, f '' (s i hi) :=
begin
simp only [Inter, infi_subtype'],
haveI : nonempty {i // p i} := nonempty_subtype.2 hp,
apply inj_on.image_Inter_eq,
simpa only [Union, supr_subtype'] using h
end
lemma inj_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s)
{f : α → β} (hf : ∀ i, inj_on f (s i)) :
inj_on f (⋃ i, s i) :=
begin
intros x hx y hy hxy,
rcases mem_Union.1 hx with ⟨i, hx⟩,
rcases mem_Union.1 hy with ⟨j, hy⟩,
rcases hs i j with ⟨k, hi, hj⟩,
exact hf k (hi hx) (hj hy) hxy
end
/-! ### `surj_on` -/
lemma surj_on_sUnion {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, surj_on f s t) :
surj_on f s (⋃₀ T) :=
λ x ⟨t, ht, hx⟩, H t ht hx
lemma surj_on_Union {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f s (t i)) :
surj_on f s (⋃ i, t i) :=
surj_on_sUnion $ forall_range_iff.2 H
lemma surj_on_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β}
(H : ∀ i, surj_on f (s i) (t i)) :
surj_on f (⋃ i, s i) (⋃ i, t i) :=
surj_on_Union $ λ i, (H i).mono (subset_Union _ _) (subset.refl _)
lemma surj_on_Union₂ {s : set α} {t : Π i, κ i → set β} {f : α → β}
(H : ∀ i j, surj_on f s (t i j)) :
surj_on f s (⋃ i j, t i j) :=
surj_on_Union $ λ i, surj_on_Union (H i)
lemma surj_on_Union₂_Union₂ {s : Π i, κ i → set α} {t : Π i, κ i → set β} {f : α → β}
(H : ∀ i j, surj_on f (s i j) (t i j)) :
surj_on f (⋃ i j, s i j) (⋃ i j, t i j) :=
surj_on_Union_Union $ λ i, surj_on_Union_Union (H i)
lemma surj_on_Inter [hi : nonempty ι] {s : ι → set α} {t : set β} {f : α → β}
(H : ∀ i, surj_on f (s i) t) (Hinj : inj_on f (⋃ i, s i)) :
surj_on f (⋂ i, s i) t :=
begin
intros y hy,
rw [Hinj.image_Inter_eq, mem_Inter],
exact λ i, H i hy
end
lemma surj_on_Inter_Inter [hi : nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β}
(H : ∀ i, surj_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) :
surj_on f (⋂ i, s i) (⋂ i, t i) :=
surj_on_Inter (λ i, (H i).mono (subset.refl _) (Inter_subset _ _)) Hinj
/-! ### `bij_on` -/
lemma bij_on_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i))
(Hinj : inj_on f (⋃ i, s i)) :
bij_on f (⋃ i, s i) (⋃ i, t i) :=
⟨maps_to_Union_Union $ λ i, (H i).maps_to, Hinj, surj_on_Union_Union $ λ i, (H i).surj_on⟩
lemma bij_on_Inter [hi :nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β}
(H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) :
bij_on f (⋂ i, s i) (⋂ i, t i) :=
⟨maps_to_Inter_Inter $ λ i, (H i).maps_to, hi.elim $ λ i, (H i).inj_on.mono (Inter_subset _ _),
surj_on_Inter_Inter (λ i, (H i).surj_on) Hinj⟩
lemma bij_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β}
(H : ∀ i, bij_on f (s i) (t i)) :
bij_on f (⋃ i, s i) (⋃ i, t i) :=
bij_on_Union H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on)
lemma bij_on_Inter_of_directed [nonempty ι] {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β}
{f : α → β} (H : ∀ i, bij_on f (s i) (t i)) :
bij_on f (⋂ i, s i) (⋂ i, t i) :=
bij_on_Inter H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on)
end function
/-! ### `image`, `preimage` -/
section image
lemma image_Union {f : α → β} {s : ι → set α} : f '' (⋃ i, s i) = (⋃ i, f '' s i) :=
begin
ext1 x,
simp [image, ← exists_and_distrib_right, @exists_swap α]
end
lemma image_Union₂ (f : α → β) (s : Π i, κ i → set α) : f '' (⋃ i j, s i j) = ⋃ i j, f '' s i j :=
by simp_rw image_Union
lemma univ_subtype {p : α → Prop} : (univ : set (subtype p)) = (⋃ x (h : p x), {⟨x, h⟩}) :=
set.ext $ λ ⟨x, h⟩, by simp [h]
lemma range_eq_Union {ι} (f : ι → α) : range f = (⋃ i, {f i}) :=
set.ext $ λ a, by simp [@eq_comm α a]
lemma image_eq_Union (f : α → β) (s : set α) : f '' s = (⋃ i ∈ s, {f i}) :=
set.ext $ λ b, by simp [@eq_comm β b]
lemma bUnion_range {f : ι → α} {g : α → set β} : (⋃ x ∈ range f, g x) = (⋃ y, g (f y)) :=
supr_range
@[simp] lemma Union_Union_eq' {f : ι → α} {g : α → set β} :
(⋃ x y (h : f y = x), g x) = ⋃ y, g (f y) :=
by simpa using bUnion_range
lemma bInter_range {f : ι → α} {g : α → set β} : (⋂ x ∈ range f, g x) = (⋂ y, g (f y)) :=
infi_range
@[simp] lemma Inter_Inter_eq' {f : ι → α} {g : α → set β} :
(⋂ x y (h : f y = x), g x) = ⋂ y, g (f y) :=
by simpa using bInter_range
variables {s : set γ} {f : γ → α} {g : α → set β}
lemma bUnion_image : (⋃ x ∈ f '' s, g x) = (⋃ y ∈ s, g (f y)) :=
supr_image
lemma bInter_image : (⋂ x ∈ f '' s, g x) = (⋂ y ∈ s, g (f y)) :=
infi_image
end image
section preimage
theorem monotone_preimage {f : α → β} : monotone (preimage f) := λ a b h, preimage_mono h
@[simp] lemma preimage_Union {f : α → β} {s : ι → set β} : f ⁻¹' (⋃ i, s i) = (⋃ i, f ⁻¹' s i) :=
set.ext $ by simp [preimage]
lemma preimage_Union₂ {f : α → β} {s : Π i, κ i → set β} :
f ⁻¹' (⋃ i j, s i j) = ⋃ i j, f ⁻¹' s i j :=
by simp_rw preimage_Union
@[simp] theorem preimage_sUnion {f : α → β} {s : set (set β)} :
f ⁻¹' (⋃₀ s) = (⋃ t ∈ s, f ⁻¹' t) :=
by rw [sUnion_eq_bUnion, preimage_Union₂]
lemma preimage_Inter {f : α → β} {s : ι → set β} : f ⁻¹' (⋂ i, s i) = (⋂ i, f ⁻¹' s i) :=
by ext; simp
lemma preimage_Inter₂ {f : α → β} {s : Π i, κ i → set β} :
f ⁻¹' (⋂ i j, s i j) = ⋂ i j, f ⁻¹' s i j :=
by simp_rw preimage_Inter
@[simp] lemma preimage_sInter {f : α → β} {s : set (set β)} : f ⁻¹' (⋂₀ s) = ⋂ t ∈ s, f ⁻¹' t :=
by rw [sInter_eq_bInter, preimage_Inter₂]
@[simp] lemma bUnion_preimage_singleton (f : α → β) (s : set β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' s :=
by rw [← preimage_Union₂, bUnion_of_singleton]
lemma bUnion_range_preimage_singleton (f : α → β) : (⋃ y ∈ range f, f ⁻¹' {y}) = univ :=
by rw [bUnion_preimage_singleton, preimage_range]
end preimage
section prod
theorem monotone_prod [preorder α] {f : α → set β} {g : α → set γ}
(hf : monotone f) (hg : monotone g) : monotone (λ x, f x ×ˢ g x) :=
λ a b h, prod_mono (hf h) (hg h)
alias monotone_prod ← monotone.set_prod
lemma prod_Union {s : set α} {t : ι → set β} : s ×ˢ (⋃ i, t i) = ⋃ i, s ×ˢ (t i) := by { ext, simp }
lemma prod_Union₂ {s : set α} {t : Π i, κ i → set β} : s ×ˢ (⋃ i j, t i j) = ⋃ i j, s ×ˢ t i j :=
by simp_rw [prod_Union]
lemma prod_sUnion {s : set α} {C : set (set β)} : s ×ˢ (⋃₀ C) = ⋃₀ ((λ t, s ×ˢ t) '' C) :=
by simp_rw [sUnion_eq_bUnion, bUnion_image, prod_Union₂]
lemma Union_prod_const {s : ι → set α} {t : set β} : (⋃ i, s i) ×ˢ t = ⋃ i, s i ×ˢ t :=
by { ext, simp }
lemma Union₂_prod_const {s : Π i, κ i → set α} {t : set β} :
(⋃ i j, s i j) ×ˢ t = ⋃ i j, s i j ×ˢ t :=
by simp_rw [Union_prod_const]
lemma sUnion_prod_const {C : set (set α)} {t : set β} :
(⋃₀ C) ×ˢ t = ⋃₀ ((λ s : set α, s ×ˢ t) '' C) :=
by simp only [sUnion_eq_bUnion, Union₂_prod_const, bUnion_image]
lemma Union_prod {ι ι' α β} (s : ι → set α) (t : ι' → set β) :
(⋃ (x : ι × ι'), s x.1 ×ˢ t x.2) = (⋃ (i : ι), s i) ×ˢ (⋃ (i : ι'), t i) :=
by { ext, simp }
lemma Union_prod_of_monotone [semilattice_sup α] {s : α → set β} {t : α → set γ}
(hs : monotone s) (ht : monotone t) : (⋃ x, s x ×ˢ t x) = (⋃ x, s x) ×ˢ (⋃ x, t x) :=
begin
ext ⟨z, w⟩, simp only [mem_prod, mem_Union, exists_imp_distrib, and_imp, iff_def], split,
{ intros x hz hw, exact ⟨⟨x, hz⟩, x, hw⟩ },
{ intros x hz x' hw, exact ⟨x ⊔ x', hs le_sup_left hz, ht le_sup_right hw⟩ }
end
end prod
section image2
variables (f : α → β → γ) {s : set α} {t : set β}
lemma Union_image_left : (⋃ a ∈ s, f a '' t) = image2 f s t :=
by { ext y, split; simp only [mem_Union]; rintro ⟨a, ha, x, hx, ax⟩; exact ⟨a, x, ha, hx, ax⟩ }
lemma Union_image_right : (⋃ b ∈ t, (λ a, f a b) '' s) = image2 f s t :=
by { ext y, split; simp only [mem_Union]; rintro ⟨a, b, c, d, e⟩, exact ⟨c, a, d, b, e⟩,
exact ⟨b, d, a, c, e⟩ }
lemma image2_Union_left (s : ι → set α) (t : set β) :
image2 f (⋃ i, s i) t = ⋃ i, image2 f (s i) t :=
by simp only [← image_prod, Union_prod_const, image_Union]
lemma image2_Union_right (s : set α) (t : ι → set β) :
image2 f s (⋃ i, t i) = ⋃ i, image2 f s (t i) :=
by simp only [← image_prod, prod_Union, image_Union]
lemma image2_Union₂_left (s : Π i, κ i → set α) (t : set β) :
image2 f (⋃ i j, s i j) t = ⋃ i j, image2 f (s i j) t :=
by simp_rw image2_Union_left
lemma image2_Union₂_right (s : set α) (t : Π i, κ i → set β) :
image2 f s (⋃ i j, t i j) = ⋃ i j, image2 f s (t i j) :=
by simp_rw image2_Union_right
lemma image2_Inter_subset_left (s : ι → set α) (t : set β) :
image2 f (⋂ i, s i) t ⊆ ⋂ i, image2 f (s i) t :=
by { simp_rw [image2_subset_iff, mem_Inter], exact λ x hx y hy i, mem_image2_of_mem (hx _) hy }
lemma image2_Inter_subset_right (s : set α) (t : ι → set β) :
image2 f s (⋂ i, t i) ⊆ ⋂ i, image2 f s (t i) :=
by { simp_rw [image2_subset_iff, mem_Inter], exact λ x hx y hy i, mem_image2_of_mem hx (hy _) }
lemma image2_Inter₂_subset_left (s : Π i, κ i → set α) (t : set β) :
image2 f (⋂ i j, s i j) t ⊆ ⋂ i j, image2 f (s i j) t :=
by { simp_rw [image2_subset_iff, mem_Inter], exact λ x hx y hy i j, mem_image2_of_mem (hx _ _) hy }
lemma image2_Inter₂_subset_right (s : set α) (t : Π i, κ i → set β) :
image2 f s (⋂ i j, t i j) ⊆ ⋂ i j, image2 f s (t i j) :=
by { simp_rw [image2_subset_iff, mem_Inter], exact λ x hx y hy i j, mem_image2_of_mem hx (hy _ _) }
/-- The `set.image2` version of `set.image_eq_Union` -/
lemma image2_eq_Union (s : set α) (t : set β) : image2 f s t = ⋃ (i ∈ s) (j ∈ t), {f i j} :=
by simp_rw [←image_eq_Union, Union_image_left]
end image2
section seq
/-- Given a set `s` of functions `α → β` and `t : set α`, `seq s t` is the union of `f '' t` over
all `f ∈ s`. -/
def seq (s : set (α → β)) (t : set α) : set β := {b | ∃ f ∈ s, ∃ a ∈ t, (f : α → β) a = b}
lemma seq_def {s : set (α → β)} {t : set α} : seq s t = ⋃ f ∈ s, f '' t :=
set.ext $ by simp [seq]
@[simp] lemma mem_seq_iff {s : set (α → β)} {t : set α} {b : β} :
b ∈ seq s t ↔ ∃ (f ∈ s) (a ∈ t), (f : α → β) a = b :=
iff.rfl
lemma seq_subset {s : set (α → β)} {t : set α} {u : set β} :
seq s t ⊆ u ↔ (∀ f ∈ s, ∀ a ∈ t, (f : α → β) a ∈ u) :=
iff.intro
(λ h f hf a ha, h ⟨f, hf, a, ha, rfl⟩)
(λ h b ⟨f, hf, a, ha, eq⟩, eq ▸ h f hf a ha)
lemma seq_mono {s₀ s₁ : set (α → β)} {t₀ t₁ : set α} (hs : s₀ ⊆ s₁) (ht : t₀ ⊆ t₁) :
seq s₀ t₀ ⊆ seq s₁ t₁ :=
λ b ⟨f, hf, a, ha, eq⟩, ⟨f, hs hf, a, ht ha, eq⟩
lemma singleton_seq {f : α → β} {t : set α} : set.seq {f} t = f '' t :=
set.ext $ by simp
lemma seq_singleton {s : set (α → β)} {a : α} : set.seq s {a} = (λ f : α → β, f a) '' s :=
set.ext $ by simp
lemma seq_seq {s : set (β → γ)} {t : set (α → β)} {u : set α} :
seq s (seq t u) = seq (seq ((∘) '' s) t) u :=
begin
refine set.ext (λ c, iff.intro _ _),
{ rintro ⟨f, hfs, b, ⟨g, hg, a, hau, rfl⟩, rfl⟩,
exact ⟨f ∘ g, ⟨(∘) f, mem_image_of_mem _ hfs, g, hg, rfl⟩, a, hau, rfl⟩ },
{ rintro ⟨fg, ⟨fc, ⟨f, hfs, rfl⟩, g, hgt, rfl⟩, a, ha, rfl⟩,
exact ⟨f, hfs, g a, ⟨g, hgt, a, ha, rfl⟩, rfl⟩ }
end
lemma image_seq {f : β → γ} {s : set (α → β)} {t : set α} :
f '' seq s t = seq ((∘) f '' s) t :=
by rw [← singleton_seq, ← singleton_seq, seq_seq, image_singleton]
lemma prod_eq_seq {s : set α} {t : set β} : s ×ˢ t = (prod.mk '' s).seq t :=
begin
ext ⟨a, b⟩,
split,
{ rintro ⟨ha, hb⟩, exact ⟨prod.mk a, ⟨a, ha, rfl⟩, b, hb, rfl⟩ },
{ rintro ⟨f, ⟨x, hx, rfl⟩, y, hy, eq⟩, rw ← eq, exact ⟨hx, hy⟩ }
end
lemma prod_image_seq_comm (s : set α) (t : set β) :
(prod.mk '' s).seq t = seq ((λ b a, (a, b)) '' t) s :=
by rw [← prod_eq_seq, ← image_swap_prod, prod_eq_seq, image_seq, ← image_comp, prod.swap]
lemma image2_eq_seq (f : α → β → γ) (s : set α) (t : set β) : image2 f s t = seq (f '' s) t :=
by { ext, simp }
end seq
section pi
variables {π : α → Type*}
lemma pi_def (i : set α) (s : Π a, set (π a)) :
pi i s = (⋂ a ∈ i, eval a ⁻¹' s a) :=
by { ext, simp }
lemma univ_pi_eq_Inter (t : Π i, set (π i)) : pi univ t = ⋂ i, eval i ⁻¹' t i :=
by simp only [pi_def, Inter_true, mem_univ]
lemma pi_diff_pi_subset (i : set α) (s t : Π a, set (π a)) :
pi i s \ pi i t ⊆ ⋃ a ∈ i, (eval a ⁻¹' (s a \ t a)) :=
begin
refine diff_subset_comm.2 (λ x hx a ha, _),
simp only [mem_diff, mem_pi, mem_Union, not_exists, mem_preimage, not_and, not_not, eval_apply]
at hx,
exact hx.2 _ ha (hx.1 _ ha)
end
lemma Union_univ_pi (t : Π i, ι → set (π i)) :
(⋃ (x : α → ι), pi univ (λ i, t i (x i))) = pi univ (λ i, ⋃ (j : ι), t i j) :=
by { ext, simp [classical.skolem] }
end pi
end set
namespace function
namespace surjective
lemma Union_comp {f : ι → ι₂} (hf : surjective f) (g : ι₂ → set α) :
(⋃ x, g (f x)) = ⋃ y, g y :=
hf.supr_comp g
lemma Inter_comp {f : ι → ι₂} (hf : surjective f) (g : ι₂ → set α) :
(⋂ x, g (f x)) = ⋂ y, g y :=
hf.infi_comp g
end surjective
end function
/-!
### Disjoint sets
We define some lemmas in the `disjoint` namespace to be able to use projection notation.
-/
section disjoint
variables {s t u : set α}
namespace disjoint
theorem union_left (hs : disjoint s u) (ht : disjoint t u) : disjoint (s ∪ t) u :=
hs.sup_left ht
theorem union_right (ht : disjoint s t) (hu : disjoint s u) : disjoint s (t ∪ u) :=
ht.sup_right hu
lemma inter_left (u : set α) (h : disjoint s t) : disjoint (s ∩ u) t :=
inf_left _ h
lemma inter_left' (u : set α) (h : disjoint s t) : disjoint (u ∩ s) t :=
inf_left' _ h
lemma inter_right (u : set α) (h : disjoint s t) : disjoint s (t ∩ u) :=
inf_right _ h
lemma inter_right' (u : set α) (h : disjoint s t) : disjoint s (u ∩ t) :=
inf_right' _ h
lemma subset_left_of_subset_union (h : s ⊆ t ∪ u) (hac : disjoint s u) : s ⊆ t :=
hac.left_le_of_le_sup_right h
lemma subset_right_of_subset_union (h : s ⊆ t ∪ u) (hab : disjoint s t) : s ⊆ u :=
hab.left_le_of_le_sup_left h
lemma preimage {α β} (f : α → β) {s t : set β} (h : disjoint s t) : disjoint (f ⁻¹' s) (f ⁻¹' t) :=
λ x hx, h hx
end disjoint
namespace set
protected theorem disjoint_iff : disjoint s t ↔ s ∩ t ⊆ ∅ := iff.rfl
theorem disjoint_iff_inter_eq_empty : disjoint s t ↔ s ∩ t = ∅ :=
disjoint_iff
lemma not_disjoint_iff : ¬disjoint s t ↔ ∃ x, x ∈ s ∧ x ∈ t :=
not_forall.trans $ exists_congr $ λ x, not_not
lemma not_disjoint_iff_nonempty_inter : ¬disjoint s t ↔ (s ∩ t).nonempty :=
by simp [set.not_disjoint_iff, set.nonempty_def]
alias not_disjoint_iff_nonempty_inter ↔ _ set.nonempty.not_disjoint
lemma disjoint_or_nonempty_inter (s t : set α) : disjoint s t ∨ (s ∩ t).nonempty :=
(em _).imp_right not_disjoint_iff_nonempty_inter.mp
lemma disjoint_left : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t :=
show (∀ x, ¬(x ∈ s ∩ t)) ↔ _, from ⟨λ h a, not_and.1 $ h a, λ h a, not_and.2 $ h a⟩
theorem disjoint_right : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
by rw [disjoint.comm, disjoint_left]
lemma disjoint_iff_forall_ne : disjoint s t ↔ ∀ (x ∈ s) (y ∈ t), x ≠ y :=
by simp only [ne.def, disjoint_left, @imp_not_comm _ (_ = _), forall_eq']
lemma _root_.disjoint.ne_of_mem (h : disjoint s t) {x y} (hx : x ∈ s) (hy : y ∈ t) : x ≠ y :=
disjoint_iff_forall_ne.mp h x hx y hy
theorem disjoint_of_subset_left (h : s ⊆ u) (d : disjoint u t) : disjoint s t :=
d.mono_left h
theorem disjoint_of_subset_right (h : t ⊆ u) (d : disjoint s u) : disjoint s t :=
d.mono_right h
theorem disjoint_of_subset {s t u v : set α} (h1 : s ⊆ u) (h2 : t ⊆ v) (d : disjoint u v) :
disjoint s t :=
d.mono h1 h2
@[simp] theorem disjoint_union_left :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
disjoint_sup_left
@[simp] theorem disjoint_union_right :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
disjoint_sup_right
@[simp] theorem disjoint_Union_left {ι : Sort*} {s : ι → set α} :
disjoint (⋃ i, s i) t ↔ ∀ i, disjoint (s i) t :=
supr_disjoint_iff
@[simp] theorem disjoint_Union_right {ι : Sort*} {s : ι → set α} :
disjoint t (⋃ i, s i) ↔ ∀ i, disjoint t (s i) :=
disjoint_supr_iff
theorem disjoint_diff {a b : set α} : disjoint a (b \ a) :=
disjoint_iff.2 (inter_diff_self _ _)
@[simp] theorem disjoint_empty (s : set α) : disjoint s ∅ := disjoint_bot_right
@[simp] theorem empty_disjoint (s : set α) : disjoint ∅ s := disjoint_bot_left
@[simp] lemma univ_disjoint {s : set α} : disjoint univ s ↔ s = ∅ :=
top_disjoint
@[simp] lemma disjoint_univ {s : set α} : disjoint s univ ↔ s = ∅ :=
disjoint_top
@[simp] theorem disjoint_singleton_left {a : α} {s : set α} : disjoint {a} s ↔ a ∉ s :=
by simp [set.disjoint_iff, subset_def]; exact iff.rfl
@[simp] theorem disjoint_singleton_right {a : α} {s : set α} : disjoint s {a} ↔ a ∉ s :=
by rw [disjoint.comm]; exact disjoint_singleton_left
@[simp] lemma disjoint_singleton {a b : α} : disjoint ({a} : set α) {b} ↔ a ≠ b :=
by rw [disjoint_singleton_left, mem_singleton_iff]
theorem disjoint_image_image {f : β → α} {g : γ → α} {s : set β} {t : set γ}
(h : ∀ b ∈ s, ∀ c ∈ t, f b ≠ g c) : disjoint (f '' s) (g '' t) :=
by rintro a ⟨⟨b, hb, eq⟩, c, hc, rfl⟩; exact h b hb c hc eq
lemma disjoint_image_of_injective {f : α → β} (hf : injective f) {s t : set α}
(hd : disjoint s t) : disjoint (f '' s) (f '' t) :=
disjoint_image_image $ λ x hx y hy, hf.ne $ λ H, set.disjoint_iff.1 hd ⟨hx, H.symm ▸ hy⟩
lemma disjoint_preimage {s t : set β} (hd : disjoint s t) (f : α → β) :
disjoint (f ⁻¹' s) (f ⁻¹' t) :=
λ x hx, hd hx
lemma preimage_eq_empty {f : α → β} {s : set β} (h : disjoint s (range f)) :
f ⁻¹' s = ∅ :=
by simpa using h.preimage f
lemma preimage_eq_empty_iff {f : α → β} {s : set β} : disjoint s (range f) ↔ f ⁻¹' s = ∅ :=
⟨preimage_eq_empty,
λ h, begin
simp only [eq_empty_iff_forall_not_mem, disjoint_iff_inter_eq_empty, not_exists,
mem_inter_eq, not_and, mem_range, mem_preimage] at h ⊢,
assume y hy x hx,
rw ← hx at hy,
exact h x hy,
end ⟩
lemma disjoint_iff_subset_compl_right :
disjoint s t ↔ s ⊆ tᶜ :=
disjoint_left
lemma disjoint_iff_subset_compl_left :
disjoint s t ↔ t ⊆ sᶜ :=
disjoint_right
lemma _root_.disjoint.image {s t u : set α} {f : α → β} (h : disjoint s t) (hf : inj_on f u)
(hs : s ⊆ u) (ht : t ⊆ u) : disjoint (f '' s) (f '' t) :=
begin
rw disjoint_iff_inter_eq_empty at h ⊢,
rw [← hf.image_inter hs ht, h, image_empty],
end
end set
end disjoint
/-! ### Intervals -/
namespace set
variables [complete_lattice α]
lemma Ici_supr (f : ι → α) : Ici (⨆ i, f i) = ⋂ i, Ici (f i) :=
ext $ λ _, by simp only [mem_Ici, supr_le_iff, mem_Inter]
lemma Iic_infi (f : ι → α) : Iic (⨅ i, f i) = ⋂ i, Iic (f i) :=
ext $ λ _, by simp only [mem_Iic, le_infi_iff, mem_Inter]
lemma Ici_supr₂ (f : Π i, κ i → α) : Ici (⨆ i j, f i j) = ⋂ i j, Ici (f i j) := by simp_rw Ici_supr
lemma Iic_infi₂ (f : Π i, κ i → α) : Iic (⨅ i j, f i j) = ⋂ i j, Iic (f i j) := by simp_rw Iic_infi
lemma Ici_Sup (s : set α) : Ici (Sup s) = ⋂ a ∈ s, Ici a := by rw [Sup_eq_supr, Ici_supr₂]
lemma Iic_Inf (s : set α) : Iic (Inf s) = ⋂ a ∈ s, Iic a := by rw [Inf_eq_infi, Iic_infi₂]
end set
namespace set
variables (t : α → set β)
lemma subset_diff {s t u : set α} : s ⊆ t \ u ↔ s ⊆ t ∧ disjoint s u :=
⟨λ h, ⟨λ x hxs, (h hxs).1, λ x ⟨hxs, hxu⟩, (h hxs).2 hxu⟩,
λ ⟨h1, h2⟩ x hxs, ⟨h1 hxs, λ hxu, h2 ⟨hxs, hxu⟩⟩⟩
lemma bUnion_diff_bUnion_subset (s₁ s₂ : set α) :
(⋃ x ∈ s₁, t x) \ (⋃ x ∈ s₂, t x) ⊆ (⋃ x ∈ s₁ \ s₂, t x) :=
begin
simp only [diff_subset_iff, ← bUnion_union],
apply bUnion_subset_bUnion_left,
rw union_diff_self,
apply subset_union_right
end
/-- If `t` is an indexed family of sets, then there is a natural map from `Σ i, t i` to `⋃ i, t i`
sending `⟨i, x⟩` to `x`. -/
def sigma_to_Union (x : Σ i, t i) : (⋃ i, t i) := ⟨x.2, mem_Union.2 ⟨x.1, x.2.2⟩⟩
lemma sigma_to_Union_surjective : surjective (sigma_to_Union t)
| ⟨b, hb⟩ := have ∃ a, b ∈ t a, by simpa using hb, let ⟨a, hb⟩ := this in ⟨⟨a, b, hb⟩, rfl⟩
lemma sigma_to_Union_injective (h : ∀ i j, i ≠ j → disjoint (t i) (t j)) :
injective (sigma_to_Union t)
| ⟨a₁, b₁, h₁⟩ ⟨a₂, b₂, h₂⟩ eq :=
have b_eq : b₁ = b₂, from congr_arg subtype.val eq,
have a_eq : a₁ = a₂, from classical.by_contradiction $ λ ne,
have b₁ ∈ t a₁ ∩ t a₂, from ⟨h₁, b_eq.symm ▸ h₂⟩,
h _ _ ne this,
sigma.eq a_eq $ subtype.eq $ by subst b_eq; subst a_eq
lemma sigma_to_Union_bijective (h : ∀ i j, i ≠ j → disjoint (t i) (t j)) :
bijective (sigma_to_Union t) :=
⟨sigma_to_Union_injective t h, sigma_to_Union_surjective t⟩
/-- Equivalence between a disjoint union and a dependent sum. -/
noncomputable def Union_eq_sigma_of_disjoint {t : α → set β}
(h : ∀ i j, i ≠ j → disjoint (t i) (t j)) : (⋃ i, t i) ≃ (Σ i, t i) :=
(equiv.of_bijective _ $ sigma_to_Union_bijective t h).symm
end set
open set
variables [complete_lattice β]
lemma supr_Union (s : ι → set α) (f : α → β) : (⨆ a ∈ (⋃ i, s i), f a) = ⨆ i (a ∈ s i), f a :=
by { rw supr_comm, simp_rw [mem_Union, supr_exists] }
lemma infi_Union (s : ι → set α) (f : α → β) : (⨅ a ∈ (⋃ i, s i), f a) = ⨅ i (a ∈ s i), f a :=
by { rw infi_comm, simp_rw [mem_Union, infi_exists] }
|
7dd3f15a3f242788be6d2edcacad7fdb7949ebe3
|
7b9ff28673cd3dd7dd3dcfe2ab8449f9244fe05a
|
/src/seul/exercise.lean
|
8f1317921e6261de011145dd8de22a5a0eea2da0
|
[] |
no_license
|
jesse-michael-han/hanoi-lean-2019
|
ea2f0e04f81093373c48447065765a964ee82262
|
a5a9f368e394d563bfcc13e3773863924505b1ce
|
refs/heads/master
| 1,591,320,223,247
| 1,561,022,886,000
| 1,561,022,886,000
| 192,264,820
| 1
| 1
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 3,743
|
lean
|
open expr tactic classical
variables {p q r s : Prop}
variables {a b c d e : Prop}
section
local attribute [instance] classical.prop_decidable
theorem not_or_of_imp (h : a → b) : ¬ a ∨ b :=
begin
by_cases H : a,
from or.inr (h ‹_›),
from or.inl ‹_›
end
theorem imp_iff_not_or : (a → b) ↔ (¬ a ∨ b) := sorry
theorem iff_def : (a ↔ b) ↔ (a → b) ∧ (b → a) := sorry
theorem not_not : ¬¬a ↔ a := sorry
theorem not_or_distrib : ¬ (a ∨ b) ↔ ¬ a ∧ ¬ b := sorry
theorem not_and_of_not_or_not (h : ¬ a ∨ ¬ b) : ¬ (a ∧ b) := sorry
theorem not_and_distrib : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := sorry
end
meta def normalize : tactic unit :=
`[ try { simp only
[ not_or_distrib,
not_and_distrib,
not_not,
imp_iff_not_or,
not_true_iff,
not_false_iff,
iff_def ] at *} ]
/- Given a list of expr of hypotheses, find an expr of a
conjunctive hypothesis in the list and return it. -/
meta def find_conj : list expr → tactic expr := sorry
/- Given a list of expr of hypotheses, find an expr of a
disjunctive hypothesis in the list and return it. -/
meta def find_disj : list expr → tactic expr := sorry
/- Find and split a conjunction. -/
meta def split_conj : tactic unit := sorry
/- Split all conjunctions using split_conj. -/
meta def split_conjs : tactic unit := sorry
/- Find and split a disjunction. -/
meta def split_disj : tactic unit := sorry
/- Given a goal of the form Γ ⊢ φ, reduce it to the goal Γ, ¬φ ⊢ ⊥ -/
meta def go_by_contradiction : tactic unit := sorry
/- The main proof search loop. First, split all conjunctions.
If the result has complementary literals, discharge the goal.
If not, find a disjunction, split it, and discharge the new
subgoals by entering the proof search loop again. -/
meta def tab_aux : tactic unit := sorry
/- Normalize goal and enter proof search loop. -/
meta def tab : tactic unit := sorry
#exit
example : a ∧ b → b ∧ a := by tab
example : a ∧ (a → b) → b := by tab
-- commutativity of ∧ and ∨
example : p ∧ q ↔ q ∧ p := by tab
example : p ∨ q ↔ q ∨ p := by tab
-- associativity of ∧ and ∨
example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := by tab
example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := by tab
-- distributivity
example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := by tab
example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := by tab
-- other properties
example : (p → (q → r)) ↔ (p ∧ q → r) := by tab
example : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) := by tab
example : ¬(p ∨ q) ↔ ¬p ∧ ¬q := by tab
example : ¬p ∨ ¬q → ¬(p ∧ q) := by tab
example : ¬(p ∧ ¬p) := by tab
example : p ∧ ¬q → ¬(p → q) := by tab
example : ¬p → (p → q) := by tab
example : (¬p ∨ q) → (p → q) := by tab
example : p ∨ false ↔ p := by tab
example : p ∧ false ↔ false := by tab
example : ¬(p ↔ ¬p) := by tab
example : (p → q) → (¬q → ¬p) := by tab
example : (p → r ∨ s) → ((p → r) ∨ (p → s)) := by tab
example : ¬(p ∧ q) → ¬p ∨ ¬q := by tab
example : ¬(p → q) → p ∧ ¬q := by tab
example : (p → q) → (¬p ∨ q) := by tab
example : (¬q → ¬p) → (p → q) := by tab
example : p ∨ ¬p := by tab
example : (((p → q) → p) → p) := by tab
example (h₁ : a ∧ b) (h₂ : b ∧ ¬ c) : a ∨ c :=
by tab
example (h₁ : a ∧ b) (h₂ : b ∧ ¬ c) : a ∧ ¬ c :=
by tab
example : ((a → b) → a) → a :=
by tab
example : (a → b) ∧ (b → c) → a → c :=
by tab
example (α : Type) (x y z w : α) :
x = y ∧ (x = y → z = w) → z = w :=
by tab
example : ¬ (a ↔ ¬ a) :=
by tab
|
900309928e3c80a2be6d9ca921a39c9b8a44ed3f
|
fa02ed5a3c9c0adee3c26887a16855e7841c668b
|
/src/algebra/lie/character.lean
|
170178ca0b8fe800561c245c92cc3ef8af4a9c53
|
[
"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
| 2,271
|
lean
|
/-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.abelian
import algebra.lie.solvable
import linear_algebra.dual
/-!
# Characters of Lie algebras
A character of a Lie algebra `L` over a commutative ring `R` is a morphism of Lie algebras `L → R`,
where `R` is regarded as a Lie algebra over itself via the ring commutator. For an Abelian Lie
algebra (e.g., a Cartan subalgebra of a semisimple Lie algebra) a character is just a linear form.
## Main definitions
* `lie_algebra.lie_character`
* `lie_algebra.lie_character_equiv_linear_dual`
## Tags
lie algebra, lie character
-/
universes u v w w₁
namespace lie_algebra
variables (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L]
/-- A character of a Lie algebra is a morphism to the scalars. -/
abbreviation lie_character := L →ₗ⁅R⁆ R
variables {R L}
@[simp] lemma lie_character_apply_lie (χ : lie_character R L) (x y : L) : χ ⁅x, y⁆ = 0 :=
by rw [lie_hom.map_lie, lie_ring.of_associative_ring_bracket, mul_comm, sub_self]
lemma lie_character_apply_of_mem_derived
(χ : lie_character R L) {x : L} (h : x ∈ derived_series R L 1) : χ x = 0 :=
begin
rw [derived_series_def, derived_series_of_ideal_succ, derived_series_of_ideal_zero,
← lie_submodule.mem_coe_submodule, lie_submodule.lie_ideal_oper_eq_linear_span] at h,
apply submodule.span_induction h,
{ rintros y ⟨⟨z, hz⟩, ⟨⟨w, hw⟩, rfl⟩⟩, apply lie_character_apply_lie, },
{ exact χ.map_zero, },
{ intros y z hy hz, rw [lie_hom.map_add, hy, hz, add_zero], },
{ intros t y hy, rw [lie_hom.map_smul, hy, smul_zero], },
end
/-- For an Abelian Lie algebra, characters are just linear forms. -/
@[simps] def lie_character_equiv_linear_dual [is_lie_abelian L] :
lie_character R L ≃ module.dual R L :=
{ to_fun := λ χ, (χ : L →ₗ[R] R),
inv_fun := λ ψ,
{ map_lie' := λ x y, by
rw [lie_module.is_trivial.trivial, lie_ring.of_associative_ring_bracket, mul_comm, sub_self,
linear_map.to_fun_eq_coe, linear_map.map_zero],
.. ψ, },
left_inv := λ χ, by { ext, refl, },
right_inv := λ ψ, by { ext, refl, }, }
end lie_algebra
|
9da5c79a6f6421bd3457a97861d8f3d4bcfb59b3
|
57c233acf9386e610d99ed20ef139c5f97504ba3
|
/src/data/set/basic.lean
|
f5165b7c34ab87e387cf8971c53fd06d33bc6a93
|
[
"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
| 98,828
|
lean
|
/-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
-/
import order.boolean_algebra
/-!
# Basic properties of sets
Sets in Lean are homogeneous; all their elements have the same type. Sets whose elements
have type `X` are thus defined as `set X := X → Prop`. Note that this function need not
be decidable. The definition is in the core library.
This file provides some basic definitions related to sets and functions not present in the core
library, as well as extra lemmas for functions in the core library (empty set, univ, union,
intersection, insert, singleton, set-theoretic difference, complement, and powerset).
Note that a set is a term, not a type. There is a coercion from `set α` to `Type*` sending
`s` to the corresponding subtype `↥s`.
See also the file `set_theory/zfc.lean`, which contains an encoding of ZFC set theory in Lean.
## Main definitions
Notation used here:
- `f : α → β` is a function,
- `s : set α` and `s₁ s₂ : set α` are subsets of `α`
- `t : set β` is a subset of `β`.
Definitions in the file:
* `nonempty s : Prop` : the predicate `s ≠ ∅`. Note that this is the preferred way to express the
fact that `s` has an element (see the Implementation Notes).
* `preimage f t : set α` : the preimage f⁻¹(t) (written `f ⁻¹' t` in Lean) of a subset of β.
* `subsingleton s : Prop` : the predicate saying that `s` has at most one element.
* `range f : set β` : the image of `univ` under `f`.
Also works for `{p : Prop} (f : p → α)` (unlike `image`)
* `inclusion s₁ s₂ : ↥s₁ → ↥s₂` : the map `↥s₁ → ↥s₂` induced by an inclusion `s₁ ⊆ s₂`.
## Notation
* `f ⁻¹' t` for `preimage f t`
* `f '' s` for `image f s`
* `sᶜ` for the complement of `s`
## Implementation notes
* `s.nonempty` is to be preferred to `s ≠ ∅` or `∃ x, x ∈ s`. It has the advantage that
the `s.nonempty` dot notation can be used.
* For `s : set α`, do not use `subtype s`. Instead use `↥s` or `(s : Type*)` or `s`.
## Tags
set, sets, subset, subsets, image, preimage, pre-image, range, union, intersection, insert,
singleton, complement, powerset
-/
/-! ### Set coercion to a type -/
open function
universes u v w x
run_cmd do e ← tactic.get_env,
tactic.set_env $ e.mk_protected `set.compl
namespace set
variable {α : Type*}
instance : has_le (set α) := ⟨(⊆)⟩
instance : has_lt (set α) := ⟨λ s t, s ≤ t ∧ ¬t ≤ s⟩ -- `⊂` is not defined until further down
instance {α : Type*} : boolean_algebra (set α) :=
{ sup := (∪),
le := (≤),
lt := (<),
inf := (∩),
bot := ∅,
compl := set.compl,
top := univ,
sdiff := (\),
.. (infer_instance : boolean_algebra (α → Prop)) }
@[simp] lemma top_eq_univ : (⊤ : set α) = univ := rfl
@[simp] lemma bot_eq_empty : (⊥ : set α) = ∅ := rfl
@[simp] lemma sup_eq_union : ((⊔) : set α → set α → set α) = (∪) := rfl
@[simp] lemma inf_eq_inter : ((⊓) : set α → set α → set α) = (∩) := rfl
@[simp] lemma le_eq_subset : ((≤) : set α → set α → Prop) = (⊆) := rfl
/-! `set.lt_eq_ssubset` is defined further down -/
@[simp] lemma compl_eq_compl : set.compl = (has_compl.compl : set α → set α) := rfl
/-- Coercion from a set to the corresponding subtype. -/
instance {α : Type u} : has_coe_to_sort (set α) (Type u) := ⟨λ s, {x // x ∈ s}⟩
instance pi_set_coe.can_lift (ι : Type u) (α : Π i : ι, Type v) [ne : Π i, nonempty (α i)]
(s : set ι) :
can_lift (Π i : s, α i) (Π i, α i) :=
{ coe := λ f i, f i,
.. pi_subtype.can_lift ι α s }
instance pi_set_coe.can_lift' (ι : Type u) (α : Type v) [ne : nonempty α] (s : set ι) :
can_lift (s → α) (ι → α) :=
pi_set_coe.can_lift ι (λ _, α) s
instance set_coe.can_lift (s : set α) : can_lift α s :=
{ coe := coe,
cond := λ a, a ∈ s,
prf := λ a ha, ⟨⟨a, ha⟩, rfl⟩ }
end set
section set_coe
variables {α : Type u}
theorem set.set_coe_eq_subtype (s : set α) :
coe_sort.{(u+1) (u+2)} s = {x // x ∈ s} := rfl
@[simp] theorem set_coe.forall {s : set α} {p : s → Prop} :
(∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) :=
subtype.forall
@[simp] theorem set_coe.exists {s : set α} {p : s → Prop} :
(∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) :=
subtype.exists
theorem set_coe.exists' {s : set α} {p : Π x, x ∈ s → Prop} :
(∃ x (h : x ∈ s), p x h) ↔ (∃ x : s, p x x.2) :=
(@set_coe.exists _ _ $ λ x, p x.1 x.2).symm
theorem set_coe.forall' {s : set α} {p : Π x, x ∈ s → Prop} :
(∀ x (h : x ∈ s), p x h) ↔ (∀ x : s, p x x.2) :=
(@set_coe.forall _ _ $ λ x, p x.1 x.2).symm
@[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : @eq (Type u) s t) (x : s),
cast H x = ⟨x.1, H' ▸ x.2⟩
| s _ rfl _ ⟨x, h⟩ := rfl
theorem set_coe.ext {s : set α} {a b : s} : (↑a : α) = ↑b → a = b :=
subtype.eq
theorem set_coe.ext_iff {s : set α} {a b : s} : (↑a : α) = ↑b ↔ a = b :=
iff.intro set_coe.ext (assume h, h ▸ rfl)
end set_coe
/-- See also `subtype.prop` -/
lemma subtype.mem {α : Type*} {s : set α} (p : s) : (p : α) ∈ s := p.prop
/-- Duplicate of `eq.subset'`, which currently has elaboration problems. -/
lemma eq.subset {α} {s t : set α} : s = t → s ⊆ t :=
by { rintro rfl x hx, exact hx }
namespace set
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a : α} {s t : set α}
instance : inhabited (set α) := ⟨∅⟩
@[ext]
theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b :=
funext (assume x, propext (h x))
theorem ext_iff {s t : set α} : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t :=
⟨λ h x, by rw h, ext⟩
@[trans] theorem mem_of_mem_of_subset {x : α} {s t : set α}
(hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx
/-! ### Lemmas about `mem` and `set_of` -/
@[simp] theorem mem_set_of_eq {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl
theorem nmem_set_of_eq {a : α} {P : α → Prop} : a ∉ {a : α | P a} = ¬ P a := rfl
@[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl
theorem set_of_set {s : set α} : set_of s = s := rfl
lemma set_of_app_iff {p : α → Prop} {x : α} : { x | p x } x ↔ p x := iff.rfl
theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl
lemma set_of_bijective : bijective (set_of : (α → Prop) → set α) := bijective_id
@[simp] theorem set_of_subset_set_of {p q : α → Prop} :
{a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl
@[simp] lemma sep_set_of {p q : α → Prop} : {a ∈ {a | p a } | q a} = {a | p a ∧ q a} := rfl
lemma set_of_and {p q : α → Prop} : {a | p a ∧ q a} = {a | p a} ∩ {a | q a} := rfl
lemma set_of_or {p q : α → Prop} : {a | p a ∨ q a} = {a | p a} ∪ {a | q a} := rfl
/-! ### Subset and strict subset relations -/
instance : has_ssubset (set α) := ⟨(<)⟩
instance : is_refl (set α) (⊆) := has_le.le.is_refl
instance : is_trans (set α) (⊆) := has_le.le.is_trans
instance : is_antisymm (set α) (⊆) := has_le.le.is_antisymm
instance : is_irrefl (set α) (⊂) := has_lt.lt.is_irrefl
instance : is_trans (set α) (⊂) := has_lt.lt.is_trans
instance : is_asymm (set α) (⊂) := has_lt.lt.is_asymm
instance : is_nonstrict_strict_order (set α) (⊆) (⊂) := ⟨λ _ _, iff.rfl⟩
-- TODO(Jeremy): write a tactic to unfold specific instances of generic notation?
lemma subset_def : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl
lemma ssubset_def : s ⊂ t = (s ⊆ t ∧ ¬ t ⊆ s) := rfl
@[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id
theorem subset.rfl {s : set α} : s ⊆ s := subset.refl s
@[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c :=
assume x h, bc (ab h)
@[trans] theorem mem_of_eq_of_mem {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s :=
hx.symm ▸ h
theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b :=
set.ext $ λ x, ⟨@h₁ _, @h₂ _⟩
theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a :=
⟨λ e, ⟨e.subset, e.symm.subset⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩
-- an alternative name
theorem eq_of_subset_of_subset {a b : set α} : a ⊆ b → b ⊆ a → a = b := subset.antisymm
theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} (h : s₁ ⊆ s₂) : a ∈ s₁ → a ∈ s₂ := @h _
theorem not_mem_subset (h : s ⊆ t) : a ∉ t → a ∉ s :=
mt $ mem_of_subset_of_mem h
theorem not_subset : (¬ s ⊆ t) ↔ ∃a ∈ s, a ∉ t := by simp only [subset_def, not_forall]
theorem nontrivial_mono {α : Type*} {s t : set α} (h₁ : s ⊆ t) (h₂ : nontrivial s) :
nontrivial t :=
begin
rw nontrivial_iff at h₂ ⊢,
obtain ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h₂,
exact ⟨⟨x, h₁ hx⟩, ⟨y, h₁ hy⟩, by simpa using hxy⟩,
end
/-! ### Definition of strict subsets `s ⊂ t` and basic properties. -/
@[simp] lemma lt_eq_ssubset : ((<) : set α → set α → Prop) = (⊂) := rfl
protected theorem eq_or_ssubset_of_subset (h : s ⊆ t) : s = t ∨ s ⊂ t :=
eq_or_lt_of_le h
lemma exists_of_ssubset {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) :=
not_subset.1 h.2
protected lemma ssubset_iff_subset_ne {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t :=
@lt_iff_le_and_ne (set α) _ s t
lemma ssubset_iff_of_subset {s t : set α} (h : s ⊆ t) : s ⊂ t ↔ ∃ x ∈ t, x ∉ s :=
⟨exists_of_ssubset, λ ⟨x, hxt, hxs⟩, ⟨h, λ h, hxs $ h hxt⟩⟩
protected lemma ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : set α} (hs₁s₂ : s₁ ⊂ s₂)
(hs₂s₃ : s₂ ⊆ s₃) :
s₁ ⊂ s₃ :=
⟨subset.trans hs₁s₂.1 hs₂s₃, λ hs₃s₁, hs₁s₂.2 (subset.trans hs₂s₃ hs₃s₁)⟩
protected lemma ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : set α} (hs₁s₂ : s₁ ⊆ s₂)
(hs₂s₃ : s₂ ⊂ s₃) :
s₁ ⊂ s₃ :=
⟨subset.trans hs₁s₂ hs₂s₃.1, λ hs₃s₁, hs₂s₃.2 (subset.trans hs₃s₁ hs₁s₂)⟩
theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := id
@[simp] theorem not_not_mem : ¬ (a ∉ s) ↔ a ∈ s := not_not
/-! ### Non-empty sets -/
/-- The property `s.nonempty` expresses the fact that the set `s` is not empty. It should be used
in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks
to the dot notation. -/
protected def nonempty (s : set α) : Prop := ∃ x, x ∈ s
@[simp] lemma nonempty_coe_sort (s : set α) : nonempty ↥s ↔ s.nonempty := nonempty_subtype
lemma nonempty_def : s.nonempty ↔ ∃ x, x ∈ s := iff.rfl
lemma nonempty_of_mem {x} (h : x ∈ s) : s.nonempty := ⟨x, h⟩
theorem nonempty.not_subset_empty : s.nonempty → ¬(s ⊆ ∅)
| ⟨x, hx⟩ hs := hs hx
theorem nonempty.ne_empty : ∀ {s : set α}, s.nonempty → s ≠ ∅
| _ ⟨x, hx⟩ rfl := hx
@[simp] theorem not_nonempty_empty : ¬(∅ : set α).nonempty :=
λ h, h.ne_empty rfl
/-- Extract a witness from `s.nonempty`. This function might be used instead of case analysis
on the argument. Note that it makes a proof depend on the `classical.choice` axiom. -/
protected noncomputable def nonempty.some (h : s.nonempty) : α := classical.some h
protected lemma nonempty.some_mem (h : s.nonempty) : h.some ∈ s := classical.some_spec h
lemma nonempty.mono (ht : s ⊆ t) (hs : s.nonempty) : t.nonempty := hs.imp ht
lemma nonempty_of_not_subset (h : ¬s ⊆ t) : (s \ t).nonempty :=
let ⟨x, xs, xt⟩ := not_subset.1 h in ⟨x, xs, xt⟩
lemma nonempty_of_ssubset (ht : s ⊂ t) : (t \ s).nonempty :=
nonempty_of_not_subset ht.2
lemma nonempty.of_diff (h : (s \ t).nonempty) : s.nonempty := h.imp $ λ _, and.left
lemma nonempty_of_ssubset' (ht : s ⊂ t) : t.nonempty := (nonempty_of_ssubset ht).of_diff
lemma nonempty.inl (hs : s.nonempty) : (s ∪ t).nonempty := hs.imp $ λ _, or.inl
lemma nonempty.inr (ht : t.nonempty) : (s ∪ t).nonempty := ht.imp $ λ _, or.inr
@[simp] lemma union_nonempty : (s ∪ t).nonempty ↔ s.nonempty ∨ t.nonempty := exists_or_distrib
lemma nonempty.left (h : (s ∩ t).nonempty) : s.nonempty := h.imp $ λ _, and.left
lemma nonempty.right (h : (s ∩ t).nonempty) : t.nonempty := h.imp $ λ _, and.right
lemma nonempty_inter_iff_exists_right : (s ∩ t).nonempty ↔ ∃ x : t, ↑x ∈ s :=
⟨λ ⟨x, xs, xt⟩, ⟨⟨x, xt⟩, xs⟩, λ ⟨⟨x, xt⟩, xs⟩, ⟨x, xs, xt⟩⟩
lemma nonempty_inter_iff_exists_left : (s ∩ t).nonempty ↔ ∃ x : s, ↑x ∈ t :=
⟨λ ⟨x, xs, xt⟩, ⟨⟨x, xs⟩, xt⟩, λ ⟨⟨x, xt⟩, xs⟩, ⟨x, xt, xs⟩⟩
lemma nonempty_iff_univ_nonempty : nonempty α ↔ (univ : set α).nonempty :=
⟨λ ⟨x⟩, ⟨x, trivial⟩, λ ⟨x, _⟩, ⟨x⟩⟩
@[simp] lemma univ_nonempty : ∀ [h : nonempty α], (univ : set α).nonempty
| ⟨x⟩ := ⟨x, trivial⟩
lemma nonempty.to_subtype (h : s.nonempty) : nonempty s :=
nonempty_subtype.2 h
instance [nonempty α] : nonempty (set.univ : set α) := set.univ_nonempty.to_subtype
@[simp] lemma nonempty_insert (a : α) (s : set α) : (insert a s).nonempty := ⟨a, or.inl rfl⟩
lemma nonempty_of_nonempty_subtype [nonempty s] : s.nonempty :=
nonempty_subtype.mp ‹_›
/-! ### Lemmas about the empty set -/
theorem empty_def : (∅ : set α) = {x | false} := rfl
@[simp] theorem mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl
@[simp] theorem set_of_false : {a : α | false} = ∅ := rfl
@[simp] theorem empty_subset (s : set α) : ∅ ⊆ s.
theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ :=
(subset.antisymm_iff.trans $ and_iff_left (empty_subset _)).symm
theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := subset_empty_iff.symm
theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1
theorem eq_empty_of_is_empty [is_empty α] (s : set α) : s = ∅ :=
eq_empty_of_subset_empty $ λ x hx, is_empty_elim x
/-- There is exactly one set of a type that is empty. -/
-- TODO[gh-6025]: make this an instance once safe to do so
def unique_empty [is_empty α] : unique (set α) :=
{ default := ∅, uniq := eq_empty_of_is_empty }
lemma not_nonempty_iff_eq_empty {s : set α} : ¬s.nonempty ↔ s = ∅ :=
by simp only [set.nonempty, eq_empty_iff_forall_not_mem, not_exists]
lemma empty_not_nonempty : ¬(∅ : set α).nonempty := λ h, h.ne_empty rfl
theorem ne_empty_iff_nonempty : s ≠ ∅ ↔ s.nonempty := not_iff_comm.1 not_nonempty_iff_eq_empty
lemma eq_empty_or_nonempty (s : set α) : s = ∅ ∨ s.nonempty :=
or_iff_not_imp_left.2 ne_empty_iff_nonempty.1
theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ :=
subset_empty_iff.1 $ e ▸ h
theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : set α), p x) ↔ true :=
iff_true_intro $ λ x, false.elim
instance (α : Type u) : is_empty.{u+1} (∅ : set α) :=
⟨λ x, x.2⟩
@[simp] lemma empty_ssubset : ∅ ⊂ s ↔ s.nonempty :=
(@bot_lt_iff_ne_bot (set α) _ _ _).trans ne_empty_iff_nonempty
/-!
### Universal set.
In Lean `@univ α` (or `univ : set α`) is the set that contains all elements of type `α`.
Mathematically it is the same as `α` but it has a different type.
-/
@[simp] theorem set_of_true : {x : α | true} = univ := rfl
@[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial
@[simp] lemma univ_eq_empty_iff : (univ : set α) = ∅ ↔ is_empty α :=
eq_empty_iff_forall_not_mem.trans ⟨λ H, ⟨λ x, H x trivial⟩, λ H x _, @is_empty.false α H x⟩
theorem empty_ne_univ [nonempty α] : (∅ : set α) ≠ univ :=
λ e, not_is_empty_of_nonempty α $ univ_eq_empty_iff.1 e.symm
@[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial
theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ :=
(subset.antisymm_iff.trans $ and_iff_right (subset_univ _)).symm
theorem eq_univ_of_univ_subset {s : set α} : univ ⊆ s → s = univ := univ_subset_iff.1
theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s :=
univ_subset_iff.symm.trans $ forall_congr $ λ x, imp_iff_right ⟨⟩
theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2
lemma eq_univ_of_subset {s t : set α} (h : s ⊆ t) (hs : s = univ) : t = univ :=
eq_univ_of_univ_subset $ hs ▸ h
lemma exists_mem_of_nonempty (α) : ∀ [nonempty α], ∃x:α, x ∈ (univ : set α)
| ⟨x⟩ := ⟨x, trivial⟩
lemma ne_univ_iff_exists_not_mem {α : Type*} (s : set α) : s ≠ univ ↔ ∃ a, a ∉ s :=
by rw [←not_forall, ←eq_univ_iff_forall]
lemma not_subset_iff_exists_mem_not_mem {α : Type*} {s t : set α} :
¬ s ⊆ t ↔ ∃ x, x ∈ s ∧ x ∉ t :=
by simp [subset_def]
lemma univ_unique [unique α] : @set.univ α = {default} :=
set.ext $ λ x, iff_of_true trivial $ subsingleton.elim x default
/-! ### Lemmas about union -/
theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl
theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl
theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr
theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H
theorem mem_union.elim {x : α} {a b : set α} {P : Prop}
(H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P :=
or.elim H₁ H₂ H₃
theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := iff.rfl
@[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl
@[simp] theorem union_self (a : set α) : a ∪ a = a := ext $ λ x, or_self _
@[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext $ λ x, or_false _
@[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext $ λ x, false_or _
theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext $ λ x, or.comm
theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext $ λ x, or.assoc
instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩
instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩
theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) :=
ext $ λ x, or.left_comm
theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ :=
ext $ λ x, or.right_comm
@[simp] theorem union_eq_left_iff_subset {s t : set α} : s ∪ t = s ↔ t ⊆ s :=
sup_eq_left
@[simp] theorem union_eq_right_iff_subset {s t : set α} : s ∪ t = t ↔ s ⊆ t :=
sup_eq_right
theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t :=
union_eq_right_iff_subset.mpr h
theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s :=
union_eq_left_iff_subset.mpr h
@[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl
@[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr
theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r :=
λ x, or.rec (@sr _) (@tr _)
@[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u :=
(forall_congr (by exact λ x, or_imp_distrib)).trans forall_and_distrib
theorem union_subset_union {s₁ s₂ t₁ t₂ : set α}
(h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := λ x, or.imp (@h₁ _) (@h₂ _)
theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t :=
union_subset_union h subset.rfl
theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ :=
union_subset_union subset.rfl h
lemma subset_union_of_subset_left {s t : set α} (h : s ⊆ t) (u : set α) : s ⊆ t ∪ u :=
subset.trans h (subset_union_left t u)
lemma subset_union_of_subset_right {s u : set α} (h : s ⊆ u) (t : set α) : s ⊆ t ∪ u :=
subset.trans h (subset_union_right t u)
@[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ :=
by simp only [← subset_empty_iff]; exact union_subset_iff
@[simp] lemma union_univ {s : set α} : s ∪ univ = univ := sup_top_eq
@[simp] lemma univ_union {s : set α} : univ ∪ s = univ := top_sup_eq
/-! ### Lemmas about intersection -/
theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl
theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl
@[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl
theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩
theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a := h.left
theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b := h.right
@[simp] theorem inter_self (a : set α) : a ∩ a = a := ext $ λ x, and_self _
@[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext $ λ x, and_false _
@[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext $ λ x, false_and _
theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext $ λ x, and.comm
theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext $ λ x, and.assoc
instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩
instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩
theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) :=
ext $ λ x, and.left_comm
theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ :=
ext $ λ x, and.right_comm
@[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x, and.left
@[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x, and.right
theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := λ x h, ⟨rs h, rt h⟩
@[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t :=
(forall_congr (by exact λ x, imp_and_distrib)).trans forall_and_distrib
@[simp] theorem inter_eq_left_iff_subset {s t : set α} : s ∩ t = s ↔ s ⊆ t :=
inf_eq_left
@[simp] theorem inter_eq_right_iff_subset {s t : set α} : s ∩ t = t ↔ t ⊆ s :=
inf_eq_right
theorem inter_eq_self_of_subset_left {s t : set α} : s ⊆ t → s ∩ t = s :=
inter_eq_left_iff_subset.mpr
theorem inter_eq_self_of_subset_right {s t : set α} : t ⊆ s → s ∩ t = t :=
inter_eq_right_iff_subset.mpr
@[simp] theorem inter_univ (a : set α) : a ∩ univ = a := inf_top_eq
@[simp] theorem univ_inter (a : set α) : univ ∩ a = a := top_inf_eq
theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α}
(h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := λ x, and.imp (@h₁ _) (@h₂ _)
theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u :=
inter_subset_inter H subset.rfl
theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t :=
inter_subset_inter subset.rfl H
theorem union_inter_cancel_left {s t : set α} : (s ∪ t) ∩ s = s :=
inter_eq_self_of_subset_right $ subset_union_left _ _
theorem union_inter_cancel_right {s t : set α} : (s ∪ t) ∩ t = t :=
inter_eq_self_of_subset_right $ subset_union_right _ _
/-! ### Distributivity laws -/
theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) :=
inf_sup_left
theorem inter_union_distrib_left {s t u : set α} : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) :=
inf_sup_left
theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) :=
inf_sup_right
theorem union_inter_distrib_right {s t u : set α} : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) :=
inf_sup_right
theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) :=
sup_inf_left
theorem union_inter_distrib_left {s t u : set α} : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) :=
sup_inf_left
theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) :=
sup_inf_right
theorem inter_union_distrib_right {s t u : set α} : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) :=
sup_inf_right
/-!
### Lemmas about `insert`
`insert α s` is the set `{α} ∪ s`.
-/
theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl
@[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := λ y, or.inr
theorem mem_insert (x : α) (s : set α) : x ∈ insert x s := or.inl rfl
theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr
theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id
theorem mem_of_mem_insert_of_ne {x a : α} {s : set α} : x ∈ insert a s → x ≠ a → x ∈ s :=
or.resolve_left
@[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ x = a ∨ x ∈ s := iff.rfl
@[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s :=
ext $ λ x, or_iff_right_of_imp $ λ e, e.symm ▸ h
lemma ne_insert_of_not_mem {s : set α} (t : set α) {a : α} : a ∉ s → s ≠ insert a t :=
mt $ λ e, e.symm ▸ mem_insert _ _
theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) :=
by simp only [subset_def, or_imp_distrib, forall_and_distrib, forall_eq, mem_insert_iff]
theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := λ x, or.imp_right (@h _)
theorem insert_subset_insert_iff (ha : a ∉ s) : insert a s ⊆ insert a t ↔ s ⊆ t :=
begin
refine ⟨λ h x hx, _, insert_subset_insert⟩,
rcases h (subset_insert _ _ hx) with (rfl|hxt),
exacts [(ha hx).elim, hxt]
end
theorem ssubset_iff_insert {s t : set α} : s ⊂ t ↔ ∃ a ∉ s, insert a s ⊆ t :=
begin
simp only [insert_subset, exists_and_distrib_right, ssubset_def, not_subset],
simp only [exists_prop, and_comm]
end
theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s :=
ssubset_iff_insert.2 ⟨a, h, subset.rfl⟩
theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) :=
ext $ λ x, or.left_comm
theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := ext $ λ x, or.assoc
@[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := ext $ λ x, or.left_comm
theorem insert_nonempty (a : α) (s : set α) : (insert a s).nonempty := ⟨a, mem_insert a s⟩
instance (a : α) (s : set α) : nonempty (insert a s : set α) := (insert_nonempty a s).to_subtype
lemma insert_inter (x : α) (s t : set α) : insert x (s ∩ t) = insert x s ∩ insert x t :=
ext $ λ y, or_and_distrib_left
-- useful in proofs by induction
theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α}
(H : ∀ x, x ∈ insert a s → P x) (x) (h : x ∈ s) : P x := H _ (or.inr h)
theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α}
(H : ∀ x, x ∈ s → P x) (ha : P a) (x) (h : x ∈ insert a s) : P x :=
h.elim (λ e, e.symm ▸ ha) (H _)
theorem bex_insert_iff {P : α → Prop} {a : α} {s : set α} :
(∃ x ∈ insert a s, P x) ↔ P a ∨ (∃ x ∈ s, P x) :=
bex_or_left_distrib.trans $ or_congr_left bex_eq_left
theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} :
(∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) :=
ball_or_left_distrib.trans $ and_congr_left' forall_eq
/-! ### Lemmas about singletons -/
theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := (insert_emptyc_eq _).symm
@[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b := iff.rfl
@[simp] lemma set_of_eq_eq_singleton {a : α} : {n | n = a} = {a} := rfl
@[simp] lemma set_of_eq_eq_singleton' {a : α} : {x | a = x} = {a} := ext $ λ x, eq_comm
-- TODO: again, annotation needed
@[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := @rfl _ _
theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := h
@[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y :=
ext_iff.trans eq_iff_eq_cancel_left
lemma singleton_injective : injective (singleton : α → set α) :=
λ _ _, singleton_eq_singleton_iff.mp
theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := H
theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := rfl
@[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := union_self _
theorem pair_comm (a b : α) : ({a, b} : set α) = {b, a} := union_comm _ _
@[simp] theorem singleton_nonempty (a : α) : ({a} : set α).nonempty :=
⟨a, rfl⟩
@[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := forall_eq
theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := rfl
@[simp] theorem singleton_union : {a} ∪ s = insert a s := rfl
@[simp] theorem union_singleton : s ∪ {a} = insert a s := union_comm _ _
@[simp] theorem singleton_inter_nonempty : ({a} ∩ s).nonempty ↔ a ∈ s :=
by simp only [set.nonempty, mem_inter_eq, mem_singleton_iff, exists_eq_left]
@[simp] theorem inter_singleton_nonempty : (s ∩ {a}).nonempty ↔ a ∈ s :=
by rw [inter_comm, singleton_inter_nonempty]
@[simp] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s :=
not_nonempty_iff_eq_empty.symm.trans singleton_inter_nonempty.not
@[simp] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s :=
by rw [inter_comm, singleton_inter_eq_empty]
lemma nmem_singleton_empty {s : set α} : s ∉ ({∅} : set (set α)) ↔ s.nonempty :=
ne_empty_iff_nonempty
instance unique_singleton (a : α) : unique ↥({a} : set α) :=
⟨⟨⟨a, mem_singleton a⟩⟩, λ ⟨x, h⟩, subtype.eq h⟩
lemma eq_singleton_iff_unique_mem : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a :=
subset.antisymm_iff.trans $ and.comm.trans $ and_congr_left' singleton_subset_iff
lemma eq_singleton_iff_nonempty_unique_mem : s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a :=
eq_singleton_iff_unique_mem.trans $ and_congr_left $ λ H, ⟨λ h', ⟨_, h'⟩, λ ⟨x, h⟩, H x h ▸ h⟩
lemma exists_eq_singleton_iff_nonempty_unique_mem :
(∃ a : α, s = {a}) ↔ (s.nonempty ∧ ∀ a b ∈ s, a = b) :=
begin
refine ⟨_, λ h, _⟩,
{ rintros ⟨a, rfl⟩,
refine ⟨set.singleton_nonempty a, λ b hb c hc, hb.trans hc.symm⟩ },
{ obtain ⟨a, ha⟩ := h.1,
refine ⟨a, set.eq_singleton_iff_unique_mem.mpr ⟨ha, λ b hb, (h.2 b hb a ha)⟩⟩ },
end
-- while `simp` is capable of proving this, it is not capable of turning the LHS into the RHS.
@[simp] lemma default_coe_singleton (x : α) : (default : ({x} : set α)) = ⟨x, rfl⟩ := rfl
/-! ### Lemmas about sets defined as `{x ∈ s | p x}`. -/
theorem mem_sep {s : set α} {p : α → Prop} {x : α} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} :=
⟨xs, px⟩
@[simp] theorem sep_mem_eq {s t : set α} : {x ∈ s | x ∈ t} = s ∩ t := rfl
@[simp] theorem mem_sep_eq {s : set α} {p : α → Prop} {x : α} :
x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl
theorem mem_sep_iff {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x :=
iff.rfl
theorem eq_sep_of_subset {s t : set α} (h : s ⊆ t) : s = {x ∈ t | x ∈ s} :=
(inter_eq_self_of_subset_right h).symm
@[simp] theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := λ x, and.left
@[simp] lemma sep_empty (p : α → Prop) : {x ∈ (∅ : set α) | p x} = ∅ :=
by { ext, exact false_and _ }
theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (H : {x ∈ s | p x} = ∅)
(x) : x ∈ s → ¬ p x := not_and.1 (eq_empty_iff_forall_not_mem.1 H x : _)
@[simp] lemma sep_univ {α} {p : α → Prop} : {a ∈ (univ : set α) | p a} = {a | p a} := univ_inter _
@[simp] lemma sep_true : {a ∈ s | true} = s :=
by { ext, simp }
@[simp] lemma sep_false : {a ∈ s | false} = ∅ :=
by { ext, simp }
lemma sep_inter_sep {p q : α → Prop} :
{x ∈ s | p x} ∩ {x ∈ s | q x} = {x ∈ s | p x ∧ q x} :=
begin
ext,
simp_rw [mem_inter_iff, mem_sep_iff],
rw [and_and_and_comm, and_self],
end
@[simp] lemma subset_singleton_iff {α : Type*} {s : set α} {x : α} : s ⊆ {x} ↔ ∀ y ∈ s, y = x :=
iff.rfl
lemma subset_singleton_iff_eq {s : set α} {x : α} : s ⊆ {x} ↔ s = ∅ ∨ s = {x} :=
begin
obtain (rfl | hs) := s.eq_empty_or_nonempty,
use ⟨λ _, or.inl rfl, λ _, empty_subset _⟩,
simp [eq_singleton_iff_nonempty_unique_mem, hs, ne_empty_iff_nonempty.2 hs],
end
lemma ssubset_singleton_iff {s : set α} {x : α} : s ⊂ {x} ↔ s = ∅ :=
begin
rw [ssubset_iff_subset_ne, subset_singleton_iff_eq, or_and_distrib_right, and_not_self, or_false,
and_iff_left_iff_imp],
rintro rfl,
refine ne_comm.1 (ne_empty_iff_nonempty.2 (singleton_nonempty _)),
end
lemma eq_empty_of_ssubset_singleton {s : set α} {x : α} (hs : s ⊂ {x}) : s = ∅ :=
ssubset_singleton_iff.1 hs
/-! ### Lemmas about complement -/
theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ sᶜ := h
lemma compl_set_of {α} (p : α → Prop) : {a | p a}ᶜ = { a | ¬ p a } := rfl
theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ sᶜ) : x ∉ s := h
@[simp] theorem mem_compl_eq (s : set α) (x : α) : x ∈ sᶜ = (x ∉ s) := rfl
theorem mem_compl_iff (s : set α) (x : α) : x ∈ sᶜ ↔ x ∉ s := iff.rfl
@[simp] theorem inter_compl_self (s : set α) : s ∩ sᶜ = ∅ := inf_compl_eq_bot
@[simp] theorem compl_inter_self (s : set α) : sᶜ ∩ s = ∅ := compl_inf_eq_bot
@[simp] theorem compl_empty : (∅ : set α)ᶜ = univ := compl_bot
@[simp] theorem compl_union (s t : set α) : (s ∪ t)ᶜ = sᶜ ∩ tᶜ := compl_sup
theorem compl_inter (s t : set α) : (s ∩ t)ᶜ = sᶜ ∪ tᶜ := compl_inf
@[simp] theorem compl_univ : (univ : set α)ᶜ = ∅ := compl_top
@[simp] lemma compl_empty_iff {s : set α} : sᶜ = ∅ ↔ s = univ := compl_eq_bot
@[simp] lemma compl_univ_iff {s : set α} : sᶜ = univ ↔ s = ∅ := compl_eq_top
lemma nonempty_compl {s : set α} : sᶜ.nonempty ↔ s ≠ univ :=
ne_empty_iff_nonempty.symm.trans compl_empty_iff.not
lemma mem_compl_singleton_iff {a x : α} : x ∈ ({a} : set α)ᶜ ↔ x ≠ a :=
mem_singleton_iff.not
lemma compl_singleton_eq (a : α) : ({a} : set α)ᶜ = {x | x ≠ a} :=
ext $ λ x, mem_compl_singleton_iff
@[simp]
lemma compl_ne_eq_singleton (a : α) : ({x | x ≠ a} : set α)ᶜ = {a} :=
by { ext, simp, }
theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = (sᶜ ∩ tᶜ)ᶜ :=
ext $ λ x, or_iff_not_and_not
theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = (sᶜ ∪ tᶜ)ᶜ :=
ext $ λ x, and_iff_not_or_not
@[simp] theorem union_compl_self (s : set α) : s ∪ sᶜ = univ := eq_univ_iff_forall.2 $ λ x, em _
@[simp] theorem compl_union_self (s : set α) : sᶜ ∪ s = univ := by rw [union_comm, union_compl_self]
theorem compl_comp_compl : compl ∘ compl = @id (set α) := funext compl_compl
theorem compl_subset_comm {s t : set α} : sᶜ ⊆ t ↔ tᶜ ⊆ s := @compl_le_iff_compl_le _ s t _
@[simp] lemma compl_subset_compl {s t : set α} : sᶜ ⊆ tᶜ ↔ t ⊆ s := @compl_le_compl_iff_le _ t s _
theorem subset_union_compl_iff_inter_subset {s t u : set α} : s ⊆ t ∪ uᶜ ↔ s ∩ u ⊆ t :=
(@is_compl_compl _ u _).le_sup_right_iff_inf_left_le
theorem compl_subset_iff_union {s t : set α} : sᶜ ⊆ t ↔ s ∪ t = univ :=
iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, or_iff_not_imp_left
theorem subset_compl_comm {s t : set α} : s ⊆ tᶜ ↔ t ⊆ sᶜ :=
forall_congr $ λ a, imp_not_comm
theorem subset_compl_iff_disjoint {s t : set α} : s ⊆ tᶜ ↔ s ∩ t = ∅ :=
iff.trans (forall_congr $ λ a, and_imp.symm) subset_empty_iff
lemma subset_compl_singleton_iff {a : α} {s : set α} : s ⊆ {a}ᶜ ↔ a ∉ s :=
subset_compl_comm.trans singleton_subset_iff
theorem inter_subset (a b c : set α) : a ∩ b ⊆ c ↔ a ⊆ bᶜ ∪ c :=
forall_congr $ λ x, and_imp.trans $ imp_congr_right $ λ _, imp_iff_not_or
lemma inter_compl_nonempty_iff {s t : set α} : (s ∩ tᶜ).nonempty ↔ ¬ s ⊆ t :=
(not_subset.trans $ exists_congr $ by exact λ x, by simp [mem_compl]).symm
/-! ### Lemmas about set difference -/
theorem diff_eq (s t : set α) : s \ t = s ∩ tᶜ := rfl
@[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl
theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t :=
⟨h1, h2⟩
theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s :=
h.left
theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t :=
h.right
theorem diff_eq_compl_inter {s t : set α} : s \ t = tᶜ ∩ s :=
by rw [diff_eq, inter_comm]
theorem nonempty_diff {s t : set α} : (s \ t).nonempty ↔ ¬ (s ⊆ t) := inter_compl_nonempty_iff
theorem diff_subset (s t : set α) : s \ t ⊆ s := show s \ t ≤ s, from sdiff_le
theorem union_diff_cancel' {s t u : set α} (h₁ : s ⊆ t) (h₂ : t ⊆ u) : t ∪ (u \ s) = u :=
sup_sdiff_cancel' h₁ h₂
theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t :=
sup_sdiff_cancel_right h
theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t :=
disjoint.sup_sdiff_cancel_left h
theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s :=
disjoint.sup_sdiff_cancel_right h
@[simp] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s :=
sup_sdiff_left_self
@[simp] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t :=
sup_sdiff_right_self
theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u :=
sup_sdiff
theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) :=
inf_sdiff_assoc
@[simp] theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ :=
inf_sdiff_self_right
@[simp] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s :=
sup_inf_sdiff s t
@[simp] lemma diff_union_inter (s t : set α) : (s \ t) ∪ (s ∩ t) = s :=
by { rw union_comm, exact sup_inf_sdiff _ _ }
@[simp] theorem inter_union_compl (s t : set α) : (s ∩ t) ∪ (s ∩ tᶜ) = s := inter_union_diff _ _
theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ :=
show s₁ ≤ s₂ → t₂ ≤ t₁ → s₁ \ t₁ ≤ s₂ \ t₂, from sdiff_le_sdiff
theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t :=
sdiff_le_sdiff_right ‹s₁ ≤ s₂›
theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t :=
sdiff_le_sdiff_left ‹t ≤ u›
theorem compl_eq_univ_diff (s : set α) : sᶜ = univ \ s :=
top_sdiff.symm
@[simp] lemma empty_diff (s : set α) : (∅ \ s : set α) = ∅ :=
bot_sdiff
theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t :=
sdiff_eq_bot_iff
@[simp] theorem diff_empty {s : set α} : s \ ∅ = s :=
sdiff_bot
@[simp] lemma diff_univ (s : set α) : s \ univ = ∅ := diff_eq_empty.2 (subset_univ s)
theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) :=
sdiff_sdiff_left
-- the following statement contains parentheses to help the reader
lemma diff_diff_comm {s t u : set α} : (s \ t) \ u = (s \ u) \ t :=
sdiff_sdiff_comm
lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u :=
show s \ t ≤ u ↔ s ≤ t ∪ u, from sdiff_le_iff
lemma subset_diff_union (s t : set α) : s ⊆ (s \ t) ∪ t :=
show s ≤ (s \ t) ∪ t, from le_sdiff_sup
lemma diff_union_of_subset {s t : set α} (h : t ⊆ s) :
(s \ t) ∪ t = s :=
subset.antisymm (union_subset (diff_subset _ _) h) (subset_diff_union _ _)
@[simp] lemma diff_singleton_subset_iff {x : α} {s t : set α} : s \ {x} ⊆ t ↔ s ⊆ insert x t :=
by { rw [←union_singleton, union_comm], apply diff_subset_iff }
lemma subset_diff_singleton {x : α} {s t : set α} (h : s ⊆ t) (hx : x ∉ s) : s ⊆ t \ {x} :=
subset_inter h $ subset_compl_comm.1 $ singleton_subset_iff.2 hx
lemma subset_insert_diff_singleton (x : α) (s : set α) : s ⊆ insert x (s \ {x}) :=
by rw [←diff_singleton_subset_iff]
lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t :=
show s \ t ≤ u ↔ s \ u ≤ t, from sdiff_le_comm
lemma diff_inter {s t u : set α} : s \ (t ∩ u) = (s \ t) ∪ (s \ u) :=
sdiff_inf
lemma diff_inter_diff {s t u : set α} : s \ t ∩ (s \ u) = s \ (t ∪ u) :=
sdiff_sup.symm
lemma diff_compl : s \ tᶜ = s ∩ t := sdiff_compl
lemma diff_diff_right {s t u : set α} : s \ (t \ u) = (s \ t) ∪ (s ∩ u) :=
sdiff_sdiff_right'
@[simp] theorem insert_diff_of_mem (s) (h : a ∈ t) : insert a s \ t = s \ t :=
by { ext, split; simp [or_imp_distrib, h] {contextual := tt} }
theorem insert_diff_of_not_mem (s) (h : a ∉ t) : insert a s \ t = insert a (s \ t) :=
begin
classical,
ext x,
by_cases h' : x ∈ t,
{ have : x ≠ a,
{ assume H,
rw H at h',
exact h h' },
simp [h, h', this] },
{ simp [h, h'] }
end
lemma insert_diff_self_of_not_mem {a : α} {s : set α} (h : a ∉ s) :
insert a s \ {a} = s :=
by { ext, simp [and_iff_left_of_imp (λ hx : x ∈ s, show x ≠ a, from λ hxa, h $ hxa ▸ hx)] }
lemma insert_inter_of_mem {s₁ s₂ : set α} {a : α} (h : a ∈ s₂) :
insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) :=
by simp [set.insert_inter, h]
lemma insert_inter_of_not_mem {s₁ s₂ : set α} {a : α} (h : a ∉ s₂) :
insert a s₁ ∩ s₂ = s₁ ∩ s₂ :=
begin
ext x,
simp only [mem_inter_iff, mem_insert_iff, mem_inter_eq, and.congr_left_iff, or_iff_right_iff_imp],
cc,
end
@[simp] theorem union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t :=
sup_sdiff_self_right
@[simp] theorem diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t :=
sup_sdiff_self_left
@[simp] theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ :=
inf_sdiff_self_left
@[simp] theorem diff_inter_self_eq_diff {s t : set α} : s \ (t ∩ s) = s \ t :=
sdiff_inf_self_right
@[simp] theorem diff_self_inter {s t : set α} : s \ (s ∩ t) = s \ t :=
sdiff_inf_self_left
@[simp] theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ :=
show s \ t = s ↔ t ⊓ s ≤ ⊥, from sdiff_eq_self_iff_disjoint
@[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s :=
diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h]
@[simp] theorem insert_diff_singleton {a : α} {s : set α} :
insert a (s \ {a}) = insert a s :=
by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union]
@[simp] lemma diff_self {s : set α} : s \ s = ∅ := sdiff_self
lemma diff_diff_cancel_left {s t : set α} (h : s ⊆ t) : t \ (t \ s) = s :=
sdiff_sdiff_eq_self h
lemma mem_diff_singleton {x y : α} {s : set α} : x ∈ s \ {y} ↔ (x ∈ s ∧ x ≠ y) :=
iff.rfl
lemma mem_diff_singleton_empty {s : set α} {t : set (set α)} :
s ∈ t \ {∅} ↔ (s ∈ t ∧ s.nonempty) :=
mem_diff_singleton.trans $ iff.rfl.and ne_empty_iff_nonempty
lemma union_eq_diff_union_diff_union_inter (s t : set α) :
s ∪ t = (s \ t) ∪ (t \ s) ∪ (s ∩ t) :=
sup_eq_sdiff_sup_sdiff_sup_inf
/-! ### Powerset -/
theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ powerset s := h
theorem subset_of_mem_powerset {x s : set α} (h : x ∈ powerset s) : x ⊆ s := h
@[simp] theorem mem_powerset_iff (x s : set α) : x ∈ powerset s ↔ x ⊆ s := iff.rfl
theorem powerset_inter (s t : set α) : 𝒫 (s ∩ t) = 𝒫 s ∩ 𝒫 t :=
ext $ λ u, subset_inter_iff
@[simp] theorem powerset_mono : 𝒫 s ⊆ 𝒫 t ↔ s ⊆ t :=
⟨λ h, h (subset.refl s), λ h u hu, subset.trans hu h⟩
theorem monotone_powerset : monotone (powerset : set α → set (set α)) :=
λ s t, powerset_mono.2
@[simp] theorem powerset_nonempty : (𝒫 s).nonempty :=
⟨∅, empty_subset s⟩
@[simp] theorem powerset_empty : 𝒫 (∅ : set α) = {∅} :=
ext $ λ s, subset_empty_iff
@[simp] theorem powerset_univ : 𝒫 (univ : set α) = univ :=
eq_univ_of_forall subset_univ
/-! ### If-then-else for sets -/
/-- `ite` for sets: `set.ite t s s' ∩ t = s ∩ t`, `set.ite t s s' ∩ tᶜ = s' ∩ tᶜ`.
Defined as `s ∩ t ∪ s' \ t`. -/
protected def ite (t s s' : set α) : set α := s ∩ t ∪ s' \ t
@[simp] lemma ite_inter_self (t s s' : set α) : t.ite s s' ∩ t = s ∩ t :=
by rw [set.ite, union_inter_distrib_right, diff_inter_self, inter_assoc, inter_self, union_empty]
@[simp] lemma ite_compl (t s s' : set α) : tᶜ.ite s s' = t.ite s' s :=
by rw [set.ite, set.ite, diff_compl, union_comm, diff_eq]
@[simp] lemma ite_inter_compl_self (t s s' : set α) : t.ite s s' ∩ tᶜ = s' ∩ tᶜ :=
by rw [← ite_compl, ite_inter_self]
@[simp] lemma ite_diff_self (t s s' : set α) : t.ite s s' \ t = s' \ t :=
ite_inter_compl_self t s s'
@[simp] lemma ite_same (t s : set α) : t.ite s s = s := inter_union_diff _ _
@[simp] lemma ite_left (s t : set α) : s.ite s t = s ∪ t := by simp [set.ite]
@[simp] lemma ite_right (s t : set α) : s.ite t s = t ∩ s := by simp [set.ite]
@[simp] lemma ite_empty (s s' : set α) : set.ite ∅ s s' = s' :=
by simp [set.ite]
@[simp] lemma ite_univ (s s' : set α) : set.ite univ s s' = s :=
by simp [set.ite]
@[simp] lemma ite_empty_left (t s : set α) : t.ite ∅ s = s \ t :=
by simp [set.ite]
@[simp] lemma ite_empty_right (t s : set α) : t.ite s ∅ = s ∩ t :=
by simp [set.ite]
lemma ite_mono (t : set α) {s₁ s₁' s₂ s₂' : set α} (h : s₁ ⊆ s₂) (h' : s₁' ⊆ s₂') :
t.ite s₁ s₁' ⊆ t.ite s₂ s₂' :=
union_subset_union (inter_subset_inter_left _ h) (inter_subset_inter_left _ h')
lemma ite_subset_union (t s s' : set α) : t.ite s s' ⊆ s ∪ s' :=
union_subset_union (inter_subset_left _ _) (diff_subset _ _)
lemma inter_subset_ite (t s s' : set α) : s ∩ s' ⊆ t.ite s s' :=
ite_same t (s ∩ s') ▸ ite_mono _ (inter_subset_left _ _) (inter_subset_right _ _)
lemma ite_inter_inter (t s₁ s₂ s₁' s₂' : set α) :
t.ite (s₁ ∩ s₂) (s₁' ∩ s₂') = t.ite s₁ s₁' ∩ t.ite s₂ s₂' :=
by { ext x, simp only [set.ite, set.mem_inter_eq, set.mem_diff, set.mem_union_eq], itauto }
lemma ite_inter (t s₁ s₂ s : set α) :
t.ite (s₁ ∩ s) (s₂ ∩ s) = t.ite s₁ s₂ ∩ s :=
by rw [ite_inter_inter, ite_same]
lemma ite_inter_of_inter_eq (t : set α) {s₁ s₂ s : set α} (h : s₁ ∩ s = s₂ ∩ s) :
t.ite s₁ s₂ ∩ s = s₁ ∩ s :=
by rw [← ite_inter, ← h, ite_same]
lemma subset_ite {t s s' u : set α} : u ⊆ t.ite s s' ↔ u ∩ t ⊆ s ∧ u \ t ⊆ s' :=
begin
simp only [subset_def, ← forall_and_distrib],
refine forall_congr (λ x, _),
by_cases hx : x ∈ t; simp [*, set.ite]
end
/-! ### Inverse image -/
/-- The preimage of `s : set β` by `f : α → β`, written `f ⁻¹' s`,
is the set of `x : α` such that `f x ∈ s`. -/
def preimage {α : Type u} {β : Type v} (f : α → β) (s : set β) : set α := {x | f x ∈ s}
infix ` ⁻¹' `:80 := preimage
section preimage
variables {f : α → β} {g : β → γ}
@[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl
@[simp] theorem mem_preimage {s : set β} {a : α} : (a ∈ f ⁻¹' s) ↔ (f a ∈ s) := iff.rfl
lemma preimage_congr {f g : α → β} {s : set β} (h : ∀ (x : α), f x = g x) : f ⁻¹' s = g ⁻¹' s :=
by { congr' with x, apply_assumption }
theorem preimage_mono {s t : set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t :=
assume x hx, h hx
@[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl
theorem subset_preimage_univ {s : set α} : s ⊆ f ⁻¹' univ := subset_univ _
@[simp] theorem preimage_inter {s t : set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl
@[simp] theorem preimage_union {s t : set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl
@[simp] theorem preimage_compl {s : set β} : f ⁻¹' sᶜ = (f ⁻¹' s)ᶜ := rfl
@[simp] theorem preimage_diff (f : α → β) (s t : set β) :
f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl
@[simp] theorem preimage_ite (f : α → β) (s t₁ t₂ : set β) :
f ⁻¹' (s.ite t₁ t₂) = (f ⁻¹' s).ite (f ⁻¹' t₁) (f ⁻¹' t₂) :=
rfl
@[simp] theorem preimage_set_of_eq {p : α → Prop} {f : β → α} : f ⁻¹' {a | p a} = {a | p (f a)} :=
rfl
@[simp] theorem preimage_id {s : set α} : id ⁻¹' s = s := rfl
@[simp] theorem preimage_id' {s : set α} : (λ x, x) ⁻¹' s = s := rfl
@[simp] theorem preimage_const_of_mem {b : β} {s : set β} (h : b ∈ s) :
(λ (x : α), b) ⁻¹' s = univ :=
eq_univ_of_forall $ λ x, h
@[simp] theorem preimage_const_of_not_mem {b : β} {s : set β} (h : b ∉ s) :
(λ (x : α), b) ⁻¹' s = ∅ :=
eq_empty_of_subset_empty $ λ x hx, h hx
theorem preimage_const (b : β) (s : set β) [decidable (b ∈ s)] :
(λ (x : α), b) ⁻¹' s = if b ∈ s then univ else ∅ :=
by { split_ifs with hb hb, exacts [preimage_const_of_mem hb, preimage_const_of_not_mem hb] }
theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl
lemma preimage_preimage {g : β → γ} {f : α → β} {s : set γ} :
f ⁻¹' (g ⁻¹' s) = (λ x, g (f x)) ⁻¹' s :=
preimage_comp.symm
theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : set (subtype p)} {t : set α} :
s = subtype.val ⁻¹' t ↔ (∀x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) :=
⟨assume s_eq x h, by { rw [s_eq], simp },
assume h, ext $ λ ⟨x, hx⟩, by simp [h]⟩
lemma nonempty_of_nonempty_preimage {s : set β} {f : α → β} (hf : (f ⁻¹' s).nonempty) :
s.nonempty :=
let ⟨x, hx⟩ := hf in ⟨f x, hx⟩
end preimage
/-! ### Image of a set under a function -/
section image
infix ` '' `:80 := image
theorem mem_image_iff_bex {f : α → β} {s : set α} {y : β} :
y ∈ f '' s ↔ ∃ x (_ : x ∈ s), f x = y := bex_def.symm
theorem mem_image_eq (f : α → β) (s : set α) (y: β) : y ∈ f '' s = ∃ x, x ∈ s ∧ f x = y := rfl
@[simp] theorem mem_image (f : α → β) (s : set α) (y : β) :
y ∈ f '' s ↔ ∃ x, x ∈ s ∧ f x = y := iff.rfl
lemma image_eta (f : α → β) : f '' s = (λ x, f x) '' s := rfl
theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a :=
⟨_, h, rfl⟩
theorem _root_.function.injective.mem_set_image {f : α → β} (hf : injective f) {s : set α} {a : α} :
f a ∈ f '' s ↔ a ∈ s :=
⟨λ ⟨b, hb, eq⟩, (hf eq) ▸ hb, mem_image_of_mem f⟩
theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} :
(∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) :=
by simp
theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop}
(h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y :=
ball_image_iff.2 h
theorem bex_image_iff {f : α → β} {s : set α} {p : β → Prop} :
(∃ y ∈ f '' s, p y) ↔ (∃ x ∈ s, p (f x)) :=
by simp
theorem mem_image_elim {f : α → β} {s : set α} {C : β → Prop} (h : ∀ (x : α), x ∈ s → C (f x)) :
∀{y : β}, y ∈ f '' s → C y
| ._ ⟨a, a_in, rfl⟩ := h a a_in
theorem mem_image_elim_on {f : α → β} {s : set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s)
(h : ∀ (x : α), x ∈ s → C (f x)) : C y :=
mem_image_elim h h_y
@[congr] lemma image_congr {f g : α → β} {s : set α}
(h : ∀a∈s, f a = g a) : f '' s = g '' s :=
by safe [ext_iff, iff_def]
/-- A common special case of `image_congr` -/
lemma image_congr' {f g : α → β} {s : set α} (h : ∀ (x : α), f x = g x) : f '' s = g '' s :=
image_congr (λx _, h x)
theorem image_comp (f : β → γ) (g : α → β) (a : set α) : (f ∘ g) '' a = f '' (g '' a) :=
subset.antisymm
(ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha)
(ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha)
/-- A variant of `image_comp`, useful for rewriting -/
lemma image_image (g : β → γ) (f : α → β) (s : set α) : g '' (f '' s) = (λ x, g (f x)) '' s :=
(image_comp g f s).symm
/-- Image is monotone with respect to `⊆`. See `set.monotone_image` for the statement in
terms of `≤`. -/
theorem image_subset {a b : set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b :=
by { simp only [subset_def, mem_image_eq], exact λ x, λ ⟨w, h1, h2⟩, ⟨w, h h1, h2⟩ }
theorem image_union (f : α → β) (s t : set α) :
f '' (s ∪ t) = f '' s ∪ f '' t :=
ext $ λ x, ⟨by rintro ⟨a, h|h, rfl⟩; [left, right]; exact ⟨_, h, rfl⟩,
by rintro (⟨a, h, rfl⟩ | ⟨a, h, rfl⟩); refine ⟨_, _, rfl⟩; [left, right]; exact h⟩
@[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := by { ext, simp }
lemma image_inter_subset (f : α → β) (s t : set α) :
f '' (s ∩ t) ⊆ f '' s ∩ f '' t :=
subset_inter (image_subset _ $ inter_subset_left _ _) (image_subset _ $ inter_subset_right _ _)
theorem image_inter_on {f : α → β} {s t : set α} (h : ∀x∈t, ∀y∈s, f x = f y → x = y) :
f '' s ∩ f '' t = f '' (s ∩ t) :=
subset.antisymm
(assume b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩,
have a₂ = a₁, from h _ ha₂ _ ha₁ (by simp *),
⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩)
(image_inter_subset _ _ _)
theorem image_inter {f : α → β} {s t : set α} (H : injective f) :
f '' s ∩ f '' t = f '' (s ∩ t) :=
image_inter_on (assume x _ y _ h, H h)
theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : surjective f) : f '' univ = univ :=
eq_univ_of_forall $ by { simpa [image] }
@[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} :=
by { ext, simp [image, eq_comm] }
@[simp] theorem nonempty.image_const {s : set α} (hs : s.nonempty) (a : β) : (λ _, a) '' s = {a} :=
ext $ λ x, ⟨λ ⟨y, _, h⟩, h ▸ mem_singleton _,
λ h, (eq_of_mem_singleton h).symm ▸ hs.imp (λ y hy, ⟨hy, rfl⟩)⟩
@[simp] lemma image_eq_empty {α β} {f : α → β} {s : set α} : f '' s = ∅ ↔ s = ∅ :=
by { simp only [eq_empty_iff_forall_not_mem],
exact ⟨λ H a ha, H _ ⟨_, ha, rfl⟩, λ H b ⟨_, ha, _⟩, H _ ha⟩ }
-- TODO(Jeremy): there is an issue with - t unfolding to compl t
theorem mem_compl_image (t : set α) (S : set (set α)) :
t ∈ compl '' S ↔ tᶜ ∈ S :=
begin
suffices : ∀ x, xᶜ = t ↔ tᶜ = x, { simp [this] },
intro x, split; { intro e, subst e, simp }
end
/-- A variant of `image_id` -/
@[simp] lemma image_id' (s : set α) : (λx, x) '' s = s := by { ext, simp }
theorem image_id (s : set α) : id '' s = s := by simp
theorem compl_compl_image (S : set (set α)) :
compl '' (compl '' S) = S :=
by rw [← image_comp, compl_comp_compl, image_id]
theorem image_insert_eq {f : α → β} {a : α} {s : set α} :
f '' (insert a s) = insert (f a) (f '' s) :=
by { ext, simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] }
theorem image_pair (f : α → β) (a b : α) : f '' {a, b} = {f a, f b} :=
by simp only [image_insert_eq, image_singleton]
theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α}
(I : left_inverse g f) (s : set α) : f '' s ⊆ g ⁻¹' s :=
λ b ⟨a, h, e⟩, e ▸ ((I a).symm ▸ h : g (f a) ∈ s)
theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α}
(I : left_inverse g f) (s : set β) : f ⁻¹' s ⊆ g '' s :=
λ b h, ⟨f b, h, I b⟩
theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α}
(h₁ : left_inverse g f) (h₂ : right_inverse g f) :
image f = preimage g :=
funext $ λ s, subset.antisymm
(image_subset_preimage_of_inverse h₁ s)
(preimage_subset_image_of_inverse h₂ s)
theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : set α}
(h₁ : left_inverse g f) (h₂ : right_inverse g f) :
b ∈ f '' s ↔ g b ∈ s :=
by rw image_eq_preimage_of_inverse h₁ h₂; refl
theorem image_compl_subset {f : α → β} {s : set α} (H : injective f) : f '' sᶜ ⊆ (f '' s)ᶜ :=
subset_compl_iff_disjoint.2 $ by simp [image_inter H]
theorem subset_image_compl {f : α → β} {s : set α} (H : surjective f) : (f '' s)ᶜ ⊆ f '' sᶜ :=
compl_subset_iff_union.2 $
by { rw ← image_union, simp [image_univ_of_surjective H] }
theorem image_compl_eq {f : α → β} {s : set α} (H : bijective f) : f '' sᶜ = (f '' s)ᶜ :=
subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2)
theorem subset_image_diff (f : α → β) (s t : set α) :
f '' s \ f '' t ⊆ f '' (s \ t) :=
begin
rw [diff_subset_iff, ← image_union, union_diff_self],
exact image_subset f (subset_union_right t s)
end
theorem image_diff {f : α → β} (hf : injective f) (s t : set α) :
f '' (s \ t) = f '' s \ f '' t :=
subset.antisymm
(subset.trans (image_inter_subset _ _ _) $ inter_subset_inter_right _ $ image_compl_subset hf)
(subset_image_diff f s t)
lemma nonempty.image (f : α → β) {s : set α} : s.nonempty → (f '' s).nonempty
| ⟨x, hx⟩ := ⟨f x, mem_image_of_mem f hx⟩
lemma nonempty.of_image {f : α → β} {s : set α} : (f '' s).nonempty → s.nonempty
| ⟨y, x, hx, _⟩ := ⟨x, hx⟩
@[simp] lemma nonempty_image_iff {f : α → β} {s : set α} :
(f '' s).nonempty ↔ s.nonempty :=
⟨nonempty.of_image, λ h, h.image f⟩
lemma nonempty.preimage {s : set β} (hs : s.nonempty) {f : α → β} (hf : surjective f) :
(f ⁻¹' s).nonempty :=
let ⟨y, hy⟩ := hs, ⟨x, hx⟩ := hf y in ⟨x, mem_preimage.2 $ hx.symm ▸ hy⟩
instance (f : α → β) (s : set α) [nonempty s] : nonempty (f '' s) :=
(set.nonempty.image f nonempty_of_nonempty_subtype).to_subtype
/-- image and preimage are a Galois connection -/
@[simp] theorem image_subset_iff {s : set α} {t : set β} {f : α → β} :
f '' s ⊆ t ↔ s ⊆ f ⁻¹' t :=
ball_image_iff
theorem image_preimage_subset (f : α → β) (s : set β) : f '' (f ⁻¹' s) ⊆ s :=
image_subset_iff.2 subset.rfl
theorem subset_preimage_image (f : α → β) (s : set α) :
s ⊆ f ⁻¹' (f '' s) :=
λ x, mem_image_of_mem f
theorem preimage_image_eq {f : α → β} (s : set α) (h : injective f) : f ⁻¹' (f '' s) = s :=
subset.antisymm
(λ x ⟨y, hy, e⟩, h e ▸ hy)
(subset_preimage_image f s)
theorem image_preimage_eq {f : α → β} (s : set β) (h : surjective f) : f '' (f ⁻¹' s) = s :=
subset.antisymm
(image_preimage_subset f s)
(λ x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩)
lemma preimage_eq_preimage {f : β → α} (hf : surjective f) : f ⁻¹' s = f ⁻¹' t ↔ s = t :=
iff.intro
(assume eq, by rw [← image_preimage_eq s hf, ← image_preimage_eq t hf, eq])
(assume eq, eq ▸ rfl)
lemma image_inter_preimage (f : α → β) (s : set α) (t : set β) :
f '' (s ∩ f ⁻¹' t) = f '' s ∩ t :=
begin
apply subset.antisymm,
{ calc f '' (s ∩ f ⁻¹' t) ⊆ f '' s ∩ (f '' (f⁻¹' t)) : image_inter_subset _ _ _
... ⊆ f '' s ∩ t : inter_subset_inter_right _ (image_preimage_subset f t) },
{ rintros _ ⟨⟨x, h', rfl⟩, h⟩,
exact ⟨x, ⟨h', h⟩, rfl⟩ }
end
lemma image_preimage_inter (f : α → β) (s : set α) (t : set β) :
f '' (f ⁻¹' t ∩ s) = t ∩ f '' s :=
by simp only [inter_comm, image_inter_preimage]
@[simp] lemma image_inter_nonempty_iff {f : α → β} {s : set α} {t : set β} :
(f '' s ∩ t).nonempty ↔ (s ∩ f ⁻¹' t).nonempty :=
by rw [←image_inter_preimage, nonempty_image_iff]
lemma image_diff_preimage {f : α → β} {s : set α} {t : set β} : f '' (s \ f ⁻¹' t) = f '' s \ t :=
by simp_rw [diff_eq, ← preimage_compl, image_inter_preimage]
theorem compl_image : image (compl : set α → set α) = preimage compl :=
image_eq_preimage_of_inverse compl_compl compl_compl
theorem compl_image_set_of {p : set α → Prop} :
compl '' {s | p s} = {s | p sᶜ} :=
congr_fun compl_image p
theorem inter_preimage_subset (s : set α) (t : set β) (f : α → β) :
s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) :=
λ x h, ⟨mem_image_of_mem _ h.left, h.right⟩
theorem union_preimage_subset (s : set α) (t : set β) (f : α → β) :
s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) :=
λ x h, or.elim h (λ l, or.inl $ mem_image_of_mem _ l) (λ r, or.inr r)
theorem subset_image_union (f : α → β) (s : set α) (t : set β) :
f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t :=
image_subset_iff.2 (union_preimage_subset _ _ _)
lemma preimage_subset_iff {A : set α} {B : set β} {f : α → β} :
f⁻¹' B ⊆ A ↔ (∀ a : α, f a ∈ B → a ∈ A) := iff.rfl
lemma image_eq_image {f : α → β} (hf : injective f) : f '' s = f '' t ↔ s = t :=
iff.symm $ iff.intro (assume eq, eq ▸ rfl) $ assume eq,
by rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, eq]
lemma image_subset_image_iff {f : α → β} (hf : injective f) : f '' s ⊆ f '' t ↔ s ⊆ t :=
begin
refine (iff.symm $ iff.intro (image_subset f) $ assume h, _),
rw [← preimage_image_eq s hf, ← preimage_image_eq t hf],
exact preimage_mono h
end
lemma prod_quotient_preimage_eq_image [s : setoid α] (g : quotient s → β) {h : α → β}
(Hh : h = g ∘ quotient.mk) (r : set (β × β)) :
{x : quotient s × quotient s | (g x.1, g x.2) ∈ r} =
(λ a : α × α, (⟦a.1⟧, ⟦a.2⟧)) '' ((λ a : α × α, (h a.1, h a.2)) ⁻¹' r) :=
Hh.symm ▸ set.ext (λ ⟨a₁, a₂⟩, ⟨quotient.induction_on₂ a₁ a₂
(λ a₁ a₂ h, ⟨(a₁, a₂), h, rfl⟩),
λ ⟨⟨b₁, b₂⟩, h₁, h₂⟩, show (g a₁, g a₂) ∈ r, from
have h₃ : ⟦b₁⟧ = a₁ ∧ ⟦b₂⟧ = a₂ := prod.ext_iff.1 h₂,
h₃.1 ▸ h₃.2 ▸ h₁⟩)
lemma exists_image_iff (f : α → β) (x : set α) (P : β → Prop) :
(∃ (a : f '' x), P a) ↔ ∃ (a : x), P (f a) :=
⟨λ ⟨a, h⟩, ⟨⟨_, a.prop.some_spec.1⟩, a.prop.some_spec.2.symm ▸ h⟩,
λ ⟨a, h⟩, ⟨⟨_, _, a.prop, rfl⟩, h⟩⟩
/-- Restriction of `f` to `s` factors through `s.image_factorization f : s → f '' s`. -/
def image_factorization (f : α → β) (s : set α) : s → f '' s :=
λ p, ⟨f p.1, mem_image_of_mem f p.2⟩
lemma image_factorization_eq {f : α → β} {s : set α} :
subtype.val ∘ image_factorization f s = f ∘ subtype.val :=
funext $ λ p, rfl
lemma surjective_onto_image {f : α → β} {s : set α} :
surjective (image_factorization f s) :=
λ ⟨_, ⟨a, ha, rfl⟩⟩, ⟨⟨a, ha⟩, rfl⟩
end image
/-! ### Subsingleton -/
/-- A set `s` is a `subsingleton`, if it has at most one element. -/
protected def subsingleton (s : set α) : Prop :=
∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y
lemma subsingleton.mono (ht : t.subsingleton) (hst : s ⊆ t) : s.subsingleton :=
λ x hx y hy, ht (hst hx) (hst hy)
lemma subsingleton.image (hs : s.subsingleton) (f : α → β) : (f '' s).subsingleton :=
λ _ ⟨x, hx, Hx⟩ _ ⟨y, hy, Hy⟩, Hx ▸ Hy ▸ congr_arg f (hs hx hy)
lemma subsingleton.eq_singleton_of_mem (hs : s.subsingleton) {x:α} (hx : x ∈ s) :
s = {x} :=
ext $ λ y, ⟨λ hy, (hs hx hy) ▸ mem_singleton _, λ hy, (eq_of_mem_singleton hy).symm ▸ hx⟩
@[simp] lemma subsingleton_empty : (∅ : set α).subsingleton := λ x, false.elim
@[simp] lemma subsingleton_singleton {a} : ({a} : set α).subsingleton :=
λ x hx y hy, (eq_of_mem_singleton hx).symm ▸ (eq_of_mem_singleton hy).symm ▸ rfl
lemma subsingleton_of_forall_eq (a : α) (h : ∀ b ∈ s, b = a) : s.subsingleton :=
λ b hb c hc, (h _ hb).trans (h _ hc).symm
lemma subsingleton_iff_singleton {x} (hx : x ∈ s) : s.subsingleton ↔ s = {x} :=
⟨λ h, h.eq_singleton_of_mem hx, λ h,h.symm ▸ subsingleton_singleton⟩
lemma subsingleton.eq_empty_or_singleton (hs : s.subsingleton) :
s = ∅ ∨ ∃ x, s = {x} :=
s.eq_empty_or_nonempty.elim or.inl (λ ⟨x, hx⟩, or.inr ⟨x, hs.eq_singleton_of_mem hx⟩)
lemma subsingleton.induction_on {p : set α → Prop} (hs : s.subsingleton) (he : p ∅)
(h₁ : ∀ x, p {x}) : p s :=
by { rcases hs.eq_empty_or_singleton with rfl|⟨x, rfl⟩, exacts [he, h₁ _] }
lemma subsingleton_univ [subsingleton α] : (univ : set α).subsingleton :=
λ x hx y hy, subsingleton.elim x y
lemma subsingleton_of_univ_subsingleton (h : (univ : set α).subsingleton) : subsingleton α :=
⟨λ a b, h (mem_univ a) (mem_univ b)⟩
@[simp] lemma subsingleton_univ_iff : (univ : set α).subsingleton ↔ subsingleton α :=
⟨subsingleton_of_univ_subsingleton, λ h, @subsingleton_univ _ h⟩
lemma subsingleton_of_subsingleton [subsingleton α] {s : set α} : set.subsingleton s :=
subsingleton.mono subsingleton_univ (subset_univ s)
lemma subsingleton_is_top (α : Type*) [partial_order α] : set.subsingleton {x : α | is_top x} :=
λ x hx y hy, hx.is_max.eq_of_le (hy x)
lemma subsingleton_is_bot (α : Type*) [partial_order α] : set.subsingleton {x : α | is_bot x} :=
λ x hx y hy, hx.is_min.eq_of_ge (hy x)
/-- `s`, coerced to a type, is a subsingleton type if and only if `s`
is a subsingleton set. -/
@[simp, norm_cast] lemma subsingleton_coe (s : set α) : subsingleton s ↔ s.subsingleton :=
begin
split,
{ refine λ h, (λ a ha b hb, _),
exact set_coe.ext_iff.2 (@subsingleton.elim s h ⟨a, ha⟩ ⟨b, hb⟩) },
{ exact λ h, subsingleton.intro (λ a b, set_coe.ext (h a.property b.property)) }
end
/-- The `coe_sort` of a set `s` in a subsingleton type is a subsingleton.
For the corresponding result for `subtype`, see `subtype.subsingleton`. -/
instance subsingleton_coe_of_subsingleton [subsingleton α] {s : set α} : subsingleton s :=
by { rw [s.subsingleton_coe], exact subsingleton_of_subsingleton }
/-- The preimage of a subsingleton under an injective map is a subsingleton. -/
theorem subsingleton.preimage {s : set β} (hs : s.subsingleton) {f : α → β}
(hf : function.injective f) :
(f ⁻¹' s).subsingleton :=
λ a ha b hb, hf $ hs ha hb
/-- `s` is a subsingleton, if its image of an injective function is. -/
theorem subsingleton_of_image {α β : Type*} {f : α → β} (hf : function.injective f)
(s : set α) (hs : (f '' s).subsingleton) : s.subsingleton :=
(hs.preimage hf).mono $ subset_preimage_image _ _
theorem univ_eq_true_false : univ = ({true, false} : set Prop) :=
eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp)
/-! ### Lemmas about range of a function. -/
section range
variables {f : ι → α}
open function
/-- Range of a function.
This function is more flexible than `f '' univ`, as the image requires that the domain is in Type
and not an arbitrary Sort. -/
def range (f : ι → α) : set α := {x | ∃y, f y = x}
@[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl
@[simp] theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩
theorem forall_range_iff {p : α → Prop} : (∀ a ∈ range f, p a) ↔ (∀ i, p (f i)) :=
by simp
theorem forall_subtype_range_iff {p : range f → Prop} :
(∀ a : range f, p a) ↔ ∀ i, p ⟨f i, mem_range_self _⟩ :=
⟨λ H i, H _, λ H ⟨y, i, hi⟩, by { subst hi, apply H }⟩
theorem exists_range_iff {p : α → Prop} : (∃ a ∈ range f, p a) ↔ (∃ i, p (f i)) :=
by simp
lemma exists_range_iff' {p : α → Prop} :
(∃ a, a ∈ range f ∧ p a) ↔ ∃ i, p (f i) :=
by simpa only [exists_prop] using exists_range_iff
lemma exists_subtype_range_iff {p : range f → Prop} :
(∃ a : range f, p a) ↔ ∃ i, p ⟨f i, mem_range_self _⟩ :=
⟨λ ⟨⟨a, i, hi⟩, ha⟩, by { subst a, exact ⟨i, ha⟩}, λ ⟨i, hi⟩, ⟨_, hi⟩⟩
theorem range_iff_surjective : range f = univ ↔ surjective f :=
eq_univ_iff_forall
alias range_iff_surjective ↔ _ function.surjective.range_eq
@[simp] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id
@[simp] theorem range_id' : range (λ (x : α), x) = univ := range_id
@[simp] theorem _root_.prod.range_fst [nonempty β] : range (prod.fst : α × β → α) = univ :=
prod.fst_surjective.range_eq
@[simp] theorem _root_.prod.range_snd [nonempty α] : range (prod.snd : α × β → β) = univ :=
prod.snd_surjective.range_eq
@[simp] theorem range_eval {ι : Type*} {α : ι → Sort*} [Π i, nonempty (α i)] (i : ι) :
range (eval i : (Π i, α i) → α i) = univ :=
(surjective_eval i).range_eq
theorem is_compl_range_inl_range_inr : is_compl (range $ @sum.inl α β) (range sum.inr) :=
⟨by { rintro y ⟨⟨x₁, rfl⟩, ⟨x₂, _⟩⟩, cc },
by { rintro (x|y) -; [left, right]; exact mem_range_self _ }⟩
@[simp] theorem range_inl_union_range_inr : range (sum.inl : α → α ⊕ β) ∪ range sum.inr = univ :=
is_compl_range_inl_range_inr.sup_eq_top
@[simp] theorem range_inl_inter_range_inr : range (sum.inl : α → α ⊕ β) ∩ range sum.inr = ∅ :=
is_compl_range_inl_range_inr.inf_eq_bot
@[simp] theorem range_inr_union_range_inl : range (sum.inr : β → α ⊕ β) ∪ range sum.inl = univ :=
is_compl_range_inl_range_inr.symm.sup_eq_top
@[simp] theorem range_inr_inter_range_inl : range (sum.inr : β → α ⊕ β) ∩ range sum.inl = ∅ :=
is_compl_range_inl_range_inr.symm.inf_eq_bot
@[simp] theorem preimage_inl_range_inr : sum.inl ⁻¹' range (sum.inr : β → α ⊕ β) = ∅ :=
by { ext, simp }
@[simp] theorem preimage_inr_range_inl : sum.inr ⁻¹' range (sum.inl : α → α ⊕ β) = ∅ :=
by { ext, simp }
@[simp] theorem range_quot_mk (r : α → α → Prop) : range (quot.mk r) = univ :=
(surjective_quot_mk r).range_eq
@[simp] theorem image_univ {f : α → β} : f '' univ = range f :=
by { ext, simp [image, range] }
theorem image_subset_range (f : α → β) (s) : f '' s ⊆ range f :=
by rw ← image_univ; exact image_subset _ (subset_univ _)
theorem mem_range_of_mem_image (f : α → β) (s) {x : β} (h : x ∈ f '' s) : x ∈ range f :=
image_subset_range f s h
lemma nonempty.preimage' {s : set β} (hs : s.nonempty) {f : α → β} (hf : s ⊆ set.range f) :
(f ⁻¹' s).nonempty :=
let ⟨y, hy⟩ := hs, ⟨x, hx⟩ := hf hy in ⟨x, set.mem_preimage.2 $ hx.symm ▸ hy⟩
theorem range_comp (g : α → β) (f : ι → α) : range (g ∘ f) = g '' range f :=
subset.antisymm
(forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _))
(ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self)
theorem range_subset_iff : range f ⊆ s ↔ ∀ y, f y ∈ s :=
forall_range_iff
theorem range_eq_iff (f : α → β) (s : set β) :
range f = s ↔ (∀ a, f a ∈ s) ∧ ∀ b ∈ s, ∃ a, f a = b :=
by { rw ←range_subset_iff, exact le_antisymm_iff }
lemma range_comp_subset_range (f : α → β) (g : β → γ) : range (g ∘ f) ⊆ range g :=
by rw range_comp; apply image_subset_range
lemma range_nonempty_iff_nonempty : (range f).nonempty ↔ nonempty ι :=
⟨λ ⟨y, x, hxy⟩, ⟨x⟩, λ ⟨x⟩, ⟨f x, mem_range_self x⟩⟩
lemma range_nonempty [h : nonempty ι] (f : ι → α) : (range f).nonempty :=
range_nonempty_iff_nonempty.2 h
@[simp] lemma range_eq_empty_iff {f : ι → α} : range f = ∅ ↔ is_empty ι :=
by rw [← not_nonempty_iff, ← range_nonempty_iff_nonempty, not_nonempty_iff_eq_empty]
lemma range_eq_empty [is_empty ι] (f : ι → α) : range f = ∅ := range_eq_empty_iff.2 ‹_›
instance [nonempty ι] (f : ι → α) : nonempty (range f) := (range_nonempty f).to_subtype
@[simp] lemma image_union_image_compl_eq_range (f : α → β) :
(f '' s) ∪ (f '' sᶜ) = range f :=
by rw [← image_union, ← image_univ, ← union_compl_self]
theorem image_preimage_eq_inter_range {f : α → β} {t : set β} :
f '' (f ⁻¹' t) = t ∩ range f :=
ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq ▸ ⟨hx, mem_range_self _⟩,
assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq ▸ mem_image_of_mem f $
show y ∈ f ⁻¹' t, by simp [preimage, h_eq, hx]⟩
lemma image_preimage_eq_of_subset {f : α → β} {s : set β} (hs : s ⊆ range f) :
f '' (f ⁻¹' s) = s :=
by rw [image_preimage_eq_inter_range, inter_eq_self_of_subset_left hs]
instance set.can_lift [can_lift α β] : can_lift (set α) (set β) :=
{ coe := λ s, can_lift.coe '' s,
cond := λ s, ∀ x ∈ s, can_lift.cond β x,
prf := λ s hs, ⟨can_lift.coe ⁻¹' s, image_preimage_eq_of_subset $
λ x hx, can_lift.prf _ (hs x hx)⟩ }
lemma image_preimage_eq_iff {f : α → β} {s : set β} : f '' (f ⁻¹' s) = s ↔ s ⊆ range f :=
⟨by { intro h, rw [← h], apply image_subset_range }, image_preimage_eq_of_subset⟩
lemma preimage_subset_preimage_iff {s t : set α} {f : β → α} (hs : s ⊆ range f) :
f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t :=
begin
split,
{ intros h x hx, rcases hs hx with ⟨y, rfl⟩, exact h hx },
intros h x, apply h
end
lemma preimage_eq_preimage' {s t : set α} {f : β → α} (hs : s ⊆ range f) (ht : t ⊆ range f) :
f ⁻¹' s = f ⁻¹' t ↔ s = t :=
begin
split,
{ intro h, apply subset.antisymm, rw [←preimage_subset_preimage_iff hs, h],
rw [←preimage_subset_preimage_iff ht, h] },
rintro rfl, refl
end
@[simp] theorem preimage_inter_range {f : α → β} {s : set β} : f ⁻¹' (s ∩ range f) = f ⁻¹' s :=
set.ext $ λ x, and_iff_left ⟨x, rfl⟩
@[simp] theorem preimage_range_inter {f : α → β} {s : set β} : f ⁻¹' (range f ∩ s) = f ⁻¹' s :=
by rw [inter_comm, preimage_inter_range]
theorem preimage_image_preimage {f : α → β} {s : set β} :
f ⁻¹' (f '' (f ⁻¹' s)) = f ⁻¹' s :=
by rw [image_preimage_eq_inter_range, preimage_inter_range]
@[simp] theorem quot_mk_range_eq [setoid α] : range (λx : α, ⟦x⟧) = univ :=
range_iff_surjective.2 quot.exists_rep
lemma range_const_subset {c : α} : range (λx:ι, c) ⊆ {c} :=
range_subset_iff.2 $ λ x, rfl
@[simp] lemma range_const : ∀ [nonempty ι] {c : α}, range (λx:ι, c) = {c}
| ⟨x⟩ c := subset.antisymm range_const_subset $
assume y hy, (mem_singleton_iff.1 hy).symm ▸ mem_range_self x
lemma image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap :=
image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse
theorem preimage_singleton_nonempty {f : α → β} {y : β} :
(f ⁻¹' {y}).nonempty ↔ y ∈ range f :=
iff.rfl
theorem preimage_singleton_eq_empty {f : α → β} {y : β} :
f ⁻¹' {y} = ∅ ↔ y ∉ range f :=
not_nonempty_iff_eq_empty.symm.trans preimage_singleton_nonempty.not
lemma range_subset_singleton {f : ι → α} {x : α} : range f ⊆ {x} ↔ f = const ι x :=
by simp [range_subset_iff, funext_iff, mem_singleton]
lemma image_compl_preimage {f : α → β} {s : set β} : f '' ((f ⁻¹' s)ᶜ) = range f \ s :=
by rw [compl_eq_univ_diff, image_diff_preimage, image_univ]
@[simp] theorem range_sigma_mk {β : α → Type*} (a : α) :
range (sigma.mk a : β a → Σ a, β a) = sigma.fst ⁻¹' {a} :=
begin
apply subset.antisymm,
{ rintros _ ⟨b, rfl⟩, simp },
{ rintros ⟨x, y⟩ (rfl|_),
exact mem_range_self y }
end
/-- Any map `f : ι → β` factors through a map `range_factorization f : ι → range f`. -/
def range_factorization (f : ι → β) : ι → range f :=
λ i, ⟨f i, mem_range_self i⟩
lemma range_factorization_eq {f : ι → β} :
subtype.val ∘ range_factorization f = f :=
funext $ λ i, rfl
@[simp] lemma range_factorization_coe (f : ι → β) (a : ι) :
(range_factorization f a : β) = f a := rfl
@[simp] lemma coe_comp_range_factorization (f : ι → β) : coe ∘ range_factorization f = f := rfl
lemma surjective_onto_range : surjective (range_factorization f) :=
λ ⟨_, ⟨i, rfl⟩⟩, ⟨i, rfl⟩
lemma image_eq_range (f : α → β) (s : set α) : f '' s = range (λ(x : s), f x) :=
by { ext, split, rintro ⟨x, h1, h2⟩, exact ⟨⟨x, h1⟩, h2⟩, rintro ⟨⟨x, h1⟩, h2⟩, exact ⟨x, h1, h2⟩ }
@[simp] lemma sum.elim_range {α β γ : Type*} (f : α → γ) (g : β → γ) :
range (sum.elim f g) = range f ∪ range g :=
by simp [set.ext_iff, mem_range]
lemma range_ite_subset' {p : Prop} [decidable p] {f g : α → β} :
range (if p then f else g) ⊆ range f ∪ range g :=
begin
by_cases h : p, {rw if_pos h, exact subset_union_left _ _},
{rw if_neg h, exact subset_union_right _ _}
end
lemma range_ite_subset {p : α → Prop} [decidable_pred p] {f g : α → β} :
range (λ x, if p x then f x else g x) ⊆ range f ∪ range g :=
begin
rw range_subset_iff, intro x, by_cases h : p x,
simp [if_pos h, mem_union, mem_range_self],
simp [if_neg h, mem_union, mem_range_self]
end
@[simp] lemma preimage_range (f : α → β) : f ⁻¹' (range f) = univ :=
eq_univ_of_forall mem_range_self
/-- The range of a function from a `unique` type contains just the
function applied to its single value. -/
lemma range_unique [h : unique ι] : range f = {f default} :=
begin
ext x,
rw mem_range,
split,
{ rintros ⟨i, hi⟩,
rw h.uniq i at hi,
exact hi ▸ mem_singleton _ },
{ exact λ h, ⟨default, h.symm⟩ }
end
lemma range_diff_image_subset (f : α → β) (s : set α) :
range f \ f '' s ⊆ f '' sᶜ :=
λ y ⟨⟨x, h₁⟩, h₂⟩, ⟨x, λ h, h₂ ⟨x, h, h₁⟩, h₁⟩
lemma range_diff_image {f : α → β} (H : injective f) (s : set α) :
range f \ f '' s = f '' sᶜ :=
subset.antisymm (range_diff_image_subset f s) $ λ y ⟨x, hx, hy⟩, hy ▸
⟨mem_range_self _, λ ⟨x', hx', eq⟩, hx $ H eq ▸ hx'⟩
/-- We can use the axiom of choice to pick a preimage for every element of `range f`. -/
noncomputable def range_splitting (f : α → β) : range f → α := λ x, x.2.some
-- This can not be a `@[simp]` lemma because the head of the left hand side is a variable.
lemma apply_range_splitting (f : α → β) (x : range f) : f (range_splitting f x) = x :=
x.2.some_spec
attribute [irreducible] range_splitting
@[simp] lemma comp_range_splitting (f : α → β) : f ∘ range_splitting f = coe :=
by { ext, simp only [function.comp_app], apply apply_range_splitting, }
-- When `f` is injective, see also `equiv.of_injective`.
lemma left_inverse_range_splitting (f : α → β) :
left_inverse (range_factorization f) (range_splitting f) :=
λ x, by { ext, simp only [range_factorization_coe], apply apply_range_splitting, }
lemma range_splitting_injective (f : α → β) : injective (range_splitting f) :=
(left_inverse_range_splitting f).injective
lemma right_inverse_range_splitting {f : α → β} (h : injective f) :
right_inverse (range_factorization f) (range_splitting f) :=
(left_inverse_range_splitting f).right_inverse_of_injective $
λ x y hxy, h $ subtype.ext_iff.1 hxy
lemma preimage_range_splitting {f : α → β} (hf : injective f) :
preimage (range_splitting f) = image (range_factorization f) :=
(image_eq_preimage_of_inverse (right_inverse_range_splitting hf)
(left_inverse_range_splitting f)).symm
lemma is_compl_range_some_none (α : Type*) :
is_compl (range (some : α → option α)) {none} :=
⟨λ x ⟨⟨a, ha⟩, (hn : x = none)⟩, option.some_ne_none _ (ha.trans hn),
λ x hx, option.cases_on x (or.inr rfl) (λ x, or.inl $ mem_range_self _)⟩
@[simp] lemma compl_range_some (α : Type*) :
(range (some : α → option α))ᶜ = {none} :=
(is_compl_range_some_none α).compl_eq
@[simp] lemma range_some_inter_none (α : Type*) : range (some : α → option α) ∩ {none} = ∅ :=
(is_compl_range_some_none α).inf_eq_bot
@[simp] lemma range_some_union_none (α : Type*) : range (some : α → option α) ∪ {none} = univ :=
(is_compl_range_some_none α).sup_eq_top
end range
end set
open set
namespace function
variables {ι : Sort*} {α : Type*} {β : Type*} {f : α → β}
lemma surjective.preimage_injective (hf : surjective f) : injective (preimage f) :=
assume s t, (preimage_eq_preimage hf).1
lemma injective.preimage_image (hf : injective f) (s : set α) : f ⁻¹' (f '' s) = s :=
preimage_image_eq s hf
lemma injective.preimage_surjective (hf : injective f) : surjective (preimage f) :=
by { intro s, use f '' s, rw hf.preimage_image }
lemma injective.subsingleton_image_iff (hf : injective f) {s : set α} :
(f '' s).subsingleton ↔ s.subsingleton :=
⟨subsingleton_of_image hf s, λ h, h.image f⟩
lemma surjective.image_preimage (hf : surjective f) (s : set β) : f '' (f ⁻¹' s) = s :=
image_preimage_eq s hf
lemma surjective.image_surjective (hf : surjective f) : surjective (image f) :=
by { intro s, use f ⁻¹' s, rw hf.image_preimage }
lemma surjective.nonempty_preimage (hf : surjective f) {s : set β} :
(f ⁻¹' s).nonempty ↔ s.nonempty :=
by rw [← nonempty_image_iff, hf.image_preimage]
lemma injective.image_injective (hf : injective f) : injective (image f) :=
by { intros s t h, rw [←preimage_image_eq s hf, ←preimage_image_eq t hf, h] }
lemma surjective.preimage_subset_preimage_iff {s t : set β} (hf : surjective f) :
f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t :=
by { apply preimage_subset_preimage_iff, rw [hf.range_eq], apply subset_univ }
lemma surjective.range_comp {ι' : Sort*} {f : ι → ι'} (hf : surjective f) (g : ι' → α) :
range (g ∘ f) = range g :=
ext $ λ y, (@surjective.exists _ _ _ hf (λ x, g x = y)).symm
lemma injective.nonempty_apply_iff {f : set α → set β} (hf : injective f)
(h2 : f ∅ = ∅) {s : set α} : (f s).nonempty ↔ s.nonempty :=
by rw [← ne_empty_iff_nonempty, ← h2, ← ne_empty_iff_nonempty, hf.ne_iff]
lemma injective.mem_range_iff_exists_unique (hf : injective f) {b : β} :
b ∈ range f ↔ ∃! a, f a = b :=
⟨λ ⟨a, h⟩, ⟨a, h, λ a' ha, hf (ha.trans h.symm)⟩, exists_unique.exists⟩
lemma injective.exists_unique_of_mem_range (hf : injective f) {b : β} (hb : b ∈ range f) :
∃! a, f a = b :=
hf.mem_range_iff_exists_unique.mp hb
theorem injective.compl_image_eq (hf : injective f) (s : set α) :
(f '' s)ᶜ = f '' sᶜ ∪ (range f)ᶜ :=
begin
ext y,
rcases em (y ∈ range f) with ⟨x, rfl⟩|hx,
{ simp [hf.eq_iff] },
{ rw [mem_range, not_exists] at hx,
simp [hx] }
end
lemma left_inverse.image_image {g : β → α} (h : left_inverse g f) (s : set α) :
g '' (f '' s) = s :=
by rw [← image_comp, h.comp_eq_id, image_id]
lemma left_inverse.preimage_preimage {g : β → α} (h : left_inverse g f) (s : set α) :
f ⁻¹' (g ⁻¹' s) = s :=
by rw [← preimage_comp, h.comp_eq_id, preimage_id]
end function
open function
lemma option.injective_iff {α β} {f : option α → β} :
injective f ↔ injective (f ∘ some) ∧ f none ∉ range (f ∘ some) :=
begin
simp only [mem_range, not_exists, (∘)],
refine ⟨λ hf, ⟨hf.comp (option.some_injective _), λ x, hf.ne $ option.some_ne_none _⟩, _⟩,
rintro ⟨h_some, h_none⟩ (_|a) (_|b) hab,
exacts [rfl, (h_none _ hab.symm).elim, (h_none _ hab).elim, congr_arg some (h_some hab)]
end
/-! ### Image and preimage on subtypes -/
namespace subtype
variable {α : Type*}
lemma coe_image {p : α → Prop} {s : set (subtype p)} :
coe '' s = {x | ∃h : p x, (⟨x, h⟩ : subtype p) ∈ s} :=
set.ext $ assume a,
⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq ▸ ⟨ha', in_s⟩,
assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩
@[simp] lemma coe_image_of_subset {s t : set α} (h : t ⊆ s) : coe '' {x : ↥s | ↑x ∈ t} = t :=
begin
ext x,
rw set.mem_image,
exact ⟨λ ⟨x', hx', hx⟩, hx ▸ hx', λ hx, ⟨⟨x, h hx⟩, hx, rfl⟩⟩,
end
lemma range_coe {s : set α} :
range (coe : s → α) = s :=
by { rw ← set.image_univ, simp [-set.image_univ, coe_image] }
/-- A variant of `range_coe`. Try to use `range_coe` if possible.
This version is useful when defining a new type that is defined as the subtype of something.
In that case, the coercion doesn't fire anymore. -/
lemma range_val {s : set α} :
range (subtype.val : s → α) = s :=
range_coe
/-- We make this the simp lemma instead of `range_coe`. The reason is that if we write
for `s : set α` the function `coe : s → α`, then the inferred implicit arguments of `coe` are
`coe α (λ x, x ∈ s)`. -/
@[simp] lemma range_coe_subtype {p : α → Prop} :
range (coe : subtype p → α) = {x | p x} :=
range_coe
@[simp] lemma coe_preimage_self (s : set α) : (coe : s → α) ⁻¹' s = univ :=
by rw [← preimage_range (coe : s → α), range_coe]
lemma range_val_subtype {p : α → Prop} :
range (subtype.val : subtype p → α) = {x | p x} :=
range_coe
theorem coe_image_subset (s : set α) (t : set s) : coe '' t ⊆ s :=
λ x ⟨y, yt, yvaleq⟩, by rw ←yvaleq; exact y.property
theorem coe_image_univ (s : set α) : (coe : s → α) '' set.univ = s :=
image_univ.trans range_coe
@[simp] theorem image_preimage_coe (s t : set α) :
(coe : s → α) '' (coe ⁻¹' t) = t ∩ s :=
image_preimage_eq_inter_range.trans $ congr_arg _ range_coe
theorem image_preimage_val (s t : set α) :
(subtype.val : s → α) '' (subtype.val ⁻¹' t) = t ∩ s :=
image_preimage_coe s t
theorem preimage_coe_eq_preimage_coe_iff {s t u : set α} :
((coe : s → α) ⁻¹' t = coe ⁻¹' u) ↔ t ∩ s = u ∩ s :=
begin
rw [←image_preimage_coe, ←image_preimage_coe],
split, { intro h, rw h },
intro h, exact coe_injective.image_injective h
end
theorem preimage_val_eq_preimage_val_iff (s t u : set α) :
((subtype.val : s → α) ⁻¹' t = subtype.val ⁻¹' u) ↔ (t ∩ s = u ∩ s) :=
preimage_coe_eq_preimage_coe_iff
lemma exists_set_subtype {t : set α} (p : set α → Prop) :
(∃(s : set t), p (coe '' s)) ↔ ∃(s : set α), s ⊆ t ∧ p s :=
begin
split,
{ rintro ⟨s, hs⟩, refine ⟨coe '' s, _, hs⟩,
convert image_subset_range _ _, rw [range_coe] },
rintro ⟨s, hs₁, hs₂⟩, refine ⟨coe ⁻¹' s, _⟩,
rw [image_preimage_eq_of_subset], exact hs₂, rw [range_coe], exact hs₁
end
lemma preimage_coe_nonempty {s t : set α} : ((coe : s → α) ⁻¹' t).nonempty ↔ (s ∩ t).nonempty :=
by rw [inter_comm, ← image_preimage_coe, nonempty_image_iff]
lemma preimage_coe_eq_empty {s t : set α} : (coe : s → α) ⁻¹' t = ∅ ↔ s ∩ t = ∅ :=
by simp only [← not_nonempty_iff_eq_empty, preimage_coe_nonempty]
@[simp] lemma preimage_coe_compl (s : set α) : (coe : s → α) ⁻¹' sᶜ = ∅ :=
preimage_coe_eq_empty.2 (inter_compl_self s)
@[simp] lemma preimage_coe_compl' (s : set α) : (coe : sᶜ → α) ⁻¹' s = ∅ :=
preimage_coe_eq_empty.2 (compl_inter_self s)
end subtype
namespace set
/-! ### Lemmas about `inclusion`, the injection of subtypes induced by `⊆` -/
section inclusion
variable {α : Type*}
/-- `inclusion` is the "identity" function between two subsets `s` and `t`, where `s ⊆ t` -/
def inclusion {s t : set α} (h : s ⊆ t) : s → t :=
λ x : s, (⟨x, h x.2⟩ : t)
@[simp] lemma inclusion_self {s : set α} (x : s) : inclusion subset.rfl x = x :=
by { cases x, refl }
@[simp] lemma inclusion_right {s t : set α} (h : s ⊆ t) (x : t) (m : (x : α) ∈ s) :
inclusion h ⟨x, m⟩ = x :=
by { cases x, refl }
@[simp] lemma inclusion_inclusion {s t u : set α} (hst : s ⊆ t) (htu : t ⊆ u)
(x : s) : inclusion htu (inclusion hst x) = inclusion (set.subset.trans hst htu) x :=
by { cases x, refl }
@[simp] lemma coe_inclusion {s t : set α} (h : s ⊆ t) (x : s) :
(inclusion h x : α) = (x : α) := rfl
lemma inclusion_injective {s t : set α} (h : s ⊆ t) :
function.injective (inclusion h)
| ⟨_, _⟩ ⟨_, _⟩ := subtype.ext_iff_val.2 ∘ subtype.ext_iff_val.1
@[simp] lemma range_inclusion {s t : set α} (h : s ⊆ t) :
range (inclusion h) = {x : t | (x:α) ∈ s} :=
by { ext ⟨x, hx⟩, simp [inclusion] }
lemma eq_of_inclusion_surjective {s t : set α} {h : s ⊆ t}
(h_surj : function.surjective (inclusion h)) : s = t :=
begin
rw [← range_iff_surjective, range_inclusion, eq_univ_iff_forall] at h_surj,
exact set.subset.antisymm h (λ x hx, h_surj ⟨x, hx⟩)
end
end inclusion
/-! ### Injectivity and surjectivity lemmas for image and preimage -/
section image_preimage
variables {α : Type u} {β : Type v} {f : α → β}
@[simp]
lemma preimage_injective : injective (preimage f) ↔ surjective f :=
begin
refine ⟨λ h y, _, surjective.preimage_injective⟩,
obtain ⟨x, hx⟩ : (f ⁻¹' {y}).nonempty,
{ rw [h.nonempty_apply_iff preimage_empty], apply singleton_nonempty },
exact ⟨x, hx⟩
end
@[simp]
lemma preimage_surjective : surjective (preimage f) ↔ injective f :=
begin
refine ⟨λ h x x' hx, _, injective.preimage_surjective⟩,
cases h {x} with s hs, have := mem_singleton x,
rwa [← hs, mem_preimage, hx, ← mem_preimage, hs, mem_singleton_iff, eq_comm] at this
end
@[simp] lemma image_surjective : surjective (image f) ↔ surjective f :=
begin
refine ⟨λ h y, _, surjective.image_surjective⟩,
cases h {y} with s hs,
have := mem_singleton y, rw [← hs] at this, rcases this with ⟨x, h1x, h2x⟩,
exact ⟨x, h2x⟩
end
@[simp] lemma image_injective : injective (image f) ↔ injective f :=
begin
refine ⟨λ h x x' hx, _, injective.image_injective⟩,
rw [← singleton_eq_singleton_iff], apply h,
rw [image_singleton, image_singleton, hx]
end
lemma preimage_eq_iff_eq_image {f : α → β} (hf : bijective f) {s t} :
f ⁻¹' s = t ↔ s = f '' t :=
by rw [← image_eq_image hf.1, hf.2.image_preimage]
lemma eq_preimage_iff_image_eq {f : α → β} (hf : bijective f) {s t} :
s = f ⁻¹' t ↔ f '' s = t :=
by rw [← image_eq_image hf.1, hf.2.image_preimage]
end image_preimage
/-! ### Lemmas about images of binary and ternary functions -/
section n_ary_image
variables {α β γ δ ε : Type*} {f f' : α → β → γ} {g g' : α → β → γ → δ}
variables {s s' : set α} {t t' : set β} {u u' : set γ} {a a' : α} {b b' : β} {c c' : γ} {d d' : δ}
/-- The image of a binary function `f : α → β → γ` as a function `set α → set β → set γ`.
Mathematically this should be thought of as the image of the corresponding function `α × β → γ`.
-/
def image2 (f : α → β → γ) (s : set α) (t : set β) : set γ :=
{c | ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c }
lemma mem_image2_eq : c ∈ image2 f s t = ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := rfl
@[simp] lemma mem_image2 : c ∈ image2 f s t ↔ ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := iff.rfl
lemma mem_image2_of_mem (h1 : a ∈ s) (h2 : b ∈ t) : f a b ∈ image2 f s t :=
⟨a, b, h1, h2, rfl⟩
lemma mem_image2_iff (hf : injective2 f) : f a b ∈ image2 f s t ↔ a ∈ s ∧ b ∈ t :=
⟨ by { rintro ⟨a', b', ha', hb', h⟩, rcases hf h with ⟨rfl, rfl⟩, exact ⟨ha', hb'⟩ },
λ ⟨ha, hb⟩, mem_image2_of_mem ha hb⟩
/-- image2 is monotone with respect to `⊆`. -/
lemma image2_subset (hs : s ⊆ s') (ht : t ⊆ t') : image2 f s t ⊆ image2 f s' t' :=
by { rintro _ ⟨a, b, ha, hb, rfl⟩, exact mem_image2_of_mem (hs ha) (ht hb) }
lemma image2_subset_left (ht : t ⊆ t') : image2 f s t ⊆ image2 f s t' := image2_subset subset.rfl ht
lemma image2_subset_right (hs : s ⊆ s') : image2 f s t ⊆ image2 f s' t :=
image2_subset hs subset.rfl
lemma forall_image2_iff {p : γ → Prop} :
(∀ z ∈ image2 f s t, p z) ↔ ∀ (x ∈ s) (y ∈ t), p (f x y) :=
⟨λ h x hx y hy, h _ ⟨x, y, hx, hy, rfl⟩, λ h z ⟨x, y, hx, hy, hz⟩, hz ▸ h x hx y hy⟩
@[simp] lemma image2_subset_iff {u : set γ} :
image2 f s t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), f x y ∈ u :=
forall_image2_iff
lemma image2_union_left : image2 f (s ∪ s') t = image2 f s t ∪ image2 f s' t :=
begin
ext c, split,
{ rintros ⟨a, b, h1a|h2a, hb, rfl⟩;[left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ },
{ rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, _, ‹_›, rfl⟩; simp [mem_union, *] }
end
lemma image2_union_right : image2 f s (t ∪ t') = image2 f s t ∪ image2 f s t' :=
begin
ext c, split,
{ rintros ⟨a, b, ha, h1b|h2b, rfl⟩;[left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ },
{ rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, ‹_›, _, rfl⟩; simp [mem_union, *] }
end
@[simp] lemma image2_empty_left : image2 f ∅ t = ∅ := ext $ by simp
@[simp] lemma image2_empty_right : image2 f s ∅ = ∅ := ext $ by simp
lemma image2_inter_subset_left : image2 f (s ∩ s') t ⊆ image2 f s t ∩ image2 f s' t :=
by { rintro _ ⟨a, b, ⟨h1a, h2a⟩, hb, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }
lemma image2_inter_subset_right : image2 f s (t ∩ t') ⊆ image2 f s t ∩ image2 f s t' :=
by { rintro _ ⟨a, b, ha, ⟨h1b, h2b⟩, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }
@[simp] lemma image2_singleton_left : image2 f {a} t = f a '' t :=
ext $ λ x, by simp
@[simp] lemma image2_singleton_right : image2 f s {b} = (λ a, f a b) '' s :=
ext $ λ x, by simp
lemma image2_singleton : image2 f {a} {b} = {f a b} := by simp
@[congr] lemma image2_congr (h : ∀ (a ∈ s) (b ∈ t), f a b = f' a b) :
image2 f s t = image2 f' s t :=
by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨a, b, ha, hb, by rw h a ha b hb⟩ }
/-- A common special case of `image2_congr` -/
lemma image2_congr' (h : ∀ a b, f a b = f' a b) : image2 f s t = image2 f' s t :=
image2_congr (λ a _ b _, h a b)
/-- The image of a ternary function `f : α → β → γ → δ` as a function
`set α → set β → set γ → set δ`. Mathematically this should be thought of as the image of the
corresponding function `α × β × γ → δ`.
-/
def image3 (g : α → β → γ → δ) (s : set α) (t : set β) (u : set γ) : set δ :=
{d | ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d }
@[simp] lemma mem_image3 : d ∈ image3 g s t u ↔ ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d :=
iff.rfl
@[congr] lemma image3_congr (h : ∀ (a ∈ s) (b ∈ t) (c ∈ u), g a b c = g' a b c) :
image3 g s t u = image3 g' s t u :=
by { ext x,
split; rintro ⟨a, b, c, ha, hb, hc, rfl⟩; exact ⟨a, b, c, ha, hb, hc, by rw h a ha b hb c hc⟩ }
/-- A common special case of `image3_congr` -/
lemma image3_congr' (h : ∀ a b c, g a b c = g' a b c) : image3 g s t u = image3 g' s t u :=
image3_congr (λ a _ b _ c _, h a b c)
lemma image2_image2_left (f : δ → γ → ε) (g : α → β → δ) :
image2 f (image2 g s t) u = image3 (λ a b c, f (g a b) c) s t u :=
begin
ext, split,
{ rintro ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ },
{ rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩ }
end
lemma image2_image2_right (f : α → δ → ε) (g : β → γ → δ) :
image2 f s (image2 g t u) = image3 (λ a b c, f a (g b c)) s t u :=
begin
ext, split,
{ rintro ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ },
{ rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩ }
end
lemma image2_assoc {ε'} {f : δ → γ → ε} {g : α → β → δ} {f' : α → ε' → ε} {g' : β → γ → ε'}
(h_assoc : ∀ a b c, f (g a b) c = f' a (g' b c)) :
image2 f (image2 g s t) u = image2 f' s (image2 g' t u) :=
by simp only [image2_image2_left, image2_image2_right, h_assoc]
lemma image_image2 (f : α → β → γ) (g : γ → δ) :
g '' image2 f s t = image2 (λ a b, g (f a b)) s t :=
begin
ext, split,
{ rintro ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ },
{ rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩ }
end
lemma image2_image_left (f : γ → β → δ) (g : α → γ) :
image2 f (g '' s) t = image2 (λ a b, f (g a) b) s t :=
begin
ext, split,
{ rintro ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ },
{ rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩ }
end
lemma image2_image_right (f : α → γ → δ) (g : β → γ) :
image2 f s (g '' t) = image2 (λ a b, f a (g b)) s t :=
begin
ext, split,
{ rintro ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ },
{ rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩ }
end
lemma image2_swap (f : α → β → γ) (s : set α) (t : set β) :
image2 f s t = image2 (λ a b, f b a) t s :=
by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨b, a, hb, ha, rfl⟩ }
@[simp] lemma image2_left (h : t.nonempty) : image2 (λ x y, x) s t = s :=
by simp [nonempty_def.mp h, ext_iff]
@[simp] lemma image2_right (h : s.nonempty) : image2 (λ x y, y) s t = t :=
by simp [nonempty_def.mp h, ext_iff]
lemma nonempty.image2 (hs : s.nonempty) (ht : t.nonempty) : (image2 f s t).nonempty :=
by { cases hs with a ha, cases ht with b hb, exact ⟨f a b, ⟨a, b, ha, hb, rfl⟩⟩ }
end n_ary_image
end set
namespace subsingleton
variables {α : Type*} [subsingleton α]
lemma eq_univ_of_nonempty {s : set α} : s.nonempty → s = univ :=
λ ⟨x, hx⟩, eq_univ_of_forall $ λ y, subsingleton.elim x y ▸ hx
@[elab_as_eliminator]
lemma set_cases {p : set α → Prop} (h0 : p ∅) (h1 : p univ) (s) : p s :=
s.eq_empty_or_nonempty.elim (λ h, h.symm ▸ h0) $ λ h, (eq_univ_of_nonempty h).symm ▸ h1
lemma mem_iff_nonempty {α : Type*} [subsingleton α] {s : set α} {x : α} :
x ∈ s ↔ s.nonempty :=
⟨λ hx, ⟨x, hx⟩, λ ⟨y, hy⟩, subsingleton.elim y x ▸ hy⟩
end subsingleton
/-! ### Decidability instances for sets -/
namespace set
variables {α : Type u} (s t : set α) (a : α)
instance decidable_sdiff [decidable (a ∈ s)] [decidable (a ∈ t)] : decidable (a ∈ s \ t) :=
(by apply_instance : decidable (a ∈ s ∧ a ∉ t))
instance decidable_inter [decidable (a ∈ s)] [decidable (a ∈ t)] : decidable (a ∈ s ∩ t) :=
(by apply_instance : decidable (a ∈ s ∧ a ∈ t))
instance decidable_union [decidable (a ∈ s)] [decidable (a ∈ t)] : decidable (a ∈ s ∪ t) :=
(by apply_instance : decidable (a ∈ s ∨ a ∈ t))
instance decidable_compl [decidable (a ∈ s)] : decidable (a ∈ sᶜ) :=
(by apply_instance : decidable (a ∉ s))
instance decidable_emptyset : decidable_pred (∈ (∅ : set α)) :=
λ _, decidable.is_false (by simp)
instance decidable_univ : decidable_pred (∈ (set.univ : set α)) :=
λ _, decidable.is_true (by simp)
instance decidable_set_of (p : α → Prop) [decidable (p a)] : decidable (a ∈ {a | p a}) :=
by assumption
end set
|
8a2914ecbd16f0591467ded577b04bb27595241a
|
c777c32c8e484e195053731103c5e52af26a25d1
|
/src/geometry/euclidean/angle/unoriented/affine.lean
|
8b4036ae625b1c380439d1783b8324be49c7877f
|
[
"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
| 23,481
|
lean
|
/-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers, Manuel Candales
-/
import analysis.convex.between
import geometry.euclidean.angle.unoriented.basic
/-!
# Angles between points
This file defines unoriented angles in Euclidean affine spaces.
## Main definitions
* `euclidean_geometry.angle`, with notation `∠`, is the undirected angle determined by three
points.
-/
noncomputable theory
open_locale big_operators
open_locale real
open_locale real_inner_product_space
namespace euclidean_geometry
open inner_product_geometry
variables {V : Type*} {P : Type*}
[normed_add_comm_group V] [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P]
include V
/-- The undirected angle at `p2` between the line segments to `p1` and
`p3`. If either of those points equals `p2`, this is π/2. Use
`open_locale euclidean_geometry` to access the `∠ p1 p2 p3`
notation. -/
def angle (p1 p2 p3 : P) : ℝ := angle (p1 -ᵥ p2 : V) (p3 -ᵥ p2)
localized "notation (name := angle) `∠` := euclidean_geometry.angle" in euclidean_geometry
lemma continuous_at_angle {x : P × P × P} (hx12 : x.1 ≠ x.2.1) (hx32 : x.2.2 ≠ x.2.1) :
continuous_at (λ y : P × P × P, ∠ y.1 y.2.1 y.2.2) x :=
begin
let f : P × P × P → V × V := λ y, (y.1 -ᵥ y.2.1, y.2.2 -ᵥ y.2.1),
have hf1 : (f x).1 ≠ 0, by simp [hx12],
have hf2 : (f x).2 ≠ 0, by simp [hx32],
exact (inner_product_geometry.continuous_at_angle hf1 hf2).comp
((continuous_fst.vsub continuous_snd.fst).prod_mk
(continuous_snd.snd.vsub continuous_snd.fst)).continuous_at
end
@[simp] lemma _root_.affine_isometry.angle_map {V₂ P₂ : Type*}
[normed_add_comm_group V₂] [inner_product_space ℝ V₂]
[metric_space P₂] [normed_add_torsor V₂ P₂] (f : P →ᵃⁱ[ℝ] P₂) (p₁ p₂ p₃ : P) :
∠ (f p₁) (f p₂) (f p₃) = ∠ p₁ p₂ p₃ :=
by simp_rw [angle, ←affine_isometry.map_vsub, linear_isometry.angle_map]
@[simp, norm_cast] lemma _root_.affine_subspace.angle_coe {s : affine_subspace ℝ P}
(p₁ p₂ p₃ : s) :
by haveI : nonempty s := ⟨p₁⟩; exact ∠ (p₁ : P) (p₂ : P) (p₃ : P) = ∠ p₁ p₂ p₃ :=
by haveI : nonempty s := ⟨p₁⟩; exact s.subtypeₐᵢ.angle_map p₁ p₂ p₃
/-- Angles are translation invariant -/
@[simp] lemma angle_const_vadd (v : V) (p₁ p₂ p₃ : P) :
∠ (v +ᵥ p₁) (v +ᵥ p₂) (v +ᵥ p₃) = ∠ p₁ p₂ p₃ :=
(affine_isometry_equiv.const_vadd ℝ P v).to_affine_isometry.angle_map _ _ _
/-- Angles are translation invariant -/
@[simp] lemma angle_vadd_const (v₁ v₂ v₃ : V) (p : P) :
∠ (v₁ +ᵥ p) (v₂ +ᵥ p) (v₃ +ᵥ p) = ∠ v₁ v₂ v₃ :=
(affine_isometry_equiv.vadd_const ℝ p).to_affine_isometry.angle_map _ _ _
/-- Angles are translation invariant -/
@[simp] lemma angle_const_vsub (p p₁ p₂ p₃ : P) : ∠ (p -ᵥ p₁) (p -ᵥ p₂) (p -ᵥ p₃) = ∠ p₁ p₂ p₃ :=
(affine_isometry_equiv.const_vsub ℝ p).to_affine_isometry.angle_map _ _ _
/-- Angles are translation invariant -/
@[simp] lemma angle_vsub_const (p₁ p₂ p₃ p : P) : ∠ (p₁ -ᵥ p) (p₂ -ᵥ p) (p₃ -ᵥ p) = ∠ p₁ p₂ p₃ :=
(affine_isometry_equiv.vadd_const ℝ p).symm.to_affine_isometry.angle_map _ _ _
/-- Angles in a vector space are translation invariant -/
@[simp] lemma angle_add_const (v₁ v₂ v₃ : V) (v : V) : ∠ (v₁ + v) (v₂ + v) (v₃ + v) = ∠ v₁ v₂ v₃ :=
angle_vadd_const _ _ _ _
/-- Angles in a vector space are translation invariant -/
@[simp] lemma angle_const_add (v : V) (v₁ v₂ v₃ : V) : ∠ (v + v₁) (v + v₂) (v + v₃) = ∠ v₁ v₂ v₃ :=
angle_const_vadd _ _ _ _
/-- Angles in a vector space are translation invariant -/
@[simp] lemma angle_sub_const (v₁ v₂ v₃ : V) (v : V) : ∠ (v₁ - v) (v₂ - v) (v₃ - v) = ∠ v₁ v₂ v₃ :=
by simpa only [vsub_eq_sub] using angle_vsub_const v₁ v₂ v₃ v
/-- Angles in a vector space are invariant to inversion -/
@[simp] lemma angle_const_sub (v : V) (v₁ v₂ v₃ : V) : ∠ (v - v₁) (v - v₂) (v - v₃) = ∠ v₁ v₂ v₃ :=
by simpa only [vsub_eq_sub] using angle_const_vsub _ _ _ _
/-- Angles in a vector space are invariant to inversion -/
@[simp] lemma angle_neg (v₁ v₂ v₃ : V) : ∠ (-v₁) (-v₂) (-v₃) = ∠ v₁ v₂ v₃ :=
by simpa only [zero_sub] using angle_const_sub 0 v₁ v₂ v₃
/-- The angle at a point does not depend on the order of the other two
points. -/
lemma angle_comm (p1 p2 p3 : P) : ∠ p1 p2 p3 = ∠ p3 p2 p1 :=
angle_comm _ _
/-- The angle at a point is nonnegative. -/
lemma angle_nonneg (p1 p2 p3 : P) : 0 ≤ ∠ p1 p2 p3 :=
angle_nonneg _ _
/-- The angle at a point is at most π. -/
lemma angle_le_pi (p1 p2 p3 : P) : ∠ p1 p2 p3 ≤ π :=
angle_le_pi _ _
/-- The angle ∠AAB at a point. -/
lemma angle_eq_left (p1 p2 : P) : ∠ p1 p1 p2 = π / 2 :=
begin
unfold angle,
rw vsub_self,
exact angle_zero_left _
end
/-- The angle ∠ABB at a point. -/
lemma angle_eq_right (p1 p2 : P) : ∠ p1 p2 p2 = π / 2 :=
by rw [angle_comm, angle_eq_left]
/-- The angle ∠ABA at a point. -/
lemma angle_eq_of_ne {p1 p2 : P} (h : p1 ≠ p2) : ∠ p1 p2 p1 = 0 :=
angle_self (λ he, h (vsub_eq_zero_iff_eq.1 he))
/-- If the angle ∠ABC at a point is π, the angle ∠BAC is 0. -/
lemma angle_eq_zero_of_angle_eq_pi_left {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) :
∠ p2 p1 p3 = 0 :=
begin
unfold angle at h,
rw angle_eq_pi_iff at h,
rcases h with ⟨hp1p2, ⟨r, ⟨hr, hpr⟩⟩⟩,
unfold angle,
rw angle_eq_zero_iff,
rw [←neg_vsub_eq_vsub_rev, neg_ne_zero] at hp1p2,
use [hp1p2, -r + 1, add_pos (neg_pos_of_neg hr) zero_lt_one],
rw [add_smul, ←neg_vsub_eq_vsub_rev p1 p2, smul_neg],
simp [←hpr]
end
/-- If the angle ∠ABC at a point is π, the angle ∠BCA is 0. -/
lemma angle_eq_zero_of_angle_eq_pi_right {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) :
∠ p2 p3 p1 = 0 :=
begin
rw angle_comm at h,
exact angle_eq_zero_of_angle_eq_pi_left h
end
/-- If ∠BCD = π, then ∠ABC = ∠ABD. -/
lemma angle_eq_angle_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) :
∠ p1 p2 p3 = ∠ p1 p2 p4 :=
begin
unfold angle at *,
rcases angle_eq_pi_iff.1 h with ⟨hp2p3, ⟨r, ⟨hr, hpr⟩⟩⟩,
rw [eq_comm],
convert angle_smul_right_of_pos (p1 -ᵥ p2) (p3 -ᵥ p2) (add_pos (neg_pos_of_neg hr) zero_lt_one),
rw [add_smul, ← neg_vsub_eq_vsub_rev p2 p3, smul_neg, neg_smul, ← hpr],
simp
end
/-- If ∠BCD = π, then ∠ACB + ∠ACD = π. -/
lemma angle_add_angle_eq_pi_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) :
∠ p1 p3 p2 + ∠ p1 p3 p4 = π :=
begin
unfold angle at h,
rw [angle_comm p1 p3 p2, angle_comm p1 p3 p4],
unfold angle,
exact angle_add_angle_eq_pi_of_angle_eq_pi _ h
end
/-- Vertical Angles Theorem: angles opposite each other, formed by two intersecting straight
lines, are equal. -/
lemma angle_eq_angle_of_angle_eq_pi_of_angle_eq_pi {p1 p2 p3 p4 p5 : P}
(hapc : ∠ p1 p5 p3 = π) (hbpd : ∠ p2 p5 p4 = π) : ∠ p1 p5 p2 = ∠ p3 p5 p4 :=
by linarith [angle_add_angle_eq_pi_of_angle_eq_pi p1 hbpd, angle_comm p4 p5 p1,
angle_add_angle_eq_pi_of_angle_eq_pi p4 hapc, angle_comm p4 p5 p3]
/-- If ∠ABC = π then dist A B ≠ 0. -/
lemma left_dist_ne_zero_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : dist p1 p2 ≠ 0 :=
begin
by_contra heq,
rw [dist_eq_zero] at heq,
rw [heq, angle_eq_left] at h,
exact real.pi_ne_zero (by linarith),
end
/-- If ∠ABC = π then dist C B ≠ 0. -/
lemma right_dist_ne_zero_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : dist p3 p2 ≠ 0 :=
left_dist_ne_zero_of_angle_eq_pi $ (angle_comm _ _ _).trans h
/-- If ∠ABC = π, then (dist A C) = (dist A B) + (dist B C). -/
lemma dist_eq_add_dist_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) :
dist p1 p3 = dist p1 p2 + dist p3 p2 :=
begin
rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right],
exact norm_sub_eq_add_norm_of_angle_eq_pi h,
end
/-- If A ≠ B and C ≠ B then ∠ABC = π if and only if (dist A C) = (dist A B) + (dist B C). -/
lemma dist_eq_add_dist_iff_angle_eq_pi {p1 p2 p3 : P} (hp1p2 : p1 ≠ p2) (hp3p2 : p3 ≠ p2) :
dist p1 p3 = dist p1 p2 + dist p3 p2 ↔ ∠ p1 p2 p3 = π :=
begin
rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right],
exact norm_sub_eq_add_norm_iff_angle_eq_pi
((λ he, hp1p2 (vsub_eq_zero_iff_eq.1 he))) (λ he, hp3p2 (vsub_eq_zero_iff_eq.1 he)),
end
/-- If ∠ABC = 0, then (dist A C) = abs ((dist A B) - (dist B C)). -/
lemma dist_eq_abs_sub_dist_of_angle_eq_zero {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = 0) :
(dist p1 p3) = |(dist p1 p2) - (dist p3 p2)| :=
begin
rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right],
exact norm_sub_eq_abs_sub_norm_of_angle_eq_zero h,
end
/-- If A ≠ B and C ≠ B then ∠ABC = 0 if and only if (dist A C) = abs ((dist A B) - (dist B C)). -/
lemma dist_eq_abs_sub_dist_iff_angle_eq_zero {p1 p2 p3 : P} (hp1p2 : p1 ≠ p2) (hp3p2 : p3 ≠ p2) :
(dist p1 p3) = |(dist p1 p2) - (dist p3 p2)| ↔ ∠ p1 p2 p3 = 0 :=
begin
rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right],
exact norm_sub_eq_abs_sub_norm_iff_angle_eq_zero
((λ he, hp1p2 (vsub_eq_zero_iff_eq.1 he))) (λ he, hp3p2 (vsub_eq_zero_iff_eq.1 he)),
end
/-- If M is the midpoint of the segment AB, then ∠AMB = π. -/
lemma angle_midpoint_eq_pi (p1 p2 : P) (hp1p2 : p1 ≠ p2) : ∠ p1 (midpoint ℝ p1 p2) p2 = π :=
have p2 -ᵥ midpoint ℝ p1 p2 = -(p1 -ᵥ midpoint ℝ p1 p2), by { rw neg_vsub_eq_vsub_rev, simp },
by simp [angle, this, hp1p2, -zero_lt_one]
/-- If M is the midpoint of the segment AB and C is the same distance from A as it is from B
then ∠CMA = π / 2. -/
lemma angle_left_midpoint_eq_pi_div_two_of_dist_eq {p1 p2 p3 : P} (h : dist p3 p1 = dist p3 p2) :
∠ p3 (midpoint ℝ p1 p2) p1 = π / 2 :=
begin
let m : P := midpoint ℝ p1 p2,
have h1 : p3 -ᵥ p1 = (p3 -ᵥ m) - (p1 -ᵥ m) := (vsub_sub_vsub_cancel_right p3 p1 m).symm,
have h2 : p3 -ᵥ p2 = (p3 -ᵥ m) + (p1 -ᵥ m),
{ rw [left_vsub_midpoint, ← midpoint_vsub_right, vsub_add_vsub_cancel] },
rw [dist_eq_norm_vsub V p3 p1, dist_eq_norm_vsub V p3 p2, h1, h2] at h,
exact (norm_add_eq_norm_sub_iff_angle_eq_pi_div_two (p3 -ᵥ m) (p1 -ᵥ m)).mp h.symm,
end
/-- If M is the midpoint of the segment AB and C is the same distance from A as it is from B
then ∠CMB = π / 2. -/
lemma angle_right_midpoint_eq_pi_div_two_of_dist_eq {p1 p2 p3 : P} (h : dist p3 p1 = dist p3 p2) :
∠ p3 (midpoint ℝ p1 p2) p2 = π / 2 :=
by rw [midpoint_comm p1 p2, angle_left_midpoint_eq_pi_div_two_of_dist_eq h.symm]
/-- If the second of three points is strictly between the other two, the angle at that point
is π. -/
lemma _root_.sbtw.angle₁₂₃_eq_pi {p₁ p₂ p₃ : P} (h : sbtw ℝ p₁ p₂ p₃) : ∠ p₁ p₂ p₃ = π :=
begin
rw [angle, angle_eq_pi_iff],
rcases h with ⟨⟨r, ⟨hr0, hr1⟩, hp₂⟩, hp₂p₁, hp₂p₃⟩,
refine ⟨vsub_ne_zero.2 hp₂p₁.symm, -(1 - r) / r, _⟩,
have hr0' : r ≠ 0,
{ rintro rfl,
rw ←hp₂ at hp₂p₁,
simpa using hp₂p₁ },
have hr1' : r ≠ 1,
{ rintro rfl,
rw ←hp₂ at hp₂p₃,
simpa using hp₂p₃ },
replace hr0 := hr0.lt_of_ne hr0'.symm,
replace hr1 := hr1.lt_of_ne hr1',
refine ⟨div_neg_of_neg_of_pos (left.neg_neg_iff.2 (sub_pos.2 hr1)) hr0, _⟩,
rw [←hp₂, affine_map.line_map_apply, vsub_vadd_eq_vsub_sub, vsub_vadd_eq_vsub_sub, vsub_self,
zero_sub, smul_neg, smul_smul, div_mul_cancel _ hr0', neg_smul, neg_neg, sub_eq_iff_eq_add,
←add_smul, sub_add_cancel, one_smul]
end
/-- If the second of three points is strictly between the other two, the angle at that point
(reversed) is π. -/
lemma _root_.sbtw.angle₃₂₁_eq_pi {p₁ p₂ p₃ : P} (h : sbtw ℝ p₁ p₂ p₃) : ∠ p₃ p₂ p₁ = π :=
by rw [←h.angle₁₂₃_eq_pi, angle_comm]
/-- The angle between three points is π if and only if the second point is strictly between the
other two. -/
lemma angle_eq_pi_iff_sbtw {p₁ p₂ p₃ : P} : ∠ p₁ p₂ p₃ = π ↔ sbtw ℝ p₁ p₂ p₃ :=
begin
refine ⟨_, λ h, h.angle₁₂₃_eq_pi⟩,
rw [angle, angle_eq_pi_iff],
rintro ⟨hp₁p₂, r, hr, hp₃p₂⟩,
refine ⟨⟨1 / (1 - r),
⟨div_nonneg zero_le_one (sub_nonneg.2 (hr.le.trans zero_le_one)),
(div_le_one (sub_pos.2 (hr.trans zero_lt_one))).2 ((le_sub_self_iff 1).2 hr.le)⟩, _⟩,
(vsub_ne_zero.1 hp₁p₂).symm, _⟩,
{ rw ←eq_vadd_iff_vsub_eq at hp₃p₂,
rw [affine_map.line_map_apply, hp₃p₂, vadd_vsub_assoc, ←neg_vsub_eq_vsub_rev p₂ p₁,
smul_neg, ←neg_smul, smul_add, smul_smul, ←add_smul, eq_comm, eq_vadd_iff_vsub_eq],
convert (one_smul ℝ (p₂ -ᵥ p₁)).symm,
field_simp [(sub_pos.2 (hr.trans zero_lt_one)).ne.symm],
abel },
{ rw [ne_comm, ←@vsub_ne_zero V, hp₃p₂, smul_ne_zero_iff],
exact ⟨hr.ne, hp₁p₂⟩ }
end
/-- If the second of three points is weakly between the other two, and not equal to the first,
the angle at the first point is zero. -/
lemma _root_.wbtw.angle₂₁₃_eq_zero_of_ne {p₁ p₂ p₃ : P} (h : wbtw ℝ p₁ p₂ p₃) (hp₂p₁ : p₂ ≠ p₁) :
∠ p₂ p₁ p₃ = 0 :=
begin
rw [angle, angle_eq_zero_iff],
rcases h with ⟨r, ⟨hr0, hr1⟩, rfl⟩,
have hr0' : r ≠ 0, { rintro rfl, simpa using hp₂p₁ },
replace hr0 := hr0.lt_of_ne hr0'.symm,
refine ⟨vsub_ne_zero.2 hp₂p₁, r⁻¹, inv_pos.2 hr0, _⟩,
rw [affine_map.line_map_apply, vadd_vsub_assoc, vsub_self, add_zero, smul_smul,
inv_mul_cancel hr0', one_smul]
end
/-- If the second of three points is strictly between the other two, the angle at the first point
is zero. -/
lemma _root_.sbtw.angle₂₁₃_eq_zero {p₁ p₂ p₃ : P} (h : sbtw ℝ p₁ p₂ p₃) : ∠ p₂ p₁ p₃ = 0 :=
h.wbtw.angle₂₁₃_eq_zero_of_ne h.ne_left
/-- If the second of three points is weakly between the other two, and not equal to the first,
the angle at the first point (reversed) is zero. -/
lemma _root_.wbtw.angle₃₁₂_eq_zero_of_ne {p₁ p₂ p₃ : P} (h : wbtw ℝ p₁ p₂ p₃) (hp₂p₁ : p₂ ≠ p₁) :
∠ p₃ p₁ p₂ = 0 :=
by rw [←h.angle₂₁₃_eq_zero_of_ne hp₂p₁, angle_comm]
/-- If the second of three points is strictly between the other two, the angle at the first point
(reversed) is zero. -/
lemma _root_.sbtw.angle₃₁₂_eq_zero {p₁ p₂ p₃ : P} (h : sbtw ℝ p₁ p₂ p₃) : ∠ p₃ p₁ p₂ = 0 :=
h.wbtw.angle₃₁₂_eq_zero_of_ne h.ne_left
/-- If the second of three points is weakly between the other two, and not equal to the third,
the angle at the third point is zero. -/
lemma _root_.wbtw.angle₂₃₁_eq_zero_of_ne {p₁ p₂ p₃ : P} (h : wbtw ℝ p₁ p₂ p₃) (hp₂p₃ : p₂ ≠ p₃) :
∠ p₂ p₃ p₁ = 0 :=
h.symm.angle₂₁₃_eq_zero_of_ne hp₂p₃
/-- If the second of three points is strictly between the other two, the angle at the third point
is zero. -/
lemma _root_.sbtw.angle₂₃₁_eq_zero {p₁ p₂ p₃ : P} (h : sbtw ℝ p₁ p₂ p₃) : ∠ p₂ p₃ p₁ = 0 :=
h.wbtw.angle₂₃₁_eq_zero_of_ne h.ne_right
/-- If the second of three points is weakly between the other two, and not equal to the third,
the angle at the third point (reversed) is zero. -/
lemma _root_.wbtw.angle₁₃₂_eq_zero_of_ne {p₁ p₂ p₃ : P} (h : wbtw ℝ p₁ p₂ p₃) (hp₂p₃ : p₂ ≠ p₃) :
∠ p₁ p₃ p₂ = 0 :=
h.symm.angle₃₁₂_eq_zero_of_ne hp₂p₃
/-- If the second of three points is strictly between the other two, the angle at the third point
(reversed) is zero. -/
lemma _root_.sbtw.angle₁₃₂_eq_zero {p₁ p₂ p₃ : P} (h : sbtw ℝ p₁ p₂ p₃) : ∠ p₁ p₃ p₂ = 0 :=
h.wbtw.angle₁₃₂_eq_zero_of_ne h.ne_right
/-- The angle between three points is zero if and only if one of the first and third points is
weakly between the other two, and not equal to the second. -/
lemma angle_eq_zero_iff_ne_and_wbtw {p₁ p₂ p₃ : P} :
∠ p₁ p₂ p₃ = 0 ↔ (p₁ ≠ p₂ ∧ wbtw ℝ p₂ p₁ p₃) ∨ (p₃ ≠ p₂ ∧ wbtw ℝ p₂ p₃ p₁) :=
begin
split,
{ rw [angle, angle_eq_zero_iff],
rintro ⟨hp₁p₂, r, hr0, hp₃p₂⟩,
rcases le_or_lt 1 r with hr1 | hr1,
{ refine or.inl ⟨vsub_ne_zero.1 hp₁p₂, r⁻¹, ⟨(inv_pos.2 hr0).le, inv_le_one hr1⟩, _⟩,
rw [affine_map.line_map_apply, hp₃p₂, smul_smul, inv_mul_cancel hr0.ne.symm, one_smul,
vsub_vadd] },
{ refine or.inr ⟨_, r, ⟨hr0.le, hr1.le⟩, _⟩,
{ rw [←@vsub_ne_zero V, hp₃p₂, smul_ne_zero_iff],
exact ⟨hr0.ne.symm, hp₁p₂⟩ },
{ rw [affine_map.line_map_apply, ←hp₃p₂, vsub_vadd] } } },
{ rintro (⟨hp₁p₂, h⟩ | ⟨hp₃p₂, h⟩),
{ exact h.angle₂₁₃_eq_zero_of_ne hp₁p₂ },
{ exact h.angle₃₁₂_eq_zero_of_ne hp₃p₂ } }
end
/-- The angle between three points is zero if and only if one of the first and third points is
strictly between the other two, or those two points are equal but not equal to the second. -/
lemma angle_eq_zero_iff_eq_and_ne_or_sbtw {p₁ p₂ p₃ : P} :
∠ p₁ p₂ p₃ = 0 ↔ (p₁ = p₃ ∧ p₁ ≠ p₂) ∨ sbtw ℝ p₂ p₁ p₃ ∨ sbtw ℝ p₂ p₃ p₁ :=
begin
rw angle_eq_zero_iff_ne_and_wbtw,
by_cases hp₁p₂ : p₁ = p₂, { simp [hp₁p₂] },
by_cases hp₁p₃ : p₁ = p₃, { simp [hp₁p₃] },
by_cases hp₃p₂ : p₃ = p₂, { simp [hp₃p₂] },
simp [hp₁p₂, hp₁p₃, ne.symm hp₁p₃, sbtw, hp₃p₂]
end
/-- Three points are collinear if and only if the first or third point equals the second or the
angle between them is 0 or π. -/
lemma collinear_iff_eq_or_eq_or_angle_eq_zero_or_angle_eq_pi {p₁ p₂ p₃ : P} :
collinear ℝ ({p₁, p₂, p₃} : set P) ↔ p₁ = p₂ ∨ p₃ = p₂ ∨ ∠ p₁ p₂ p₃ = 0 ∨ ∠ p₁ p₂ p₃ = π :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ replace h := h.wbtw_or_wbtw_or_wbtw,
by_cases h₁₂ : p₁ = p₂, { exact or.inl h₁₂ },
by_cases h₃₂ : p₃ = p₂, { exact or.inr (or.inl h₃₂) },
rw [or_iff_right h₁₂, or_iff_right h₃₂],
rcases h with h | h | h,
{ exact or.inr (angle_eq_pi_iff_sbtw.2 ⟨h, ne.symm h₁₂, ne.symm h₃₂⟩) },
{ exact or.inl (h.angle₃₁₂_eq_zero_of_ne h₃₂) },
{ exact or.inl (h.angle₂₃₁_eq_zero_of_ne h₁₂) } },
{ rcases h with rfl | rfl | h | h,
{ simpa using collinear_pair ℝ p₁ p₃ },
{ simpa using collinear_pair ℝ p₁ p₃ },
{ rw angle_eq_zero_iff_ne_and_wbtw at h,
rcases h with ⟨-, h⟩ | ⟨-, h⟩,
{ rw set.insert_comm, exact h.collinear },
{ rw [set.insert_comm, set.pair_comm], exact h.collinear } },
{ rw angle_eq_pi_iff_sbtw at h,
exact h.wbtw.collinear } }
end
/-- If the angle between three points is 0, they are collinear. -/
lemma collinear_of_angle_eq_zero {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = 0) :
collinear ℝ ({p₁, p₂, p₃} : set P) :=
collinear_iff_eq_or_eq_or_angle_eq_zero_or_angle_eq_pi.2 $ or.inr $ or.inr $ or.inl h
/-- If the angle between three points is π, they are collinear. -/
lemma collinear_of_angle_eq_pi {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π) :
collinear ℝ ({p₁, p₂, p₃} : set P) :=
collinear_iff_eq_or_eq_or_angle_eq_zero_or_angle_eq_pi.2 $ or.inr $ or.inr $ or.inr h
/-- If three points are not collinear, the angle between them is nonzero. -/
lemma angle_ne_zero_of_not_collinear {p₁ p₂ p₃ : P} (h : ¬collinear ℝ ({p₁, p₂, p₃} : set P)) :
∠ p₁ p₂ p₃ ≠ 0 :=
mt collinear_of_angle_eq_zero h
/-- If three points are not collinear, the angle between them is not π. -/
lemma angle_ne_pi_of_not_collinear {p₁ p₂ p₃ : P} (h : ¬collinear ℝ ({p₁, p₂, p₃} : set P)) :
∠ p₁ p₂ p₃ ≠ π :=
mt collinear_of_angle_eq_pi h
/-- If three points are not collinear, the angle between them is positive. -/
lemma angle_pos_of_not_collinear {p₁ p₂ p₃ : P} (h : ¬collinear ℝ ({p₁, p₂, p₃} : set P)) :
0 < ∠ p₁ p₂ p₃ :=
(angle_nonneg _ _ _).lt_of_ne (angle_ne_zero_of_not_collinear h).symm
/-- If three points are not collinear, the angle between them is less than π. -/
lemma angle_lt_pi_of_not_collinear {p₁ p₂ p₃ : P} (h : ¬collinear ℝ ({p₁, p₂, p₃} : set P)) :
∠ p₁ p₂ p₃ < π :=
(angle_le_pi _ _ _).lt_of_ne $ angle_ne_pi_of_not_collinear h
/-- The cosine of the angle between three points is 1 if and only if the angle is 0. -/
lemma cos_eq_one_iff_angle_eq_zero {p₁ p₂ p₃ : P} :
real.cos (∠ p₁ p₂ p₃) = 1 ↔ ∠ p₁ p₂ p₃ = 0 :=
cos_eq_one_iff_angle_eq_zero
/-- The cosine of the angle between three points is 0 if and only if the angle is π / 2. -/
lemma cos_eq_zero_iff_angle_eq_pi_div_two {p₁ p₂ p₃ : P} :
real.cos (∠ p₁ p₂ p₃) = 0 ↔ ∠ p₁ p₂ p₃ = π / 2 :=
cos_eq_zero_iff_angle_eq_pi_div_two
/-- The cosine of the angle between three points is -1 if and only if the angle is π. -/
lemma cos_eq_neg_one_iff_angle_eq_pi {p₁ p₂ p₃ : P} :
real.cos (∠ p₁ p₂ p₃) = -1 ↔ ∠ p₁ p₂ p₃ = π :=
cos_eq_neg_one_iff_angle_eq_pi
/-- The sine of the angle between three points is 0 if and only if the angle is 0 or π. -/
lemma sin_eq_zero_iff_angle_eq_zero_or_angle_eq_pi {p₁ p₂ p₃ : P} :
real.sin (∠ p₁ p₂ p₃) = 0 ↔ ∠ p₁ p₂ p₃ = 0 ∨ ∠ p₁ p₂ p₃ = π :=
sin_eq_zero_iff_angle_eq_zero_or_angle_eq_pi
/-- The sine of the angle between three points is 1 if and only if the angle is π / 2. -/
lemma sin_eq_one_iff_angle_eq_pi_div_two {p₁ p₂ p₃ : P} :
real.sin (∠ p₁ p₂ p₃) = 1 ↔ ∠ p₁ p₂ p₃ = π / 2 :=
sin_eq_one_iff_angle_eq_pi_div_two
/-- Three points are collinear if and only if the first or third point equals the second or
the sine of the angle between three points is zero. -/
lemma collinear_iff_eq_or_eq_or_sin_eq_zero {p₁ p₂ p₃ : P} :
collinear ℝ ({p₁, p₂, p₃} : set P) ↔ p₁ = p₂ ∨ p₃ = p₂ ∨ real.sin (∠ p₁ p₂ p₃) = 0 :=
by rw [sin_eq_zero_iff_angle_eq_zero_or_angle_eq_pi,
collinear_iff_eq_or_eq_or_angle_eq_zero_or_angle_eq_pi]
/-- If three points are not collinear, the sine of the angle between them is positive. -/
lemma sin_pos_of_not_collinear {p₁ p₂ p₃ : P} (h : ¬collinear ℝ ({p₁, p₂, p₃} : set P)) :
0 < real.sin (∠ p₁ p₂ p₃) :=
real.sin_pos_of_pos_of_lt_pi (angle_pos_of_not_collinear h) (angle_lt_pi_of_not_collinear h)
/-- If three points are not collinear, the sine of the angle between them is nonzero. -/
lemma sin_ne_zero_of_not_collinear {p₁ p₂ p₃ : P} (h : ¬collinear ℝ ({p₁, p₂, p₃} : set P)) :
real.sin (∠ p₁ p₂ p₃) ≠ 0 :=
ne_of_gt (sin_pos_of_not_collinear h)
/-- If the sine of the angle between three points is 0, they are collinear. -/
lemma collinear_of_sin_eq_zero {p₁ p₂ p₃ : P} (h : real.sin (∠ p₁ p₂ p₃) = 0) :
collinear ℝ ({p₁, p₂, p₃} : set P) :=
imp_of_not_imp_not _ _ sin_ne_zero_of_not_collinear h
end euclidean_geometry
|
0828a4b87fe5c4c3c0e270ae55a85a940296a34b
|
5749d8999a76f3a8fddceca1f6941981e33aaa96
|
/src/data/equiv/algebra.lean
|
ef0dafd5baf37876615ac43a868ecf4af6faa7d4
|
[
"Apache-2.0"
] |
permissive
|
jdsalchow/mathlib
|
13ab43ef0d0515a17e550b16d09bd14b76125276
|
497e692b946d93906900bb33a51fd243e7649406
|
refs/heads/master
| 1,585,819,143,348
| 1,580,072,892,000
| 1,580,072,892,000
| 154,287,128
| 0
| 0
|
Apache-2.0
| 1,540,281,610,000
| 1,540,281,609,000
| null |
UTF-8
|
Lean
| false
| false
| 22,325
|
lean
|
/-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Callum Sutton
-/
import data.equiv.basic algebra.field
/-!
# equivs in the algebraic hierarchy
In the first part there are theorems of the following
form: if `α` has a group structure and `α ≃ β` then `β` has a group structure, and
similarly for monoids, semigroups, rings, integral domains, fields and so on.
In the second part there are extensions of `equiv` called `add_equiv`,
`mul_equiv`, and `ring_equiv`, which are datatypes representing
isomorphisms of add_monoids/add_groups, monoids/groups and rings. We
also introduce the corresponding groups of automorphisms `add_aut`,
`mul_aut`, and `ring_aut`.
## Notations
The extended equivs all have coercions to functions, and the coercions are the canonical
notation when treating the isomorphisms as maps.
## Implementation notes
The fields for `mul_equiv`, `add_equiv`, and `ring_equiv` now avoid
the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated.
Definition of multiplication in the groups of automorphisms agrees
with function composition, multiplication in `equiv.perm`, and
multiplication in `category_theory.End`, not with
`category_theory.comp`.
## Tags
equiv, mul_equiv, add_equiv, ring_equiv, mul_aut, add_aut, ring_aut
-/
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
namespace equiv
section group
variables [group α]
@[to_additive]
protected def mul_left (a : α) : α ≃ α :=
{ to_fun := λx, a * x,
inv_fun := λx, a⁻¹ * x,
left_inv := assume x, show a⁻¹ * (a * x) = x, from inv_mul_cancel_left a x,
right_inv := assume x, show a * (a⁻¹ * x) = x, from mul_inv_cancel_left a x }
@[to_additive]
protected def mul_right (a : α) : α ≃ α :=
{ to_fun := λx, x * a,
inv_fun := λx, x * a⁻¹,
left_inv := assume x, show (x * a) * a⁻¹ = x, from mul_inv_cancel_right x a,
right_inv := assume x, show (x * a⁻¹) * a = x, from inv_mul_cancel_right x a }
@[to_additive]
protected def inv (α) [group α] : α ≃ α :=
{ to_fun := λa, a⁻¹,
inv_fun := λa, a⁻¹,
left_inv := assume a, inv_inv a,
right_inv := assume a, inv_inv a }
end group
section field
variables (α) [field α]
def units_equiv_ne_zero : units α ≃ {a : α | a ≠ 0} :=
⟨λ a, ⟨a.1, units.ne_zero _⟩, λ a, units.mk0 _ a.2, λ ⟨_, _, _, _⟩, units.ext rfl, λ ⟨_, _⟩, rfl⟩
variable {α}
@[simp] lemma coe_units_equiv_ne_zero (a : units α) :
((units_equiv_ne_zero α a) : α) = a := rfl
end field
section instances
variables (e : α ≃ β)
protected def has_zero [has_zero β] : has_zero α := ⟨e.symm 0⟩
lemma zero_def [has_zero β] : @has_zero.zero _ (equiv.has_zero e) = e.symm 0 := rfl
protected def has_one [has_one β] : has_one α := ⟨e.symm 1⟩
lemma one_def [has_one β] : @has_one.one _ (equiv.has_one e) = e.symm 1 := rfl
protected def has_mul [has_mul β] : has_mul α := ⟨λ x y, e.symm (e x * e y)⟩
lemma mul_def [has_mul β] (x y : α) :
@has_mul.mul _ (equiv.has_mul e) x y = e.symm (e x * e y) := rfl
protected def has_add [has_add β] : has_add α := ⟨λ x y, e.symm (e x + e y)⟩
lemma add_def [has_add β] (x y : α) :
@has_add.add _ (equiv.has_add e) x y = e.symm (e x + e y) := rfl
protected def has_inv [has_inv β] : has_inv α := ⟨λ x, e.symm (e x)⁻¹⟩
lemma inv_def [has_inv β] (x : α) : @has_inv.inv _ (equiv.has_inv e) x = e.symm (e x)⁻¹ := rfl
protected def has_neg [has_neg β] : has_neg α := ⟨λ x, e.symm (-e x)⟩
lemma neg_def [has_neg β] (x : α) : @has_neg.neg _ (equiv.has_neg e) x = e.symm (-e x) := rfl
protected def semigroup [semigroup β] : semigroup α :=
{ mul_assoc := by simp [mul_def, mul_assoc],
..equiv.has_mul e }
protected def comm_semigroup [comm_semigroup β] : comm_semigroup α :=
{ mul_comm := by simp [mul_def, mul_comm],
..equiv.semigroup e }
protected def monoid [monoid β] : monoid α :=
{ one_mul := by simp [mul_def, one_def],
mul_one := by simp [mul_def, one_def],
..equiv.semigroup e,
..equiv.has_one e }
protected def comm_monoid [comm_monoid β] : comm_monoid α :=
{ ..equiv.comm_semigroup e,
..equiv.monoid e }
protected def group [group β] : group α :=
{ mul_left_inv := by simp [mul_def, inv_def, one_def],
..equiv.monoid e,
..equiv.has_inv e }
protected def comm_group [comm_group β] : comm_group α :=
{ ..equiv.group e,
..equiv.comm_semigroup e }
protected def add_semigroup [add_semigroup β] : add_semigroup α :=
@additive.add_semigroup _ (@equiv.semigroup _ _ e multiplicative.semigroup)
protected def add_comm_semigroup [add_comm_semigroup β] : add_comm_semigroup α :=
@additive.add_comm_semigroup _ (@equiv.comm_semigroup _ _ e multiplicative.comm_semigroup)
protected def add_monoid [add_monoid β] : add_monoid α :=
@additive.add_monoid _ (@equiv.monoid _ _ e multiplicative.monoid)
protected def add_comm_monoid [add_comm_monoid β] : add_comm_monoid α :=
@additive.add_comm_monoid _ (@equiv.comm_monoid _ _ e multiplicative.comm_monoid)
protected def add_group [add_group β] : add_group α :=
@additive.add_group _ (@equiv.group _ _ e multiplicative.group)
protected def add_comm_group [add_comm_group β] : add_comm_group α :=
@additive.add_comm_group _ (@equiv.comm_group _ _ e multiplicative.comm_group)
protected def semiring [semiring β] : semiring α :=
{ right_distrib := by simp [mul_def, add_def, add_mul],
left_distrib := by simp [mul_def, add_def, mul_add],
zero_mul := by simp [mul_def, zero_def],
mul_zero := by simp [mul_def, zero_def],
..equiv.has_zero e,
..equiv.has_mul e,
..equiv.has_add e,
..equiv.monoid e,
..equiv.add_comm_monoid e }
protected def comm_semiring [comm_semiring β] : comm_semiring α :=
{ ..equiv.semiring e,
..equiv.comm_monoid e }
protected def ring [ring β] : ring α :=
{ ..equiv.semiring e,
..equiv.add_comm_group e }
protected def comm_ring [comm_ring β] : comm_ring α :=
{ ..equiv.comm_monoid e,
..equiv.ring e }
protected def zero_ne_one_class [zero_ne_one_class β] : zero_ne_one_class α :=
{ zero_ne_one := by simp [zero_def, one_def],
..equiv.has_zero e,
..equiv.has_one e }
protected def nonzero_comm_ring [nonzero_comm_ring β] : nonzero_comm_ring α :=
{ ..equiv.zero_ne_one_class e,
..equiv.comm_ring e }
protected def domain [domain β] : domain α :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := by simp [mul_def, zero_def, equiv.eq_symm_apply],
..equiv.has_zero e,
..equiv.zero_ne_one_class e,
..equiv.has_mul e,
..equiv.ring e }
protected def integral_domain [integral_domain β] : integral_domain α :=
{ ..equiv.domain e,
..equiv.nonzero_comm_ring e }
protected def division_ring [division_ring β] : division_ring α :=
{ inv_mul_cancel := λ _,
by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm];
exact inv_mul_cancel,
mul_inv_cancel := λ _,
by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm];
exact mul_inv_cancel,
..equiv.has_zero e,
..equiv.has_one e,
..equiv.domain e,
..equiv.has_inv e }
protected def field [field β] : field α :=
{ ..equiv.integral_domain e,
..equiv.division_ring e }
protected def discrete_field [discrete_field β] : discrete_field α :=
{ has_decidable_eq := equiv.decidable_eq e,
inv_zero := by simp [mul_def, inv_def, zero_def],
..equiv.has_mul e,
..equiv.has_inv e,
..equiv.has_zero e,
..equiv.field e }
end instances
end equiv
set_option old_structure_cmd true
/-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/
structure add_equiv (α β : Type*) [has_add α] [has_add β] extends α ≃ β :=
(map_add' : ∀ x y : α, to_fun (x + y) = to_fun x + to_fun y)
/-- `mul_equiv α β` is the type of an equiv `α ≃ β` which preserves multiplication. -/
@[to_additive "`add_equiv α β` is the type of an equiv `α ≃ β` which preserves addition."]
structure mul_equiv (α β : Type*) [has_mul α] [has_mul β] extends α ≃ β :=
(map_mul' : ∀ x y : α, to_fun (x * y) = to_fun x * to_fun y)
infix ` ≃* `:25 := mul_equiv
infix ` ≃+ `:25 := add_equiv
namespace mul_equiv
@[to_additive]
instance {α β} [has_mul α] [has_mul β] : has_coe_to_fun (α ≃* β) := ⟨_, mul_equiv.to_fun⟩
variables [has_mul α] [has_mul β] [has_mul γ]
/-- A multiplicative isomorphism preserves multiplication (canonical form). -/
@[to_additive]
lemma map_mul (f : α ≃* β) : ∀ x y : α, f (x * y) = f x * f y := f.map_mul'
/-- A multiplicative isomorphism preserves multiplication (deprecated). -/
@[to_additive]
instance (h : α ≃* β) : is_mul_hom h := ⟨h.map_mul⟩
/-- Makes a multiplicative isomorphism from a bijection which preserves multiplication. -/
@[to_additive]
def mk' (f : α ≃ β) (h : ∀ x y, f (x * y) = f x * f y) : α ≃* β :=
⟨f.1, f.2, f.3, f.4, h⟩
/-- The identity map is a multiplicative isomorphism. -/
@[refl, to_additive]
def refl (α : Type*) [has_mul α] : α ≃* α :=
{ map_mul' := λ _ _,rfl,
..equiv.refl _}
/-- The inverse of an isomorphism is an isomorphism. -/
@[symm, to_additive]
def symm (h : α ≃* β) : β ≃* α :=
{ map_mul' := λ n₁ n₂, function.injective_of_left_inverse h.left_inv begin
show h.to_equiv (h.to_equiv.symm (n₁ * n₂)) =
h ((h.to_equiv.symm n₁) * (h.to_equiv.symm n₂)),
rw h.map_mul,
show _ = h.to_equiv (_) * h.to_equiv (_),
rw [h.to_equiv.apply_symm_apply, h.to_equiv.apply_symm_apply, h.to_equiv.apply_symm_apply], end,
..h.to_equiv.symm}
@[simp, to_additive]
theorem to_equiv_symm (f : α ≃* β) : f.symm.to_equiv = f.to_equiv.symm := rfl
/-- Transitivity of multiplication-preserving isomorphisms -/
@[trans, to_additive]
def trans (h1 : α ≃* β) (h2 : β ≃* γ) : (α ≃* γ) :=
{ map_mul' := λ x y, show h2 (h1 (x * y)) = h2 (h1 x) * h2 (h1 y),
by rw [h1.map_mul, h2.map_mul],
..h1.to_equiv.trans h2.to_equiv }
/-- e.right_inv in canonical form -/
@[simp, to_additive]
lemma apply_symm_apply (e : α ≃* β) : ∀ (y : β), e (e.symm y) = y :=
e.to_equiv.apply_symm_apply
/-- e.left_inv in canonical form -/
@[simp, to_additive]
lemma symm_apply_apply (e : α ≃* β) : ∀ (x : α), e.symm (e x) = x :=
equiv.symm_apply_apply (e.to_equiv)
/-- a multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism) -/
@[simp, to_additive]
lemma map_one {α β} [monoid α] [monoid β] (h : α ≃* β) : h 1 = 1 :=
by rw [←mul_one (h 1), ←h.apply_symm_apply 1, ←h.map_mul, one_mul]
@[simp, to_additive]
lemma map_eq_one_iff {α β} [monoid α] [monoid β] (h : α ≃* β) {x : α} :
h x = 1 ↔ x = 1 :=
h.map_one ▸ h.to_equiv.apply_eq_iff_eq x 1
@[to_additive]
lemma map_ne_one_iff {α β} [monoid α] [monoid β] (h : α ≃* β) {x : α} :
h x ≠ 1 ↔ x ≠ 1 :=
⟨mt h.map_eq_one_iff.2, mt h.map_eq_one_iff.1⟩
/--
Extract the forward direction of a multiplicative equivalence
as a multiplication preserving function.
-/
@[to_additive to_add_monoid_hom]
def to_monoid_hom {α β} [monoid α] [monoid β] (h : α ≃* β) : (α →* β) :=
{ to_fun := h,
map_mul' := h.map_mul,
map_one' := h.map_one }
@[simp, to_additive]
lemma to_monoid_hom_apply_symm_to_monoid_hom_apply {α β} [monoid α] [monoid β] (e : α ≃* β) :
∀ (y : β), e.to_monoid_hom (e.symm.to_monoid_hom y) = y :=
e.to_equiv.apply_symm_apply
@[simp, to_additive]
lemma symm_to_monoid_hom_apply_to_monoid_hom_apply {α β} [monoid α] [monoid β] (e : α ≃* β) :
∀ (x : α), e.symm.to_monoid_hom (e.to_monoid_hom x) = x :=
equiv.symm_apply_apply (e.to_equiv)
/-- A multiplicative equivalence of groups preserves inversion. -/
@[to_additive]
lemma map_inv {α β} [group α] [group β] (h : α ≃* β) (x : α) : h x⁻¹ = (h x)⁻¹ :=
h.to_monoid_hom.map_inv x
/-- A multiplicative bijection between two monoids is a monoid hom
(deprecated -- use to_monoid_hom). -/
@[to_additive is_add_monoid_hom]
instance is_monoid_hom {α β} [monoid α] [monoid β] (h : α ≃* β) : is_monoid_hom h :=
⟨h.map_one⟩
/-- A multiplicative bijection between two groups is a group hom
(deprecated -- use to_monoid_hom). -/
@[to_additive is_add_group_hom]
instance is_group_hom {α β} [group α] [group β] (h : α ≃* β) :
is_group_hom h := { map_mul := h.map_mul }
/-- Two multiplicative isomorphisms agree if they are defined by the
same underlying function. -/
@[ext, to_additive
"Two additive isomorphisms agree if they are defined by the same underlying function."]
lemma ext {α β : Type*} [has_mul α] [has_mul β]
{f g : mul_equiv α β} (h : ∀ x, f x = g x) : f = g :=
begin
have h₁ := equiv.ext f.to_equiv g.to_equiv h,
cases f, cases g, congr,
{ exact (funext h) },
{ exact congr_arg equiv.inv_fun h₁ }
end
attribute [ext] add_equiv.ext
end mul_equiv
/-- An additive equivalence of additive groups preserves subtraction. -/
lemma add_equiv.map_sub {α β} [add_group α] [add_group β] (h : α ≃+ β) (x y : α) :
h (x - y) = h x - h y :=
h.to_add_monoid_hom.map_sub x y
/-- The group of multiplicative automorphisms. -/
@[to_additive "The group of additive automorphisms."]
def mul_aut (α : Type u) [has_mul α] := α ≃* α
namespace mul_aut
variables (α) [has_mul α]
/--
The group operation on multiplicative automorphisms is defined by
`λ g h, mul_equiv.trans h g`.
This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`.
-/
instance : group (mul_aut α) :=
by refine_struct
{ mul := λ g h, mul_equiv.trans h g,
one := mul_equiv.refl α,
inv := mul_equiv.symm };
intros; ext; try { refl }; apply equiv.left_inv
/-- Monoid hom from the group of multiplicative automorphisms to the group of permutations. -/
def to_perm : mul_aut α →* equiv.perm α :=
by refine_struct { to_fun := mul_equiv.to_equiv }; intros; refl
end mul_aut
namespace add_aut
variables (α) [has_add α]
/--
The group operation on additive automorphisms is defined by
`λ g h, mul_equiv.trans h g`.
This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`.
-/
instance group : group (add_aut α) :=
by refine_struct
{ mul := λ g h, add_equiv.trans h g,
one := add_equiv.refl α,
inv := add_equiv.symm };
intros; ext; try { refl }; apply equiv.left_inv
/-- Monoid hom from the group of multiplicative automorphisms to the group of permutations. -/
def to_perm : add_aut α →* equiv.perm α :=
by refine_struct { to_fun := add_equiv.to_equiv }; intros; refl
end add_aut
/-- A group is isomorphic to its group of units. -/
def to_units (α) [group α] : α ≃* units α :=
{ to_fun := λ x, ⟨x, x⁻¹, mul_inv_self _, inv_mul_self _⟩,
inv_fun := coe,
left_inv := λ x, rfl,
right_inv := λ u, units.ext rfl,
map_mul' := λ x y, units.ext rfl }
namespace units
variables [monoid α] [monoid β] [monoid γ]
(f : α → β) (g : β → γ) [is_monoid_hom f] [is_monoid_hom g]
def map_equiv (h : α ≃* β) : units α ≃* units β :=
{ inv_fun := map h.symm.to_monoid_hom,
left_inv := λ u, ext $ h.left_inv u,
right_inv := λ u, ext $ h.right_inv u,
.. map h.to_monoid_hom }
end units
/- (semi)ring equivalence. -/
structure ring_equiv (α β : Type*) [has_mul α] [has_add α] [has_mul β] [has_add β]
extends α ≃ β, α ≃* β, α ≃+ β
infix ` ≃+* `:25 := ring_equiv
namespace ring_equiv
section basic
variables [has_mul α] [has_add α] [has_mul β] [has_add β] [has_mul γ] [has_add γ]
instance : has_coe_to_fun (α ≃+* β) := ⟨_, ring_equiv.to_fun⟩
instance has_coe_to_mul_equiv : has_coe (α ≃+* β) (α ≃* β) := ⟨ring_equiv.to_mul_equiv⟩
instance has_coe_to_add_equiv : has_coe (α ≃+* β) (α ≃+ β) := ⟨ring_equiv.to_add_equiv⟩
@[squash_cast] lemma coe_mul_equiv (f : α ≃+* β) (a : α) :
(f : α ≃* β) a = f a := rfl
@[squash_cast] lemma coe_add_equiv (f : α ≃+* β) (a : α) :
(f : α ≃+ β) a = f a := rfl
variable (α)
/-- The identity map is a ring isomorphism. -/
@[refl] protected def refl : α ≃+* α := { .. mul_equiv.refl α, .. add_equiv.refl α }
variables {α}
/-- The inverse of a ring isomorphism is a ring isomorphis. -/
@[symm] protected def symm (e : α ≃+* β) : β ≃+* α :=
{ .. e.to_mul_equiv.symm, .. e.to_add_equiv.symm }
/-- Transitivity of `ring_equiv`. -/
@[trans] protected def trans (e₁ : α ≃+* β) (e₂ : β ≃+* γ) : α ≃+* γ :=
{ .. (e₁.to_mul_equiv.trans e₂.to_mul_equiv), .. (e₁.to_add_equiv.trans e₂.to_add_equiv) }
@[simp] lemma apply_symm_apply (e : α ≃+* β) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply
@[simp] lemma symm_apply_apply (e : α ≃+* β) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply
lemma image_eq_preimage (e : α ≃+* β) (s : set α) : e '' s = e.symm ⁻¹' s :=
e.to_equiv.image_eq_preimage s
end basic
section
variables [semiring α] [semiring β] (f : α ≃+* β) (x y : α)
/-- A ring isomorphism preserves multiplication. -/
@[simp] lemma map_mul : f (x * y) = f x * f y := f.map_mul' x y
/-- A ring isomorphism sends one to one. -/
@[simp] lemma map_one : f 1 = 1 := (f : α ≃* β).map_one
/-- A ring isomorphism preserves addition. -/
@[simp] lemma map_add : f (x + y) = f x + f y := f.map_add' x y
/-- A ring isomorphism sends zero to zero. -/
@[simp] lemma map_zero : f 0 = 0 := (f : α ≃+ β).map_zero
variable {x}
@[simp] lemma map_eq_one_iff : f x = 1 ↔ x = 1 := (f : α ≃* β).map_eq_one_iff
@[simp] lemma map_eq_zero_iff : f x = 0 ↔ x = 0 := (f : α ≃+ β).map_eq_zero_iff
lemma map_ne_one_iff : f x ≠ 1 ↔ x ≠ 1 := (f : α ≃* β).map_ne_one_iff
lemma map_ne_zero_iff : f x ≠ 0 ↔ x ≠ 0 := (f : α ≃+ β).map_ne_zero_iff
end
section
variables [ring α] [ring β] (f : α ≃+* β) (x y : α)
@[simp] lemma map_neg : f (-x) = -f x := (f : α ≃+ β).map_neg x
@[simp] lemma map_sub : f (x - y) = f x - f y := (f : α ≃+ β).map_sub x y
@[simp] lemma map_neg_one : f (-1) = -1 := f.map_one ▸ f.map_neg 1
end
section semiring_hom
variables [semiring α] [semiring β]
/-- Reinterpret a ring equivalence as a ring homomorphism. -/
def to_ring_hom (e : α ≃+* β) : α →+* β :=
{ .. e.to_mul_equiv.to_monoid_hom, .. e.to_add_equiv.to_add_monoid_hom }
/-- Reinterpret a ring equivalence as a monoid homomorphism. -/
abbreviation to_monoid_hom (e : α ≃+* β) : α →* β := e.to_ring_hom.to_monoid_hom
/-- Reinterpret a ring equivalence as an `add_monoid` homomorphism. -/
abbreviation to_add_monoid_hom (e : α ≃+* β) : α →+ β := e.to_ring_hom.to_add_monoid_hom
/-- Interpret an equivalence `f : α ≃ β` as a ring equivalence `α ≃+* β`. -/
def of (e : α ≃ β) [is_semiring_hom e] : α ≃+* β :=
{ .. e, .. monoid_hom.of e, .. add_monoid_hom.of e }
instance (e : α ≃+* β) : is_semiring_hom e := e.to_ring_hom.is_semiring_hom
@[simp]
lemma to_ring_hom_apply_symm_to_ring_hom_apply {α β} [semiring α] [semiring β] (e : α ≃+* β) :
∀ (y : β), e.to_ring_hom (e.symm.to_ring_hom y) = y :=
e.to_equiv.apply_symm_apply
@[simp]
lemma symm_to_ring_hom_apply_to_ring_hom_apply {α β} [semiring α] [semiring β] (e : α ≃+* β) :
∀ (x : α), e.symm.to_ring_hom (e.to_ring_hom x) = x :=
equiv.symm_apply_apply (e.to_equiv)
end semiring_hom
end ring_equiv
namespace mul_equiv
/-- Gives an `is_semiring_hom` instance from a `mul_equiv` of semirings that preserves addition. -/
protected lemma to_semiring_hom {R : Type*} {S : Type*} [semiring R] [semiring S]
(h : R ≃* S) (H : ∀ x y : R, h (x + y) = h x + h y) : is_semiring_hom h :=
⟨add_equiv.map_zero $ add_equiv.mk' h.to_equiv H, h.map_one, H, h.5⟩
/-- Gives a `ring_equiv` from a `mul_equiv` preserving addition.-/
def to_ring_equiv {R : Type*} {S : Type*} [has_add R] [has_add S] [has_mul R] [has_mul S]
(h : R ≃* S) (H : ∀ x y : R, h (x + y) = h x + h y) : R ≃+* S :=
{..h.to_equiv, ..h, ..add_equiv.mk' h.to_equiv H }
end mul_equiv
namespace add_equiv
/-- Gives an `is_semiring_hom` instance from a `mul_equiv` of semirings that preserves addition. -/
protected lemma to_semiring_hom {R : Type*} {S : Type*} [semiring R] [semiring S]
(h : R ≃+ S) (H : ∀ x y : R, h (x * y) = h x * h y) : is_semiring_hom h :=
⟨h.map_zero, mul_equiv.map_one $ mul_equiv.mk' h.to_equiv H, h.5, H⟩
end add_equiv
namespace ring_equiv
section ring_hom
variables [ring α] [ring β]
/-- Interpret an equivalence `f : α ≃ β` as a ring equivalence `α ≃+* β`. -/
def of' (e : α ≃ β) [is_ring_hom e] : α ≃+* β :=
{ .. e, .. monoid_hom.of e, .. add_monoid_hom.of e }
instance (e : α ≃+* β) : is_ring_hom e := e.to_ring_hom.is_ring_hom
end ring_hom
/-- Two ring isomorphisms agree if they are defined by the
same underlying function. -/
@[ext] lemma ext {R S : Type*} [has_mul R] [has_add R] [has_mul S] [has_add S]
{f g : R ≃+* S} (h : ∀ x, f x = g x) : f = g :=
begin
have h₁ := equiv.ext f.to_equiv g.to_equiv h,
cases f, cases g, congr,
{ exact (funext h) },
{ exact congr_arg equiv.inv_fun h₁ }
end
end ring_equiv
/-- The group of ring automorphisms. -/
def ring_aut (R : Type u) [has_mul R] [has_add R] := ring_equiv R R
namespace ring_aut
variables (R : Type u) [has_mul R] [has_add R]
/--
The group operation on automorphisms of a ring is defined by
λ g h, ring_equiv.trans h g.
This means that multiplication agrees with composition, (g*h)(x) = g (h x) .
-/
instance : group (ring_aut R) :=
by refine_struct
{ mul := λ g h, ring_equiv.trans h g,
one := ring_equiv.refl R,
inv := ring_equiv.symm };
intros; ext; try { refl }; apply equiv.left_inv
/-- Monoid homomorphism from ring automorphisms to additive automorphisms. -/
def to_add_aut : ring_aut R →* add_aut R :=
by refine_struct { to_fun := ring_equiv.to_add_equiv }; intros; refl
/-- Monoid homomorphism from ring automorphisms to multiplicative automorphisms. -/
def to_mul_aut : ring_aut R →* mul_aut R :=
by refine_struct { to_fun := ring_equiv.to_mul_equiv }; intros; refl
/-- Monoid homomorphism from ring automorphisms to permutations. -/
def to_perm : ring_aut R →* equiv.perm R :=
by refine_struct { to_fun := ring_equiv.to_equiv }; intros; refl
end ring_aut
|
dde105ada211930ddbfc3ecf3d5c48d6378be12e
|
9028d228ac200bbefe3a711342514dd4e4458bff
|
/src/data/nat/associated.lean
|
86e4ffee2f56f9aa8810c010a5a35721f09f56e4
|
[
"Apache-2.0"
] |
permissive
|
mcncm/mathlib
|
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
|
fde3d78cadeec5ef827b16ae55664ef115e66f57
|
refs/heads/master
| 1,672,743,316,277
| 1,602,618,514,000
| 1,602,618,514,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 1,816
|
lean
|
/-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import data.nat.prime
import algebra.associated
import tactic.omega
/-#
# Primes and irreducibles in `ℕ`
This file connects the ideas presented in `algebra.associated` with the natural numbers.
## Main results
* `nat.prime_iff`: `nat.prime` coincides with the general definition of `prime`
* `nat.irreducible_iff_prime`: a non-unit natural number is only divisible by `1` iff it is prime
## Tags
prime, irreducible, natural numbers,
-/
theorem nat.prime_iff {p : ℕ} : p.prime ↔ prime p :=
begin
split; intro h,
{ refine ⟨h.ne_zero, ⟨_, λ a b, _⟩⟩,
{ rw nat.is_unit_iff, apply h.ne_one },
{ apply h.dvd_mul.1 } },
{ refine ⟨_, λ m hm, _⟩,
{ cases p, { exfalso, apply h.ne_zero rfl },
cases p, { exfalso, apply h.ne_one rfl },
omega },
{ cases hm with n hn,
cases h.2.2 m n (hn ▸ dvd_refl _) with hpm hpn,
{ right, apply nat.dvd_antisymm (dvd.intro _ hn.symm) hpm },
{ left,
cases n, { exfalso, rw [hn, mul_zero] at h, apply h.ne_zero rfl },
apply nat.eq_of_mul_eq_mul_right (nat.succ_pos _),
rw [← hn, one_mul],
apply nat.dvd_antisymm hpn (dvd.intro m _),
rw [mul_comm, hn], }, } }
end
theorem nat.irreducible_iff_prime {p : ℕ} : irreducible p ↔ prime p :=
begin
refine ⟨λ h, _, irreducible_of_prime⟩,
rw ← nat.prime_iff,
refine ⟨_, λ m hm, _⟩,
{ cases p, { exfalso, apply h.ne_zero rfl },
cases p, { exfalso, apply h.1 is_unit_one, },
omega },
{ cases hm with n hn,
cases h.2 m n hn with um un,
{ left, rw nat.is_unit_iff.1 um, },
{ right, rw [hn, nat.is_unit_iff.1 un, mul_one], } }
end
|
8bb80454c3bab07ddf1045a5e66e65ed825f780d
|
f618aea02cb4104ad34ecf3b9713065cc0d06103
|
/src/linear_algebra/determinant.lean
|
389f94c01756cdf288e793bca74c925347915623
|
[
"Apache-2.0"
] |
permissive
|
joehendrix/mathlib
|
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
|
c15eab34ad754f9ecd738525cb8b5a870e834ddc
|
refs/heads/master
| 1,589,606,591,630
| 1,555,946,393,000
| 1,555,946,393,000
| 182,813,854
| 0
| 0
| null | 1,555,946,309,000
| 1,555,946,308,000
| null |
UTF-8
|
Lean
| false
| false
| 5,621
|
lean
|
/-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Chris Hughes
-/
import data.matrix
import group_theory.subgroup group_theory.perm.sign
local attribute [instance, priority 0] nat.cast_coe
local attribute [instance, priority 0] int.cast_coe
universes u v
open equiv equiv.perm finset function
namespace matrix
variables {n : Type u} [fintype n] [decidable_eq n] {R : Type v} [comm_ring R]
local notation `ε` σ:max := ((sign σ : ℤ ) : R)
definition det (M : matrix n n R) : R :=
univ.sum (λ (σ : perm n), ε σ * univ.prod (λ i, M (σ i) i))
@[simp] lemma det_diagonal {d : n → R} : det (diagonal d) = univ.prod d :=
begin
refine (finset.sum_eq_single 1 _ _).trans _,
{ intros σ h1 h2,
cases not_forall.1 (mt (equiv.ext _ _) h2) with x h3,
convert ring.mul_zero _,
apply finset.prod_eq_zero,
{ change x ∈ _, simp },
exact if_neg h3 },
{ simp },
{ simp }
end
@[simp] lemma det_zero (h : nonempty n) : det (0 : matrix n n R) = 0 :=
by rw [← diagonal_zero, det_diagonal, finset.prod_const, ← fintype.card,
zero_pow (fintype.card_pos_iff.2 h)]
@[simp] lemma det_one : det (1 : matrix n n R) = 1 :=
by rw [← diagonal_one]; simp [-diagonal_one]
lemma det_mul_aux {M N : matrix n n R} {p : n → n} (H : ¬bijective p) :
univ.sum (λ σ : perm n, (ε σ) * (univ.prod (λ x, M (σ x) (p x) * N (p x) x))) = 0 :=
let ⟨i, hi⟩ := classical.not_forall.1 (mt fintype.injective_iff_bijective.1 H) in
let ⟨j, hij'⟩ := classical.not_forall.1 hi in
have hij : p i = p j ∧ i ≠ j, from not_imp.1 hij',
sum_involution
(λ σ _, σ * swap i j)
(λ σ _,
have ∀ a, p (swap i j a) = p a := λ a, by simp only [swap_apply_def]; split_ifs; cc,
have univ.prod (λ x, M (σ x) (p x)) = univ.prod (λ x, M ((σ * swap i j) x) (p x)),
from prod_bij (λ a _, swap i j a) (λ _ _, mem_univ _) (by simp [this])
(λ _ _ _ _ h, (swap i j).injective h)
(λ b _, ⟨swap i j b, mem_univ _, by simp⟩),
by simp [sign_mul, this, sign_swap hij.2, prod_mul_distrib])
(λ σ _ _ h, hij.2 (σ.injective $ by conv {to_lhs, rw ← h}; simp))
(λ _ _, mem_univ _)
(λ _ _, equiv.ext _ _ $ by simp)
@[simp] lemma det_mul (M N : matrix n n R) : det (M * N) = det M * det N :=
calc det (M * N) = univ.sum (λ σ : perm n, (univ.pi (λ a, univ)).sum
(λ (p : Π (a : n), a ∈ univ → n), ε σ *
univ.attach.prod (λ i, M (σ i.1) (p i.1 (mem_univ _)) * N (p i.1 (mem_univ _)) i.1))) :
by simp only [det, mul_val', prod_sum, mul_sum]
... = univ.sum (λ σ : perm n, univ.sum
(λ p : n → n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) :
sum_congr rfl (λ σ _, sum_bij
(λ f h i, f i (mem_univ _)) (λ _ _, mem_univ _)
(by simp) (by simp [funext_iff]) (λ b _, ⟨λ i hi, b i, by simp⟩))
... = univ.sum (λ p : n → n, univ.sum
(λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) :
finset.sum_comm
... = ((@univ (n → n) _).filter bijective ∪ univ.filter (λ p : n → n, ¬bijective p)).sum
(λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) :
finset.sum_congr (finset.ext.2 (by simp; tauto)) (λ _ _, rfl)
... = ((@univ (n → n) _).filter bijective).sum (λ p : n → n, univ.sum
(λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) +
(univ.filter (λ p : n → n, ¬bijective p)).sum (λ p : n → n, univ.sum
(λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) :
finset.sum_union (by simp [finset.ext]; tauto)
... = ((@univ (n → n) _).filter bijective).sum (λ p : n → n, univ.sum
(λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) +
(univ.filter (λ p : n → n, ¬bijective p)).sum (λ p, 0) :
(add_left_inj _).2 (finset.sum_congr rfl $ λ p h, det_mul_aux (mem_filter.1 h).2)
... = ((@univ (n → n) _).filter bijective).sum (λ p : n → n, univ.sum
(λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : by simp
... = (@univ (perm n) _).sum (λ τ, univ.sum
(λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (τ i) * N (τ i) i))) :
sum_bij (λ p h, equiv.of_bijective (mem_filter.1 h).2) (λ _ _, mem_univ _)
(λ _ _, rfl) (λ _ _ _ _ h, by injection h)
(λ b _, ⟨b, mem_filter.2 ⟨mem_univ _, b.bijective⟩, eq_of_to_fun_eq rfl⟩)
... = univ.sum (λ σ : perm n, univ.sum (λ τ : perm n,
(univ.prod (λ i, N (σ i) i) * ε τ) * univ.prod (λ j, M (τ j) (σ j)))) :
by simp [mul_sum, det, mul_comm, mul_left_comm, prod_mul_distrib, mul_assoc]
... = univ.sum (λ σ : perm n, univ.sum (λ τ : perm n,
(univ.prod (λ i, N (σ i) i) * (ε σ * ε τ)) *
univ.prod (λ i, M (τ i) i))) :
sum_congr rfl (λ σ _, sum_bij (λ τ _, τ * σ⁻¹) (λ _ _, mem_univ _)
(λ τ _,
have univ.prod (λ j, M (τ j) (σ j)) = univ.prod (λ j, M ((τ * σ⁻¹) j) j),
by rw prod_univ_perm σ⁻¹; simp [mul_apply],
have h : ε σ * ε (τ * σ⁻¹) = ε τ :=
calc ε σ * ε (τ * σ⁻¹) = ε ((τ * σ⁻¹) * σ) :
by rw [mul_comm, sign_mul (τ * σ⁻¹)]; simp [sign_mul]
... = ε τ : by simp,
by rw h; simp [this, mul_comm, mul_assoc, mul_left_comm])
(λ _ _ _ _, (mul_right_inj _).1) (λ τ _, ⟨τ * σ, by simp⟩))
... = det M * det N : by simp [det, mul_assoc, mul_sum, mul_comm, mul_left_comm]
instance : is_monoid_hom (det : matrix n n R → R) :=
{ map_one := det_one,
map_mul := det_mul }
end matrix
|
1c1ae44a84307e64b2ebf86b841ca8855c1167d1
|
d406927ab5617694ec9ea7001f101b7c9e3d9702
|
/src/number_theory/class_number/admissible_card_pow_degree.lean
|
0566fcc9534bb0688e42ee213f55b893aac5d501
|
[
"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
| 13,825
|
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 number_theory.class_number.admissible_absolute_value
import analysis.special_functions.pow
import ring_theory.ideal.local_ring
import data.polynomial.degree.card_pow_degree
/-!
# Admissible absolute values on polynomials
This file defines an admissible absolute value
`polynomial.card_pow_degree_is_admissible` which we use to show the class number
of the ring of integers of a function field is finite.
## Main results
* `polynomial.card_pow_degree_is_admissible` shows `card_pow_degree`,
mapping `p : polynomial 𝔽_q` to `q ^ degree p`, is admissible
-/
namespace polynomial
open_locale polynomial
open absolute_value real
variables {Fq : Type*} [fintype Fq]
/-- If `A` is a family of enough low-degree polynomials over a finite semiring, there is a
pair of equal elements in `A`. -/
lemma exists_eq_polynomial [semiring Fq] {d : ℕ} {m : ℕ} (hm : fintype.card Fq ^ d ≤ m) (b : Fq[X])
(hb : nat_degree b ≤ d) (A : fin m.succ → Fq[X]) (hA : ∀ i, degree (A i) < degree b) :
∃ i₀ i₁, i₀ ≠ i₁ ∧ A i₁ = A i₀ :=
begin
-- Since there are > q^d elements of A, and only q^d choices for the highest `d` coefficients,
-- there must be two elements of A with the same coefficients at
-- `0`, ... `degree b - 1` ≤ `d - 1`.
-- In other words, the following map is not injective:
set f : fin m.succ → (fin d → Fq) := λ i j, (A i).coeff j,
have : fintype.card (fin d → Fq) < fintype.card (fin m.succ),
{ simpa using lt_of_le_of_lt hm (nat.lt_succ_self m) },
-- Therefore, the differences have all coefficients higher than `deg b - d` equal.
obtain ⟨i₀, i₁, i_ne, i_eq⟩ := fintype.exists_ne_map_eq_of_card_lt f this,
use [i₀, i₁, i_ne],
ext j,
-- The coefficients higher than `deg b` are the same because they are equal to 0.
by_cases hbj : degree b ≤ j,
{ rw [coeff_eq_zero_of_degree_lt (lt_of_lt_of_le (hA _) hbj),
coeff_eq_zero_of_degree_lt (lt_of_lt_of_le (hA _) hbj)] },
-- So we only need to look for the coefficients between `0` and `deg b`.
rw not_le at hbj,
apply congr_fun i_eq.symm ⟨j, _⟩,
exact lt_of_lt_of_le (coe_lt_degree.mp hbj) hb
end
/-- If `A` is a family of enough low-degree polynomials over a finite ring,
there is a pair of elements in `A` (with different indices but not necessarily
distinct), such that their difference has small degree. -/
lemma exists_approx_polynomial_aux [ring Fq] {d : ℕ} {m : ℕ} (hm : fintype.card Fq ^ d ≤ m)
(b : Fq[X]) (A : fin m.succ → Fq[X]) (hA : ∀ i, degree (A i) < degree b) :
∃ i₀ i₁, i₀ ≠ i₁ ∧ degree (A i₁ - A i₀) < ↑(nat_degree b - d) :=
begin
have hb : b ≠ 0,
{ rintro rfl,
specialize hA 0,
rw degree_zero at hA,
exact not_lt_of_le bot_le hA },
-- Since there are > q^d elements of A, and only q^d choices for the highest `d` coefficients,
-- there must be two elements of A with the same coefficients at
-- `degree b - 1`, ... `degree b - d`.
-- In other words, the following map is not injective:
set f : fin m.succ → (fin d → Fq) := λ i j, (A i).coeff (nat_degree b - j.succ),
have : fintype.card (fin d → Fq) < fintype.card (fin m.succ),
{ simpa using lt_of_le_of_lt hm (nat.lt_succ_self m) },
-- Therefore, the differences have all coefficients higher than `deg b - d` equal.
obtain ⟨i₀, i₁, i_ne, i_eq⟩ := fintype.exists_ne_map_eq_of_card_lt f this,
use [i₀, i₁, i_ne],
refine (degree_lt_iff_coeff_zero _ _).mpr (λ j hj, _),
-- The coefficients higher than `deg b` are the same because they are equal to 0.
by_cases hbj : degree b ≤ j,
{ refine coeff_eq_zero_of_degree_lt (lt_of_lt_of_le _ hbj),
exact lt_of_le_of_lt (degree_sub_le _ _) (max_lt (hA _) (hA _)) },
-- So we only need to look for the coefficients between `deg b - d` and `deg b`.
rw [coeff_sub, sub_eq_zero],
rw [not_le, degree_eq_nat_degree hb, with_bot.coe_lt_coe] at hbj,
have hj : nat_degree b - j.succ < d,
{ by_cases hd : nat_degree b < d,
{ exact lt_of_le_of_lt tsub_le_self hd },
{ rw not_lt at hd,
have := lt_of_le_of_lt hj (nat.lt_succ_self j),
rwa [tsub_lt_iff_tsub_lt hd hbj] at this } },
have : j = b.nat_degree - (nat_degree b - j.succ).succ,
{ rw [← nat.succ_sub hbj, nat.succ_sub_succ, tsub_tsub_cancel_of_le hbj.le] },
convert congr_fun i_eq.symm ⟨nat_degree b - j.succ, hj⟩
end
variables [field Fq]
/-- If `A` is a family of enough low-degree polynomials over a finite field,
there is a pair of elements in `A` (with different indices but not necessarily
distinct), such that the difference of their remainders is close together. -/
lemma exists_approx_polynomial {b : Fq[X]} (hb : b ≠ 0)
{ε : ℝ} (hε : 0 < ε)
(A : fin (fintype.card Fq ^ ⌈- log ε / log (fintype.card Fq)⌉₊).succ → Fq[X]) :
∃ i₀ i₁, i₀ ≠ i₁ ∧ (card_pow_degree (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree b • ε :=
begin
have hbε : 0 < card_pow_degree b • ε,
{ rw [algebra.smul_def, eq_int_cast],
exact mul_pos (int.cast_pos.mpr (absolute_value.pos _ hb)) hε },
have one_lt_q : 1 < fintype.card Fq := fintype.one_lt_card,
have one_lt_q' : (1 : ℝ) < fintype.card Fq, { assumption_mod_cast },
have q_pos : 0 < fintype.card Fq, { linarith },
have q_pos' : (0 : ℝ) < fintype.card Fq, { assumption_mod_cast },
-- If `b` is already small enough, then the remainders are equal and we are done.
by_cases le_b : b.nat_degree ≤ ⌈- log ε / log (fintype.card Fq)⌉₊,
{ obtain ⟨i₀, i₁, i_ne, mod_eq⟩ := exists_eq_polynomial le_rfl b le_b (λ i, A i % b)
(λ i, euclidean_domain.mod_lt (A i) hb),
refine ⟨i₀, i₁, i_ne, _⟩,
simp only at mod_eq,
rwa [mod_eq, sub_self, absolute_value.map_zero, int.cast_zero] },
-- Otherwise, it suffices to choose two elements whose difference is of small enough degree.
rw not_le at le_b,
obtain ⟨i₀, i₁, i_ne, deg_lt⟩ := exists_approx_polynomial_aux le_rfl b (λ i, A i % b)
(λ i, euclidean_domain.mod_lt (A i) hb),
simp only at deg_lt,
use [i₀, i₁, i_ne],
-- Again, if the remainders are equal we are done.
by_cases h : A i₁ % b = A i₀ % b,
{ rwa [h, sub_self, absolute_value.map_zero, int.cast_zero] },
have h' : A i₁ % b - A i₀ % b ≠ 0 := mt sub_eq_zero.mp h,
-- If the remainders are not equal, we'll show their difference is of small degree.
-- In particular, we'll show the degree is less than the following:
suffices : (nat_degree (A i₁ % b - A i₀ % b) : ℝ) <
b.nat_degree + log ε / log (fintype.card Fq),
{ rwa [← real.log_lt_log_iff (int.cast_pos.mpr (card_pow_degree.pos h')) hbε,
card_pow_degree_nonzero _ h', card_pow_degree_nonzero _ hb,
algebra.smul_def, eq_int_cast,
int.cast_pow, int.cast_coe_nat, int.cast_pow, int.cast_coe_nat,
log_mul (pow_ne_zero _ q_pos'.ne') hε.ne',
← rpow_nat_cast, ← rpow_nat_cast, log_rpow q_pos', log_rpow q_pos',
← lt_div_iff (log_pos one_lt_q'), add_div, mul_div_cancel _ (log_pos one_lt_q').ne'] },
-- And that result follows from manipulating the result from `exists_approx_polynomial_aux`
-- to turn the `-⌈-stuff⌉₊` into `+ stuff`.
refine lt_of_lt_of_le (nat.cast_lt.mpr (with_bot.coe_lt_coe.mp _)) _,
swap, { convert deg_lt, rw degree_eq_nat_degree h' },
rw [← sub_neg_eq_add, neg_div],
refine le_trans _ (sub_le_sub_left (nat.le_ceil _) (b.nat_degree : ℝ)),
rw ← neg_div,
exact le_of_eq (nat.cast_sub le_b.le)
end
/-- If `x` is close to `y` and `y` is close to `z`, then `x` and `z` are at least as close. -/
lemma card_pow_degree_anti_archimedean {x y z : Fq[X]} {a : ℤ}
(hxy : card_pow_degree (x - y) < a) (hyz : card_pow_degree (y - z) < a) :
card_pow_degree (x - z) < a :=
begin
have ha : 0 < a := lt_of_le_of_lt (absolute_value.nonneg _ _) hxy,
by_cases hxy' : x = y,
{ rwa hxy' },
by_cases hyz' : y = z,
{ rwa ← hyz' },
by_cases hxz' : x = z,
{ rwa [hxz', sub_self, absolute_value.map_zero] },
rw [← ne.def, ← sub_ne_zero] at hxy' hyz' hxz',
refine lt_of_le_of_lt _ (max_lt hxy hyz),
rw [card_pow_degree_nonzero _ hxz', card_pow_degree_nonzero _ hxy',
card_pow_degree_nonzero _ hyz'],
have : (1 : ℤ) ≤ fintype.card Fq, { exact_mod_cast (@fintype.one_lt_card Fq _ _).le },
simp only [int.cast_pow, int.cast_coe_nat, le_max_iff],
refine or.imp (pow_le_pow this) (pow_le_pow this) _,
rw [nat_degree_le_iff_degree_le, nat_degree_le_iff_degree_le, ← le_max_iff,
← degree_eq_nat_degree hxy', ← degree_eq_nat_degree hyz'],
convert degree_add_le (x - y) (y - z) using 2,
exact (sub_add_sub_cancel _ _ _).symm
end
/-- A slightly stronger version of `exists_partition` on which we perform induction on `n`:
for all `ε > 0`, we can partition the remainders of any family of polynomials `A`
into equivalence classes, where the equivalence(!) relation is "closer than `ε`". -/
lemma exists_partition_polynomial_aux (n : ℕ) {ε : ℝ} (hε : 0 < ε)
{b : Fq[X]} (hb : b ≠ 0) (A : fin n → Fq[X]) :
∃ (t : fin n → fin (fintype.card Fq ^ ⌈- log ε / log (fintype.card Fq)⌉₊)),
∀ (i₀ i₁ : fin n),
t i₀ = t i₁ ↔ (card_pow_degree (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree b • ε :=
begin
have hbε : 0 < card_pow_degree b • ε,
{ rw [algebra.smul_def, eq_int_cast],
exact mul_pos (int.cast_pos.mpr (absolute_value.pos _ hb)) hε },
-- We go by induction on the size `A`.
induction n with n ih,
{ refine ⟨fin_zero_elim, fin_zero_elim⟩ },
-- Show `anti_archimedean` also holds for real distances.
have anti_archim' : ∀ {i j k} {ε : ℝ}, (card_pow_degree (A i % b - A j % b) : ℝ) < ε →
(card_pow_degree (A j % b - A k % b) : ℝ) < ε → (card_pow_degree (A i % b - A k % b) : ℝ) < ε,
{ intros i j k ε,
simp_rw [← int.lt_ceil],
exact card_pow_degree_anti_archimedean },
obtain ⟨t', ht'⟩ := ih (fin.tail A),
-- We got rid of `A 0`, so determine the index `j` of the partition we'll re-add it to.
rsuffices ⟨j, hj⟩ : ∃ j,
∀ i, t' i = j ↔ (card_pow_degree (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree b • ε,
{ refine ⟨fin.cons j t', λ i₀ i₁, _⟩,
refine fin.cases _ (λ i₀, _) i₀; refine fin.cases _ (λ i₁, _) i₁,
{ simpa using hbε },
{ rw [fin.cons_succ, fin.cons_zero, eq_comm, absolute_value.map_sub],
exact hj i₁ },
{ rw [fin.cons_succ, fin.cons_zero],
exact hj i₀ },
{ rw [fin.cons_succ, fin.cons_succ],
exact ht' i₀ i₁ } },
-- `exists_approx_polynomial` guarantees that we can insert `A 0` into some partition `j`,
-- but not that `j` is uniquely defined (which is needed to keep the induction going).
obtain ⟨j, hj⟩ : ∃ j, ∀ (i : fin n), t' i = j →
(card_pow_degree (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree b • ε,
{ by_contra this, push_neg at this,
obtain ⟨j₀, j₁, j_ne, approx⟩ := exists_approx_polynomial hb hε
(fin.cons (A 0) (λ j, A (fin.succ (classical.some (this j))))),
revert j_ne approx,
refine fin.cases _ (λ j₀, _) j₀; refine fin.cases (λ j_ne approx, _) (λ j₁ j_ne approx, _) j₁,
{ exact absurd rfl j_ne },
{ rw [fin.cons_succ, fin.cons_zero, ← not_le, absolute_value.map_sub] at approx,
have := (classical.some_spec (this j₁)).2,
contradiction },
{ rw [fin.cons_succ, fin.cons_zero, ← not_le] at approx,
have := (classical.some_spec (this j₀)).2,
contradiction },
{ rw [fin.cons_succ, fin.cons_succ] at approx,
rw [ne.def, fin.succ_inj] at j_ne,
have : j₀ = j₁ :=
(classical.some_spec (this j₀)).1.symm.trans
(((ht' (classical.some (this j₀)) (classical.some (this j₁))).mpr approx).trans
(classical.some_spec (this j₁)).1),
contradiction } },
-- However, if one of those partitions `j` is inhabited by some `i`, then this `j` works.
by_cases exists_nonempty_j : ∃ j, (∃ i, t' i = j) ∧
∀ i, t' i = j → (card_pow_degree (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree b • ε,
{ obtain ⟨j, ⟨i, hi⟩, hj⟩ := exists_nonempty_j,
refine ⟨j, λ i', ⟨hj i', λ hi', trans ((ht' _ _).mpr _) hi⟩⟩,
apply anti_archim' _ hi',
rw absolute_value.map_sub,
exact hj _ hi },
-- And otherwise, we can just take any `j`, since those are empty.
refine ⟨j, λ i, ⟨hj i, λ hi, _⟩⟩,
have := exists_nonempty_j ⟨t' i, ⟨i, rfl⟩, λ i' hi', anti_archim' hi ((ht' _ _).mp hi')⟩,
contradiction
end
/-- For all `ε > 0`, we can partition the remainders of any family of polynomials `A`
into classes, where all remainders in a class are close together. -/
lemma exists_partition_polynomial (n : ℕ) {ε : ℝ} (hε : 0 < ε)
{b : Fq[X]} (hb : b ≠ 0) (A : fin n → Fq[X]) :
∃ (t : fin n → fin (fintype.card Fq ^ ⌈- log ε / log (fintype.card Fq)⌉₊)),
∀ (i₀ i₁ : fin n), t i₀ = t i₁ →
(card_pow_degree (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree b • ε :=
begin
obtain ⟨t, ht⟩ := exists_partition_polynomial_aux n hε hb A,
exact ⟨t, λ i₀ i₁ hi, (ht i₀ i₁).mp hi⟩
end
/-- `λ p, fintype.card Fq ^ degree p` is an admissible absolute value.
We set `q ^ degree 0 = 0`. -/
noncomputable def card_pow_degree_is_admissible :
is_admissible (card_pow_degree : absolute_value Fq[X] ℤ) :=
{ card := λ ε, fintype.card Fq ^ ⌈- log ε / log (fintype.card Fq)⌉₊,
exists_partition' := λ n ε hε b hb, exists_partition_polynomial n hε hb,
.. @card_pow_degree_is_euclidean Fq _ _ }
end polynomial
|
307cf9a3e55c88d81a18e476f6a39aa920293350
|
3aad12fe82645d2d3173fbedc2e5c2ba945a4d75
|
/src/data/serial/json.lean
|
48d85eeeee2f36494e2bda7f11b57290767dae1e
|
[] |
no_license
|
seanpm2001/LeanProver-Community_MathLIB-Nursery
|
4f88d539cb18d73a94af983092896b851e6640b5
|
0479b31fa5b4d39f41e89b8584c9f5bf5271e8ec
|
refs/heads/master
| 1,688,730,786,645
| 1,572,070,026,000
| 1,572,070,026,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 12,434
|
lean
|
import data.serial.string
import tactic.linarith
import category.monad_trans
import data.list.nursery
import system.io
universes u
namespace json
inductive value
| object : unit → list (string × value) → value
| number : ℤ → value
| array : unit → list value → value
| bool : bool → value
| string : string → value
| nil : value
-- with object : Type
-- | fields : list (string × value) → object
open value (hiding object bool string)
@[reducible] def object := list (string × value)
def is_atom : value → bool
| (number n) := tt
| (value.bool b) := tt
| (value.string s) := tt
| value.nil := tt
| _ := ff
def encode_line : value → string
| (number n) := to_string n
| (value.bool n) := to_string n
| (value.string n) := to_string n
| nil := "nil"
| (value.object _ _) := "<object>"
| (value.array _ _) := "<array>"
namespace syntax
@[derive decidable_eq]
inductive token
| open_curly | close_curly
| open_square | close_square
| colon | comma | nil | bool (b : bool)
| number (n : ℤ) | string (s : string)
abbreviation put_m' := medium.put_m'.{u} token
abbreviation put_m := medium.put_m'.{u} token punit
abbreviation get_m := medium.get_m.{u} token
export medium (hiding put_m put_m' get_m)
namespace put_m'
export medium.put_m'
end put_m'
namespace get_m
export medium.get_m
end get_m
export token (hiding number string bool)
mutual def encode_val, encode_obj, encode_array
with encode_val : value → put_m
| (value.string s) := write_word $ token.string s
| (value.number n) := write_word $ token.number n
| (value.bool b) := write_word $ token.bool b
| (value.nil) := write_word $ token.nil
| (value.object _ []) :=
write_word open_curly >> write_word close_curly
| (value.object _ ((fn,v)::vs)) :=
do write_word open_curly,
write_word (token.string fn),
write_word colon,
encode_obj v vs,
write_word close_curly
| (value.array _ obj) :=
write_word open_square >> encode_array obj >> write_word close_square
with encode_obj : value → list (string × value) → put_m
| v [] := encode_val v
| v ((fn,v') :: vs) :=
do encode_val v,
write_word comma,
write_word (token.string fn),
write_word colon,
encode_obj v' vs
with encode_array : list value → put_m
| [] := pure ()
| (v :: vs) :=
do encode_val v,
when (¬ vs = []) $ do
write_word comma,
encode_array vs
inductive partial_val
| array (ar : list value)
| object (obj : list (string × value)) (field : string)
def parser_state := list partial_val
open ulift
def push : list partial_val → value → get_m ( value ⊕ parser_state )
| [] v := pure (sum.inl v)
| (partial_val.array ar :: vs) v :=
do t ← read_word,
if down t = comma then pure (sum.inr (partial_val.array (v :: ar) :: vs))
else if down t = close_square then push vs (value.array () (list.reverse $ v :: ar))
else failure
| (partial_val.object ar fn :: vs) v :=
do t ← read_word,
if down t = comma then do
⟨token.string fn'⟩ ← read_word | failure,
⟨colon⟩ ← read_word | failure,
pure (sum.inr (partial_val.object ((fn,v) :: ar) fn' :: vs))
else if down t = close_curly then push vs (value.object () (list.reverse $ (fn,v) :: ar))
else failure
def parser_step : parser_state → token → get_m ( value ⊕ parser_state )
| vs nil := push vs value.nil
| vs open_curly :=
do t ← read_word,
match down t with
| (token.string fn) :=
expect_word colon >>
pure (sum.inr (partial_val.object [] fn :: vs))
| close_curly := push vs (value.object () [])
| _ := failure
end
| vs open_square := pure (sum.inr (partial_val.array [] :: vs))
| vs (token.bool b) := push vs (value.bool b)
| vs (token.number n) := push vs (value.number n)
| vs (token.string str) := push vs (value.string str)
| vs close_square :=
match vs with
| (partial_val.array vs' :: vs) := push vs $ value.array () vs'.reverse
| _ := failure
end
| _ _ := failure
def decode_val : get_m value :=
get_m.loop parser_step pure []
def encoding_correctness_val (m : ℕ) :=
(∀ (v : value) (vs : list partial_val) (x : punit → put_m), sizeof v ≤ m →
get_m.loop parser_step pure vs -<< (encode_val v >>= x) =
(push vs v >>= get_m.loop.rest parser_step pure) -<< x punit.star)
def encoding_correctness_obj (m : ℕ) :=
(∀ (fn : string) (v : value) (obj obj' : object)
(vs : list partial_val) (x : punit → put_m),
sizeof obj' ≤ m → sizeof v < m →
get_m.loop parser_step pure (partial_val.object obj fn :: vs) -<<
(encode_obj v obj' >>= λ _, write_word close_curly >>= x) =
(push vs (value.object punit.star (obj.reverse ++ (fn,v) :: obj')) >>= get_m.loop.rest parser_step pure) -<< x punit.star)
def encoding_correctness_array (m : ℕ) :=
(∀ (v v' : list value)
(vs : list partial_val) (x : punit → put_m), sizeof v' ≤ m →
get_m.loop parser_step pure (partial_val.array v :: vs) -<<
(encode_array v' >>= λ (x_1 : punit), write_word close_square >>= x) =
(push vs (value.array punit.star (v.reverse ++ v')) >>= get_m.loop.rest parser_step pure) -<< x punit.star)
section correctness
variables n : ℕ
variables ih_val : ∀ (x : ℕ), x < n → encoding_correctness_val x
variables ih_obj : ∀ (x : ℕ), x < n → encoding_correctness_obj x
variables ih_ar : ∀ (x : ℕ), x < n → encoding_correctness_array x
include ih_val ih_obj ih_ar
lemma encode_val_ind_step : encoding_correctness_val n :=
begin
dsimp [encoding_correctness_val], introv h,
{ cases v with v fs _ v fs; casesm* unit;
try { simp [encode_val,parser_step] },
{ rcases fs with _ | ⟨ ⟨ fn,v ⟩, vs ⟩,
{ simp [encode_val,parser_step] with functor_norm },
{ simp [encode_val,parser_step,expect_word] with functor_norm,
apply ih_obj (1 + sizeof v + sizeof vs),
apply lt_of_lt_of_le _ h,
well_founded_tactics.default_dec_tac,
apply le_of_lt, well_founded_tactics.default_dec_tac,
well_founded_tactics.default_dec_tac }, },
{ simp [encode_val,parser_step] with functor_norm,
rw ih_ar; try { refl },
apply lt_of_lt_of_le _ h,
simp [sizeof,has_sizeof.sizeof,value.sizeof,punit.sizeof,list.sizeof] } },
end
lemma encode_obj_ind_step : encoding_correctness_obj n :=
begin
dsimp [encoding_correctness_obj], introv h h',
{ rcases obj' with _ | ⟨ ⟨ fn', v' ⟩, obj' ⟩,
{ simp [encode_obj], rw ih_val; try { assumption <|> refl },
simp [push] with functor_norm, },
{ simp [encode_obj] with functor_norm, rw ih_val (sizeof v),
simp [push] with functor_norm, rw ih_obj (1 + sizeof v' + sizeof obj'),
congr' 4, simp,
apply lt_of_lt_of_le _ h,
all_goals { try { well_founded_tactics.default_dec_tac } },
apply le_of_lt, well_founded_tactics.default_dec_tac,
refl } },
end
lemma encode_array_ind_step : encoding_correctness_array n :=
begin
dsimp [encoding_correctness_array], introv h,
{ cases v' with v' vs'; simp [encode_array,parser_step] with functor_norm,
rw ih_val (sizeof v' ),
by_cases h' : (vs' = []),
{ subst vs', simp [when,list.empty,push] with functor_norm },
{ simp [when,*,push] with functor_norm,
rw ih_ar (sizeof vs'), simp, apply lt_of_lt_of_le _ h,
well_founded_tactics.default_dec_tac, refl },
apply lt_of_lt_of_le _ h,
well_founded_tactics.default_dec_tac,
refl },
end
end correctness
lemma encoding_correctness' (m : ℕ) :
encoding_correctness_val m ∧
encoding_correctness_obj m ∧
encoding_correctness_array m :=
begin
induction m using nat.strong_induction_on with n ih,
simp [imp_and_distrib,forall_and_distrib,push] at ih,
rcases ih with ⟨ ih_val, ih_obj, ih_ar ⟩,
repeat { split },
apply encode_val_ind_step; assumption,
apply encode_obj_ind_step; assumption,
apply encode_array_ind_step; assumption,
end
lemma encoding_correctness (v : value) :
decode_val -<< encode_val v = some v :=
begin
have := (encoding_correctness' (sizeof v)).1 v [] pure _,
simp with functor_norm at this,
simp [decode_val,this,push], refl, refl
end
def value.repr : token → string
| (token.number n) := to_string n
| (token.string s) := "\"" ++ s ++ "\""
| (token.bool b) := to_string b
| nil := "nil"
| open_curly := "'{'"
| close_curly := "'}'"
| open_square := "'['"
| close_square := "']'"
| colon := "':'"
| comma := "','"
instance : has_repr token := ⟨ value.repr ⟩
#eval (encode_val (value.object ()
[ ("a",value.number 3),
("boo",value.array () [ value.number 3,
value.array () [ value.number 3, value.number 7, value.string "ho" ] ,
value.string "abc" ]) ])).eval
end syntax
end json
-- namespace yaml
-- open string.medium json
-- @[reducible] def writer := reader_t ℕ put_m'
-- def newline : writer unit :=
-- ⟨ λ n, emit $ "\n" ++ (list.repeat ' ' n).as_string ⟩
-- def bump {α} (tac : writer α) : writer α :=
-- ⟨ λ n, tac.run (n+2) ⟩
-- mutual def encode_aux, encode_obj, encode_array
-- with encode_aux : value → writer unit
-- | (value.string v) := monad_lift $ emit $ "\"" ++ v ++ "\""
-- | (value.bool v) := monad_lift $ emit $ to_string v
-- | (value.number v) := monad_lift $ emit $ to_string v
-- | value.nil := monad_lift $ emit "nil"
-- | (value.object _ o) := encode_obj o
-- | (value.array _ ar) := encode_array ar
-- with encode_obj : list (string × value) → writer unit
-- | [] := monad_lift $ emit "[]"
-- | ((f,v) :: vs) :=
-- do monad_lift $ emit (f ++ ": "),
-- bump $ do {
-- when (¬ is_atom v) newline,
-- encode_aux v },
-- when (¬ vs.empty) $ do
-- newline,
-- encode_obj vs
-- with encode_array : list value → writer unit
-- | [] := monad_lift $ emit "[]"
-- | (v :: vs) :=
-- do monad_lift $ emit "- ",
-- bump $ encode_aux v,
-- when (¬ vs.empty) $ do
-- newline,
-- encode_array vs
-- def encode (v : value) : put_m :=
-- (encode_aux v).run 0
-- def select_aux {α} (f : char → list (bool × reader α)) (c : char) : reader α :=
-- (prod.snd <$> list.find (λ x, prod.fst x = tt) (f c)).get_or_else failure
-- def select {α} (f : char → list (bool × reader α)) : reader α :=
-- peek >>= select_aux f
-- def try_char (p : char → Prop) [decidable_pred p] : reader (option char) :=
-- do c ← read_char,
-- if p c then pure c
-- else unread c >> pure none
-- def many_loop (p : char → Prop) [decidable_pred p] : list char → char → get_m ((list char × option char) ⊕ list char)
-- | s c :=
-- if p c then pure (sum.inr $ c :: s)
-- else pure (sum.inl (s.reverse,some c))
-- def many (p : char → Prop) [decidable_pred p] : reader (list char) :=
-- ⟨ λ n, ⟨ λ s : option char,
-- do s' ← match s with
-- | none := pure $ sum.inr []
-- | (some s) := many_loop p [] s
-- end,
-- match s' with
-- | (sum.inl x) := pure x
-- | (sum.inr x) := get_m.loop (many_loop p) pure x
-- end ⟩ ⟩
-- def parse_nat : reader ℕ :=
-- do c ← read_char,
-- guard c.is_digit,
-- cs ← many char.is_digit,
-- pure $ list.foldl (λ x (c : char), 10 * x + c.val - '0'.val) 0 (c :: cs)
-- def parse_int : reader ℤ :=
-- do x ← try_char (= '-'),
-- n ← parse_nat,
-- pure $ if x.is_some then - ↑n
-- else n
-- def parse_value : reader value :=
-- value.number <$> parse_int <* expect_char '\n'
-- -- def read_write (i n : ℕ) :
-- -- parse_value.run i -<< encode (value.number n) = some (value.number n) :=
-- -- begin
-- -- rw [encode,encode_aux,emit],
-- -- induction n using nat.strong_induction_on,
-- -- simp [to_string,has_to_string.to_string],
-- -- unfold_coes, simp [int.repr],
-- -- -- induction h : (string.to_list (to_string ↑n)) generalizing n;
-- -- -- rw [mmap'],
-- -- -- { admit },
-- -- -- { simp [monad_lift_and_then writer,parse_value,parse_int] with functor_norm, }
-- -- end
-- #eval do io.put_str_ln "",
-- io.put_str_ln $ to_string $ encode (value.object ()
-- [ ("a",value.number 3),
-- ("boo",value.array () [ value.number 3,
-- value.array () [ value.number 3, value.number 7, value.string "ho" ] ,
-- value.string "abc" ]) ])
-- end yaml
|
e4a034a441bb441963cf92e0af9c4d86a7ecd089
|
f20db13587f4dd28a4b1fbd31953afd491691fa0
|
/library/init/meta/interactive.lean
|
d6128a019822fb9548ad4bc90521a837283432cc
|
[
"Apache-2.0"
] |
permissive
|
AHartNtkn/lean
|
9a971edfc6857c63edcbf96bea6841b9a84cf916
|
0d83a74b26541421fc1aa33044c35b03759710ed
|
refs/heads/master
| 1,620,592,591,236
| 1,516,749,881,000
| 1,516,749,881,000
| 118,697,288
| 1
| 0
| null | 1,516,759,470,000
| 1,516,759,470,000
| null |
UTF-8
|
Lean
| false
| false
| 67,413
|
lean
|
/-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.tactic init.meta.rewrite_tactic init.meta.simp_tactic
import init.meta.smt.congruence_closure init.category.combinators
import init.meta.interactive_base init.meta.derive init.meta.match_tactic
import init.meta.congr_tactic
open lean
open lean.parser
local postfix `?`:9001 := optional
local postfix *:9001 := many
namespace tactic
/- allows metavars -/
meta def i_to_expr (q : pexpr) : tactic expr :=
to_expr q tt
/- allow metavars and no subgoals -/
meta def i_to_expr_no_subgoals (q : pexpr) : tactic expr :=
to_expr q tt ff
/- doesn't allows metavars -/
meta def i_to_expr_strict (q : pexpr) : tactic expr :=
to_expr q ff
/- Auxiliary version of i_to_expr for apply-like tactics.
This is a workaround for comment
https://github.com/leanprover/lean/issues/1342#issuecomment-307912291
at issue #1342.
In interactive mode, given a tactic
apply f
we want the apply tactic to create all metavariables. The following
definition will return `@f` for `f`. That is, it will **not** create
metavariables for implicit arguments.
Before we added `i_to_expr_for_apply`, the tactic
apply le_antisymm
would first elaborate `le_antisymm`, and create
@le_antisymm ?m_1 ?m_2 ?m_3 ?m_4
The type class resolution problem
?m_2 : weak_order ?m_1
by the elaborator since ?m_1 is not assigned yet, and the problem is
discarded.
Then, we would invoke `apply_core`, which would create two
new metavariables for the explicit arguments, and try to unify the resulting
type with the current target. After the unification,
the metavariables ?m_1, ?m_3 and ?m_4 are assigned, but we lost
the information about the pending type class resolution problem.
With `i_to_expr_for_apply`, `le_antisymm` is elaborate into `@le_antisymm`,
the apply_core tactic creates all metavariables, and solves the ones that
can be solved by type class resolution.
Another possible fix: we modify the elaborator to return pending
type class resolution problems, and store them in the tactic_state.
-/
meta def i_to_expr_for_apply (q : pexpr) : tactic expr :=
let aux (n : name) : tactic expr := do
p ← resolve_name n,
match p with
| (expr.const c []) := do r ← mk_const c, save_type_info r q, return r
| _ := i_to_expr p
end
in match q with
| (expr.const c []) := aux c
| (expr.local_const c _ _ _) := aux c
| _ := i_to_expr q
end
namespace interactive
open interactive interactive.types expr
/--
itactic: parse a nested "interactive" tactic. That is, parse
`{` tactic `}`
-/
meta def itactic : Type :=
tactic unit
meta def propagate_tags (tac : tactic unit) : tactic unit :=
do tag ← get_main_tag,
if tag = [] then tac
else focus1 $ do
tac,
gs ← get_goals,
when (bnot gs.empty) $ do
new_tag ← get_main_tag,
when new_tag.empty $ with_enable_tags (set_main_tag tag)
meta def concat_tags (tac : tactic (list (name × expr))) : tactic unit :=
mcond tags_enabled
(do in_tag ← get_main_tag,
r ← tac,
/- remove assigned metavars -/
r ← r.mfilter $ λ ⟨n, m⟩, bnot <$> is_assigned m,
match r with
| [(_, m)] := set_tag m in_tag /- if there is only new subgoal, we just propagate `in_tag` -/
| _ := r.mmap' (λ ⟨n, m⟩, set_tag m (n::in_tag))
end)
(tac >> skip)
/--
If the current goal is a Pi/forall `∀ x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`.
If the goal is an arrow `t → u`, then it puts `h : t` in the local context and the new goal target is `u`.
If the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails.
-/
meta def intro : parse ident_? → tactic unit
| none := propagate_tags (intro1 >> skip)
| (some h) := propagate_tags (tactic.intro h >> skip)
/--
Similar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder.
The variant `intros h₁ ... hₙ` introduces `n` new hypotheses using the given identifiers to name them.
-/
meta def intros : parse ident_* → tactic unit
| [] := propagate_tags (tactic.intros >> skip)
| hs := propagate_tags (intro_lst hs >> skip)
/--
The tactic `introv` allows the user to automatically introduce the variables of a theorem and explicitly name the hypotheses involved. The given names are used to name non-dependent hypotheses.
Examples:
```
example : ∀ a b : nat, a = b → b = a :=
begin
introv h,
exact h.symm
end
```
The state after `introv h` is
```
a b : ℕ,
h : a = b
⊢ b = a
```
```
example : ∀ a b : nat, a = b → ∀ c, b = c → a = c :=
begin
introv h₁ h₂,
exact h₁.trans h₂
end
```
The state after `introv h₁ h₂` is
```
a b : ℕ,
h₁ : a = b,
c : ℕ,
h₂ : b = c
⊢ a = c
```
-/
meta def introv (ns : parse ident_*) : tactic unit :=
propagate_tags (tactic.introv ns >> return ())
/--
The tactic `rename h₁ h₂` renames hypothesis `h₁` to `h₂` in the current local context.
-/
meta def rename (h₁ h₂ : parse ident) : tactic unit :=
propagate_tags (tactic.rename h₁ h₂)
/--
The `apply` tactic tries to match the current goal against the conclusion of the type of term. The argument term should be a term well-formed in the local context of the main goal. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones.
The `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types.
-/
meta def apply (q : parse texpr) : tactic unit :=
concat_tags (do h ← i_to_expr_for_apply q, tactic.apply h)
/--
Similar to the `apply` tactic, but does not reorder goals.
-/
meta def fapply (q : parse texpr) : tactic unit :=
concat_tags (i_to_expr_for_apply q >>= tactic.fapply)
/--
Similar to the `apply` tactic, but only creates subgoals for non-dependent premises that have not been fixed by type inference or type class resolution.
-/
meta def eapply (q : parse texpr) : tactic unit :=
concat_tags (i_to_expr_for_apply q >>= tactic.eapply)
/--
Similar to the `apply` tactic, but allows the user to provide a `apply_cfg` configuration object.
-/
meta def apply_with (q : parse parser.pexpr) (cfg : apply_cfg) : tactic unit :=
concat_tags (do e ← i_to_expr_for_apply q, tactic.apply e cfg)
/--
Similar to the `apply` tactic, but uses matching instead of unification.
`apply_match t` is equivalent to `apply_with t {unify := ff}`
-/
meta def mapply (q : parse texpr) : tactic unit :=
concat_tags (do e ← i_to_expr_for_apply q, tactic.apply e {unify := ff})
/--
This tactic tries to close the main goal `... ⊢ t` by generating a term of type `t` using type class resolution.
-/
meta def apply_instance : tactic unit :=
tactic.apply_instance
/--
This tactic behaves like `exact`, but with a big difference: the user can put underscores `_` in the expression as placeholders for holes that need to be filled, and `refine` will generate as many subgoals as there are holes.
Note that some holes may be implicit. The type of each hole must either be synthesized by the system or declared by an explicit type ascription like `(_ : nat → Prop)`.
-/
meta def refine (q : parse texpr) : tactic unit :=
tactic.refine q
/--
This tactic looks in the local context for a hypothesis whose type is equal to the goal target. If it finds one, it uses it to prove the goal, and otherwise it fails.
-/
meta def assumption : tactic unit :=
tactic.assumption
/-- Try to apply `assumption` to all goals. -/
meta def assumption' : tactic unit :=
tactic.any_goals tactic.assumption
private 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 u` replaces the target `t` of the main goal to `u` provided that `t` is well formed with respect to the local context of the main goal and `t` and `u` are definitionally equal.
`change u at h` will change a local hypothesis to `u`.
`change t with u at h1 h2 ...` will replace `t` with `u` in all the supplied hypotheses (or `*`), or in the goal if no `at` clause is specified, provided that `t` and `u` are definitionally equal.
-/
meta def change (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit
| none (loc.ns [none]) := do e ← i_to_expr q, change_core e none
| none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh)
| none _ := fail "change-at does not support multiple locations"
| (some w) l :=
do u ← mk_meta_univ,
ty ← mk_meta_var (sort u),
eq ← i_to_expr ``(%%q : %%ty),
ew ← i_to_expr ``(%%w : %%ty),
let repl := λe : expr, e.replace (λ a n, if a = eq then some ew else none),
l.try_apply
(λh, do e ← infer_type h, change_core (repl e) (some h))
(do g ← target, change_core (repl g) none)
/--
This tactic provides an exact proof term to solve the main goal. If `t` is the goal and `p` is a term of type `u` then `exact p` succeeds if and only if `t` and `u` can be unified.
-/
meta def exact (q : parse texpr) : tactic unit :=
do tgt : expr ← target,
i_to_expr_strict ``(%%q : %%tgt) >>= tactic.exact
/--
Like `exact`, but takes a list of terms and checks that all goals are discharged after the tactic.
-/
meta def exacts : parse pexpr_list_or_texpr → tactic unit
| [] := done
| (t :: ts) := exact t >> exacts ts
/--
A synonym for `exact` that allows writing `have/suffices/show ..., from ...` in tactic mode.
-/
meta def «from» := exact
/--
`revert h₁ ... hₙ` applies to any goal with hypotheses `h₁` ... `hₙ`. It moves the hypotheses and their dependencies to the target of the goal. This tactic is the inverse of `intro`.
-/
meta def revert (ids : parse ident*) : tactic unit :=
propagate_tags (do hs ← mmap tactic.get_local ids, revert_lst hs, skip)
private meta def resolve_name' (n : name) : tactic expr :=
do {
p ← resolve_name n,
match p with
| expr.const n _ := mk_const n -- create metavars for universe levels
| _ := i_to_expr p
end
}
/- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant.
This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used.
Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat.
Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/
meta def to_expr' (p : pexpr) : tactic expr :=
match p with
| (const c []) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e
| (local_const c _ _ _) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e
| _ := i_to_expr p
end
@[derive has_reflect]
meta structure rw_rule :=
(pos : pos)
(symm : bool)
(rule : pexpr)
meta def get_rule_eqn_lemmas (r : rw_rule) : tactic (list name) :=
let aux (n : name) : tactic (list name) := do {
p ← resolve_name n,
-- unpack local refs
let e := p.erase_annotations.get_app_fn.erase_annotations,
match e with
| const n _ := get_eqn_lemmas_for tt n
| _ := return []
end } <|> return [] in
match r.rule with
| const n _ := aux n
| local_const n _ _ _ := aux n
| _ := return []
end
private meta def rw_goal (cfg : rewrite_cfg) (rs : list rw_rule) : tactic unit :=
rs.mmap' $ λ r, do
save_info r.pos,
eq_lemmas ← get_rule_eqn_lemmas r,
orelse'
(do e ← to_expr' r.rule, rewrite_target e {symm := r.symm, ..cfg})
(eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_target e {symm := r.symm, ..cfg})
(eq_lemmas.empty)
private meta def uses_hyp (e : expr) (h : expr) : bool :=
e.fold ff $ λ t _ r, r || to_bool (t = h)
private meta def rw_hyp (cfg : rewrite_cfg) : list rw_rule → expr → tactic unit
| [] hyp := skip
| (r::rs) hyp := do
save_info r.pos,
eq_lemmas ← get_rule_eqn_lemmas r,
orelse'
(do e ← to_expr' r.rule, when (not (uses_hyp e hyp)) $ rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs)
(eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs)
(eq_lemmas.empty)
meta def rw_rule_p (ep : parser pexpr) : parser rw_rule :=
rw_rule.mk <$> cur_pos <*> (option.is_some <$> (with_desc "←" (tk "←" <|> tk "<-"))?) <*> ep
@[derive has_reflect]
meta structure rw_rules_t :=
(rules : list rw_rule)
(end_pos : option pos)
-- accepts the same content as `pexpr_list_or_texpr`, but with correct goal info pos annotations
meta def rw_rules : parser rw_rules_t :=
(tk "[" *>
rw_rules_t.mk <$> sep_by (skip_info (tk ",")) (set_goal_info_pos $ rw_rule_p (parser.pexpr 0))
<*> (some <$> cur_pos <* set_goal_info_pos (tk "]")))
<|> rw_rules_t.mk <$> (list.ret <$> rw_rule_p texpr) <*> return none
private meta def rw_core (rs : parse rw_rules) (loca : parse location) (cfg : rewrite_cfg) : tactic unit :=
match loca with
| loc.wildcard := loca.try_apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules)
| _ := loca.apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules)
end >> try (reflexivity reducible)
>> (returnopt rs.end_pos >>= save_info <|> skip)
/--
`rewrite e` applies identity `e` as a rewrite rule to the target of the main goal. If `e` is preceded by left arrow (`←` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational lemmas associated with `e` are used. This provides a convenient way to unfold `e`.
`rewrite [e₁, ..., eₙ]` applies the given rules sequentially.
`rewrite e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `⊢` or `|-` can also be used, to signify the target of the goal.
-/
meta def rewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit :=
propagate_tags (rw_core q l cfg)
/--
An abbreviation for `rewrite`.
-/
meta def rw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit :=
propagate_tags (rw_core q l cfg)
/--
`rewrite` followed by `assumption`.
-/
meta def rwa (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit :=
rewrite q l cfg >> try assumption
/--
A variant of `rewrite` that uses the unifier more aggressively, unfolding semireducible definitions.
-/
meta def erewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit :=
propagate_tags (rw_core q l cfg)
/--
An abbreviation for `erewrite`.
-/
meta def erw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit :=
propagate_tags (rw_core q l cfg)
precedence `generalizing` : 0
private meta def collect_hyps_uids : tactic name_set :=
do ctx ← local_context,
return $ ctx.foldl (λ r h, r.insert h.local_uniq_name) mk_name_set
private meta def revert_new_hyps (input_hyp_uids : name_set) : tactic unit :=
do ctx ← local_context,
let to_revert := ctx.foldr (λ h r, if input_hyp_uids.contains h.local_uniq_name then r else h::r) [],
tag ← get_main_tag,
m ← revert_lst to_revert,
set_main_tag (mk_num_name `_case m :: tag)
/--
Apply `t` to main goal, and revert any new hypothesis in the generated goals,
and tag generated goals when using supported tactics such as: `induction`, `apply`, `cases`, `constructor`, ...
This tactic is useful for writing robust proof scripts that are not sensitive
to the name generation strategy used by `t`.
```
example (n : ℕ) : n = n :=
begin
with_cases { induction n },
case nat.zero { reflexivity },
case nat.succ : n' ih { reflexivity }
end
```
TODO(Leo): improve docstring
-/
meta def with_cases (t : itactic) : tactic unit :=
with_enable_tags $ focus1 $ do
input_hyp_uids ← collect_hyps_uids,
t,
all_goals (revert_new_hyps input_hyp_uids)
private meta def get_type_name (e : expr) : tactic name :=
do e_type ← infer_type e >>= whnf,
(const I ls) ← return $ get_app_fn e_type,
return I
private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name)
| (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x)
| _ := fail "parse error"
private meta def generalize_arg_p : parser (pexpr × name) :=
with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux
/--
`generalize : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type.
`generalize h : e = x` in addition registers the hypothesis `h : e = x`.
-/
meta def generalize (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) : tactic unit :=
propagate_tags $
do let (p, x) := p,
e ← i_to_expr p,
some h ← pure h | tactic.generalize e x >> intro1 >> skip,
tgt ← target,
-- if generalizing fails, fall back to not replacing anything
tgt' ← do {
⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize e x >> target),
to_expr ``(Π x, %%e = x → %%(tgt'.binding_body.lift_vars 0 1))
} <|> to_expr ``(Π x, %%e = x → %%tgt),
t ← assert h tgt',
swap,
exact ``(%%t %%e rfl),
intro x,
intro h
meta def cases_arg_p : parser (option name × pexpr) :=
with_desc "(id :)? expr" $ do
t ← texpr,
match t with
| (local_const x _ _ _) :=
(tk ":" *> do t ← texpr, pure (some x, t)) <|> pure (none, t)
| _ := pure (none, t)
end
/--
Given the initial tag `in_tag` and the cases names produced by `induction` or `cases` tactic,
update the tag of the new subgoals.
-/
private meta def set_cases_tags (in_tag : tag) (rs : list name) : tactic unit :=
do te ← tags_enabled,
gs ← get_goals,
match gs with
| [g] := when te (set_tag g in_tag) -- if only one goal was produced, we should not make the tag longer
| _ := do
let tgs : list (name × expr) := rs.map₂ (λ n g, (n, g)) gs,
if te
then tgs.mmap' (λ ⟨n, g⟩, set_tag g (n::in_tag))
/- If `induction/cases` is not in a `with_cases` block, we still set tags using `_case_simple` to make
sure we can use the `case` notation.
```
induction h,
case c { ... }
```
-/
else tgs.mmap' (λ ⟨n, g⟩, with_enable_tags (set_tag g (`_case_simple::n::[])))
end
private meta def set_induction_tags (in_tag : tag) (rs : list (name × list expr × list (name × expr))) : tactic unit :=
set_cases_tags in_tag (rs.map (λ e, e.1))
/--
Assuming `x` is a variable in the local context with an inductive type, `induction x` applies induction on `x` to the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor and an inductive hypothesis is added for each recursive argument to the constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the inductive hypothesis incorporates that hypothesis as well.
For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypotheses `h : P (nat.succ a)` and `ih₁ : P a → Q a` and target `Q (nat.succ a)`. Here the names `a` and `ih₁` ire chosen automatically.
`induction e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then performs induction on the resulting variable.
`induction e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors and inductive hypotheses, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. Note that for long sequences of names, the `case` tactic provides a more convenient naming mechanism.
`induction e using r` allows the user to specify the principle of induction that should be used. Here `r` should be a theorem whose result type must be of the form `C t`, where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables
`induction e generalizing z₁ ... zₙ`, where `z₁ ... zₙ` are variables in the local context, generalizes over `z₁ ... zₙ` before applying the induction but then introduces them in each goal. In other words, the net effect is that each inductive hypothesis is generalized.
`induction h : t` will introduce an equality of the form `h : t = C x y`, asserting that the input term is equal to the current constructor case, to the context.
-/
meta def induction (hp : parse cases_arg_p) (rec_name : parse using_ident) (ids : parse with_ident_list)
(revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit :=
do in_tag ← get_main_tag,
focus1 $ do {
-- process `h : t` case
e ← match hp with
| (some h, p) := do
x ← mk_fresh_name,
generalize h () (p, x),
get_local x
| (none, p) := i_to_expr p
end,
-- generalize major premise
e ← if e.is_local_constant then pure e
else tactic.generalize e >> intro1,
-- generalize major premise args
(e, newvars, locals) ← do {
none ← pure rec_name | pure (e, [], []),
t ← infer_type e,
t ← whnf_ginductive t,
const n _ ← pure t.get_app_fn | pure (e, [], []),
env ← get_env,
tt ← pure $ env.is_inductive n | pure (e, [], []),
let (locals, nonlocals) := (t.get_app_args.drop $ env.inductive_num_params n).partition
(λ arg : expr, arg.is_local_constant),
_ :: _ ← pure nonlocals | pure (e, [], []),
n ← tactic.revert e,
newvars ← nonlocals.mmap $ λ arg, do {
n ← revert_kdeps arg,
tactic.generalize arg,
h ← intro1,
intron n,
-- now try to clear hypotheses that may have been abstracted away
let locals := arg.fold [] (λ e _ acc, if e.is_local_constant then e::acc else acc),
locals.mmap' (try ∘ clear),
pure h
},
intron (n-1),
e ← intro1,
pure (e, newvars, locals)
},
-- revert `generalizing` params
n ← mmap tactic.get_local (revert.get_or_else []) >>= revert_lst,
rs ← tactic.induction e ids rec_name,
all_goals $ do {
intron n,
clear_lst (newvars.map local_pp_name),
(e::locals).mmap' (try ∘ clear) },
set_induction_tags in_tag rs }
private meta def is_case_simple_tag : tag → bool
| (`_case_simple :: _) := tt
| _ := ff
private meta def is_case_tag : tag → option nat
| (name.mk_numeral n `_case :: _) := some n.val
| _ := none
private meta def tag_match (t : tag) (pre : list name) : bool :=
pre.is_prefix_of t.reverse &&
((is_case_tag t).is_some || is_case_simple_tag t)
private meta def collect_tagged_goals (pre : list name) : tactic (list expr) :=
do gs ← get_goals,
gs.mfoldr (λ g r, do
t ← get_tag g,
if tag_match t pre then return (g::r) else return r)
[]
private meta def find_tagged_goal_aux (pre : list name) : tactic expr :=
do gs ← collect_tagged_goals pre,
match gs with
| [] := fail ("invalid `case`, there is no goal tagged with prefix " ++ to_string pre)
| [g] := return g
| gs := do
tags : list (list name) ← gs.mmap get_tag,
fail ("invalid `case`, there is more than one goal tagged with prefix " ++ to_string pre ++ ", matching tags: " ++ to_string tags)
end
private meta def find_tagged_goal (pre : list name) : tactic expr :=
match pre with
| [] := do g::gs ← get_goals, return g
| _ :=
find_tagged_goal_aux pre
<|>
-- try to resolve constructor names, and try again
do env ← get_env,
pre ← pre.mmap (λ id,
(do r_id ← resolve_constant id,
if (env.inductive_type_of r_id).is_none then return id
else return r_id)
<|> return id),
find_tagged_goal_aux pre
end
private meta def find_case (goals : list expr) (ty : name) (idx : nat) (num_indices : nat) : option expr → expr → option (expr × expr)
| case e := if e.has_meta_var then match e with
| (mvar _ _ _) :=
do case ← case,
guard $ e ∈ goals,
pure (case, e)
| (app _ _) :=
let idx :=
match e.get_app_fn with
| const (name.mk_string rec ty') _ :=
guard (ty' = ty) >>
match mk_simple_name rec with
| `drec := some idx | `rec := some idx
-- indices + major premise
| `dcases_on := some (idx + num_indices + 1) | `cases_on := some (idx + num_indices + 1)
| _ := none
end
| _ := none
end in
match idx with
| none := list.foldl (<|>) (find_case case e.get_app_fn) $ e.get_app_args.map (find_case case)
| some idx :=
let args := e.get_app_args in
do arg ← args.nth idx,
args.enum.foldl
(λ acc ⟨i, arg⟩, match acc with
| some _ := acc
| _ := if i ≠ idx then find_case none arg else none
end)
-- start recursion with likely case
(find_case (some arg) arg)
end
| (lam _ _ _ e) := find_case case e
| (macro n args) := list.foldl (<|>) none $ args.map (find_case case)
| _ := none
end else none
private meta def rename_lams : expr → list name → tactic unit
| (lam n _ _ e) (n'::ns) := (rename n n' >> rename_lams e ns) <|> rename_lams e (n'::ns)
| _ _ := skip
/--
Focuses on the `induction`/`cases`/`with_cases` subgoal corresponding to the given tag prefix, optionally renaming introduced locals.
```
example (n : ℕ) : n = n :=
begin
induction n,
case nat.zero { reflexivity },
case nat.succ : a ih { reflexivity }
end
```
-/
meta def case (pre : parse ident_*) (ids : parse $ (tk ":" *> ident_*)?) (tac : itactic) : tactic unit :=
do g ← find_tagged_goal pre,
tag ← get_tag g,
let ids := ids.get_or_else [],
match is_case_tag tag with
| some n := do
let m := ids.length,
gs ← get_goals,
set_goals $ g :: gs.filter (≠ g),
intro_lst ids,
when (m < n) $ intron (n - m),
solve1 tac
| none :=
match is_case_simple_tag tag with
| tt :=
/- Use the old `case` implementation -/
do r ← result,
env ← get_env,
[ctor_id] ← return pre,
ctor ← resolve_constant ctor_id
<|> fail ("'" ++ to_string ctor_id ++ "' is not a constructor"),
ty ← (env.inductive_type_of ctor).to_monad
<|> fail ("'" ++ to_string ctor ++ "' is not a constructor"),
let ctors := env.constructors_of ty,
let idx := env.inductive_num_params ty + /- motive -/ 1 +
list.index_of ctor ctors,
/- Remark: we now use `find_case` just to locate the `lambda` used in `rename_lams`.
The goal is now located using tags. -/
(case, _) ← (find_case [g] ty idx (env.inductive_num_indices ty) none r ).to_monad
<|> fail "could not find open goal of given case",
gs ← get_goals,
set_goals $ g :: gs.filter (≠ g),
rename_lams case ids,
solve1 tac
| ff := failed
end
end
/--
Assuming `x` is a variable in the local context with an inductive type, `destruct x` splits the main goal, producing one goal for each constructor of the inductive type, in which `x` is assumed to be a general instance of that constructor. In contrast to `cases`, the local context is unchanged, i.e. no elements are reverted or introduced.
For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `destruct n` produces one goal with target `n = 0 → Q n`, and one goal with target `∀ (a : ℕ), (λ (w : ℕ), n = w → Q n) (nat.succ a)`. Here the name `a` is chosen automatically.
-/
meta def destruct (p : parse texpr) : tactic unit :=
i_to_expr p >>= tactic.destruct
meta def cases_core (e : expr) (ids : list name := []) : tactic unit :=
do in_tag ← get_main_tag,
focus1 $ do
rs ← tactic.cases e ids,
set_cases_tags in_tag rs
/--
Assuming `x` is a variable in the local context with an inductive type, `cases x` splits the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the case split affects that hypothesis as well.
For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypothesis `h : P (nat.succ a)` and target `Q (nat.succ a)`. Here the name `a` is chosen automatically.
`cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then cases on the resulting variable.
`cases e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically.
`cases h : e`, where `e` is a variable or an expression, performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis, where `...` is the constructor instance for that particular case.
-/
meta def cases : parse cases_arg_p → parse with_ident_list → tactic unit
| (none, p) ids := do
e ← i_to_expr p,
cases_core e ids
| (some h, p) ids := do
x ← mk_fresh_name,
generalize h () (p, x),
hx ← get_local x,
cases_core hx ids
private meta def find_matching_hyp (ps : list pattern) : tactic expr :=
any_hyp $ λ h, do
type ← infer_type h,
ps.mfirst $ λ p, do
match_pattern p type,
return h
/--
`cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`.
`cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns.
`cases_matching* p` more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once.
Example: The following tactic destructs all conjunctions and disjunctions in the current goal.
```
cases_matching* [_ ∨ _, _ ∧ _]
```
-/
meta def cases_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit :=
do ps ← ps.mmap pexpr_to_pattern,
if rec.is_none
then find_matching_hyp ps >>= cases_core
else tactic.focus1 $ tactic.repeat $ find_matching_hyp ps >>= cases_core
/-- Shorthand for `cases_matching` -/
meta def casesm (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit :=
cases_matching rec ps
private meta def try_cases_for_types (type_names : list name) (at_most_one : bool) : tactic unit :=
any_hyp $ λ h, do
I ← expr.get_app_fn <$> (infer_type h >>= head_beta),
guard I.is_constant,
guard (I.const_name ∈ type_names),
tactic.focus1 (cases_core h >> if at_most_one then do n ← num_goals, guard (n <= 1) else skip)
/--
`cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)`
`cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)`
`cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }`
`cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1.
Example: The following tactic destructs all conjunctions and disjunctions in the current goal.
```
cases_type* or and
```
-/
meta def cases_type (one : parse $ (tk "!")?) (rec : parse $ (tk "*")?) (type_names : parse ident*) : tactic unit :=
do type_names ← type_names.mmap resolve_constant,
if rec.is_none
then try_cases_for_types type_names (bnot one.is_none)
else tactic.focus1 $ tactic.repeat $ try_cases_for_types type_names (bnot one.is_none)
/--
Tries to solve the current goal using a canonical proof of `true`, or the `reflexivity` tactic, or the `contradiction` tactic.
-/
meta def trivial : tactic unit :=
tactic.triv <|> tactic.reflexivity <|> tactic.contradiction <|> fail "trivial tactic failed"
/--
Closes the main goal using `sorry`.
-/
meta def admit : tactic unit := tactic.admit
/--
Closes the main goal using `sorry`.
-/
meta def «sorry» : tactic unit := tactic.admit
/--
The contradiction tactic attempts to find in the current local context a hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses.
-/
meta def contradiction : tactic unit :=
tactic.contradiction
/--
`iterate { t }` repeatedly applies tactic `t` until `t` fails. `iterate { t }` always succeeds.
`iterate n { t }` applies `t` `n` times.
-/
meta def iterate (n : parse small_nat?) (t : itactic) : tactic unit :=
match n with
| none := tactic.iterate t
| some n := iterate_exactly n t
end
/--
`repeat { t }` applies `t` to each goal. If the application succeeds,
the tactic is applied recursively to all the generated subgoals until it eventually fails.
The recursion stops in a subgoal when the tactic has failed to make progress.
The tactic `repeat { t }` never fails.
-/
meta def repeat : itactic → tactic unit :=
tactic.repeat
/--
`try { t }` tries to apply tactic `t`, but succeeds whether or not `t` succeeds.
-/
meta def try : itactic → tactic unit :=
tactic.try
/--
A do-nothing tactic that always succeeds.
-/
meta def skip : tactic unit :=
tactic.skip
/--
`solve1 { t }` applies the tactic `t` to the main goal and fails if it is not solved.
-/
meta def solve1 : itactic → tactic unit :=
tactic.solve1
/--
`abstract id { t }` tries to use tactic `t` to solve the main goal. If it succeeds, it abstracts the goal as an independent definition or theorem with name `id`. If `id` is omitted, a name is generated automatically.
-/
meta def abstract (id : parse ident?) (tac : itactic) : tactic unit :=
tactic.abstract tac id
/--
`all_goals { t }` applies the tactic `t` to every goal, and succeeds if each application succeeds.
-/
meta def all_goals : itactic → tactic unit :=
tactic.all_goals
/--
`any_goals { t }` applies the tactic `t` to every goal, and succeeds if at least one application succeeds.
-/
meta def any_goals : itactic → tactic unit :=
tactic.any_goals
/--
`focus { t }` temporarily hides all goals other than the first, applies `t`, and then restores the other goals. It fails if there are no goals.
-/
meta def focus (tac : itactic) : tactic unit :=
tactic.focus1 tac
private meta def assume_core (n : name) (ty : pexpr) :=
do t ← target,
when (not $ t.is_pi ∨ t.is_let) whnf_target,
t ← target,
when (not $ t.is_pi ∨ t.is_let) $
fail "assume tactic failed, Pi/let expression expected",
ty ← i_to_expr ty,
unify ty t.binding_domain,
intro_core n >> skip
/--
Assuming the target of the goal is a Pi or a let, `assume h : t` unifies the type of the binder with `t` and introduces it with name `h`, just like `intro h`. If `h` is absent, the tactic uses the name `this`. If `t` is omitted, it will be inferred.
`assume (h₁ : t₁) ... (hₙ : tₙ)` introduces multiple hypotheses. Any of the types may be omitted, but the names must be present.
-/
meta def «assume» : parse (sum.inl <$> (tk ":" *> texpr) <|> sum.inr <$> parse_binders tac_rbp) → tactic unit
| (sum.inl ty) := assume_core `this ty
| (sum.inr binders) :=
binders.mmap' $ λ b, assume_core b.local_pp_name b.local_type
/--
`have h : t := p` adds the hypothesis `h : t` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred.
`have h : t` adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable.
If `h` is omitted, the name `this` is used.
-/
meta def «have» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit :=
let h := h.get_or_else `this in
match q₁, q₂ with
| some e, some p := do
t ← i_to_expr e,
v ← i_to_expr ``(%%p : %%t),
tactic.assertv h t v
| none, some p := do
p ← i_to_expr p,
tactic.note h none p
| some e, none := i_to_expr e >>= tactic.assert h
| none, none := do
u ← mk_meta_univ,
e ← mk_meta_var (sort u),
tactic.assert h e
end >> skip
/--
`let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred.
`let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable.
If `h` is omitted, the name `this` is used.
-/
meta def «let» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit :=
let h := h.get_or_else `this in
match q₁, q₂ with
| some e, some p := do
t ← i_to_expr e,
v ← i_to_expr ``(%%p : %%t),
tactic.definev h t v
| none, some p := do
p ← i_to_expr p,
tactic.pose h none p
| some e, none := i_to_expr e >>= tactic.define h
| none, none := do
u ← mk_meta_univ,
e ← mk_meta_var (sort u),
tactic.define h e
end >> skip
/--
`suffices h : t` is the same as `have h : t, tactic.swap`. In other words, it adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`.
-/
meta def «suffices» (h : parse ident?) (t : parse (tk ":" *> texpr)?) : tactic unit :=
«have» h t none >> tactic.swap
/--
This tactic displays the current state in the tracing buffer.
-/
meta def trace_state : tactic unit :=
tactic.trace_state
/--
`trace a` displays `a` in the tracing buffer.
-/
meta def trace {α : Type} [has_to_tactic_format α] (a : α) : tactic unit :=
tactic.trace a
/--
`existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals.
`existsi [e₁, ..., eₙ]` iteratively does the same for each expression in the list.
-/
meta def existsi : parse pexpr_list_or_texpr → tactic unit
| [] := return ()
| (p::ps) := i_to_expr p >>= tactic.existsi >> existsi ps
/--
This tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds.
-/
meta def constructor : tactic unit :=
concat_tags tactic.constructor
/--
Similar to `constructor`, but only non-dependent premises are added as new goals.
-/
meta def econstructor : tactic unit :=
concat_tags tactic.econstructor
/--
Applies the first constructor when the type of the target is an inductive data type with two constructors.
-/
meta def left : tactic unit :=
concat_tags tactic.left
/--
Applies the second constructor when the type of the target is an inductive data type with two constructors.
-/
meta def right : tactic unit :=
concat_tags tactic.right
/--
Applies the constructor when the type of the target is an inductive data type with one constructor.
-/
meta def split : tactic unit :=
concat_tags tactic.split
private meta def constructor_matching_aux (ps : list pattern) : tactic unit :=
do t ← target, ps.mfirst (λ p, match_pattern p t), constructor
meta def constructor_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit :=
do ps ← ps.mmap pexpr_to_pattern,
if rec.is_none then constructor_matching_aux ps
else tactic.focus1 $ tactic.repeat $ constructor_matching_aux ps
/--
Replaces the target of the main goal by `false`.
-/
meta def exfalso : tactic unit :=
tactic.exfalso
/--
The `injection` tactic is based on the fact that constructors of inductive data types are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t₁)` and `(c t₂)` are two terms that are equal then `t₁` and `t₂` are equal too.
If `q` is a proof of a statement of conclusion `t₁ = t₂`, then injection applies injectivity to derive the equality of all arguments of `t₁` and `t₂` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t₁` and `t₂` should be constructor applications of the same constructor.
Given `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h₁ h₂` uses the names `h₁` and `h₂` to name the new hypotheses.
-/
meta def injection (q : parse texpr) (hs : parse with_ident_list) : tactic unit :=
do e ← i_to_expr q, tactic.injection_with e hs, try assumption
/--
`injections with h₁ ... hₙ` iteratively applies `injection` to hypotheses using the names `h₁ ... hₙ`.
-/
meta def injections (hs : parse with_ident_list) : tactic unit :=
do tactic.injections_with hs, try assumption
end interactive
meta structure simp_config_ext extends simp_config :=
(discharger : tactic unit := failed)
section mk_simp_set
open expr interactive.types
@[derive has_reflect]
meta inductive simp_arg_type : Type
| all_hyps : simp_arg_type
| except : name → simp_arg_type
| expr : pexpr → simp_arg_type
meta def simp_arg : parser simp_arg_type :=
(tk "*" *> return simp_arg_type.all_hyps) <|> (tk "-" *> simp_arg_type.except <$> ident) <|> (simp_arg_type.expr <$> texpr)
meta def simp_arg_list : parser (list simp_arg_type) :=
(tk "*" *> return [simp_arg_type.all_hyps]) <|> list_of simp_arg <|> return []
private meta def resolve_exception_ids (all_hyps : bool) : list name → list name → list name → tactic (list name × list name)
| [] gex hex := return (gex.reverse, hex.reverse)
| (id::ids) gex hex := do
p ← resolve_name id,
let e := p.erase_annotations.get_app_fn.erase_annotations,
match e with
| const n _ := resolve_exception_ids ids (n::gex) hex
| local_const n _ _ _ := when (not all_hyps) (fail $ sformat! "invalid local exception {id}, '*' was not used") >>
resolve_exception_ids ids gex (n::hex)
| _ := fail $ sformat! "invalid exception {id}, unknown identifier"
end
/- Return (hs, gex, hex, all) -/
meta def decode_simp_arg_list (hs : list simp_arg_type) : tactic $ list pexpr × list name × list name × bool :=
do
let (hs, ex, all) := hs.foldl
(λ r h,
match r, h with
| (es, ex, all), simp_arg_type.all_hyps := (es, ex, tt)
| (es, ex, all), simp_arg_type.except id := (es, id::ex, all)
| (es, ex, all), simp_arg_type.expr e := (e::es, ex, all)
end)
([], [], ff),
(gex, hex) ← resolve_exception_ids all ex [] [],
return (hs.reverse, gex, hex, all)
private 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
private meta def report_invalid_simp_lemma {α : Type} (n : name): tactic α :=
fail format!"invalid simplification lemma '{n}' (use command 'set_option trace.simp_lemmas true' for more details)"
private meta def check_no_overload (p : pexpr) : tactic unit :=
when p.is_choice_macro $
match p with
| macro _ ps :=
fail $ to_fmt "ambiguous overload, possible interpretations" ++
format.join (ps.map (λ p, (to_fmt p).indent 4))
| _ := failed
end
private meta def simp_lemmas.resolve_and_add (s : simp_lemmas) (u : list name) (n : name) (ref : pexpr) : tactic (simp_lemmas × list name) :=
do
p ← resolve_name n,
check_no_overload p,
-- unpack local refs
let e := p.erase_annotations.get_app_fn.erase_annotations,
match e with
| const n _ :=
(do b ← is_valid_simp_lemma_cnst n, guard b, save_const_type_info n ref, s ← s.add_simp n, return (s, u))
<|>
(do eqns ← get_eqn_lemmas_for tt n, guard (eqns.length > 0), save_const_type_info n ref, s ← add_simps s eqns, return (s, u))
<|>
(do env ← get_env, guard (env.is_projection n).is_some, return (s, n::u))
<|>
report_invalid_simp_lemma n
| _ :=
(do e ← i_to_expr_no_subgoals p, b ← is_valid_simp_lemma e, guard b, try (save_type_info e ref), s ← s.add e, return (s, u))
<|>
report_invalid_simp_lemma n
end
private meta def simp_lemmas.add_pexpr (s : simp_lemmas) (u : list name) (p : pexpr) : tactic (simp_lemmas × list name) :=
match p with
| (const c []) := simp_lemmas.resolve_and_add s u c p
| (local_const c _ _ _) := simp_lemmas.resolve_and_add s u c p
| _ := do new_e ← i_to_expr_no_subgoals p, s ← s.add new_e, return (s, u)
end
private meta def simp_lemmas.append_pexprs : simp_lemmas → list name → list pexpr → tactic (simp_lemmas × list name)
| s u [] := return (s, u)
| s u (l::ls) := do (s, u) ← simp_lemmas.add_pexpr s u l, simp_lemmas.append_pexprs s u ls
meta def mk_simp_set_core (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) (at_star : bool)
: tactic (bool × simp_lemmas × list name) :=
do (hs, gex, hex, all_hyps) ← decode_simp_arg_list hs,
when (all_hyps ∧ at_star ∧ not hex.empty) $ fail "A tactic of the form `simp [*, -h] at *` is currently not supported",
s ← join_user_simp_lemmas no_dflt attr_names,
(s, u) ← simp_lemmas.append_pexprs s [] hs,
s ← if not at_star ∧ all_hyps then do
ctx ← collect_ctx_simps,
let ctx := ctx.filter (λ h, h.local_uniq_name ∉ hex), -- remove local exceptions
s.append ctx
else return s,
-- add equational lemmas, if any
gex ← gex.mmap (λ n, list.cons n <$> get_eqn_lemmas_for tt n),
return (all_hyps, simp_lemmas.erase s $ gex.join, u)
meta def mk_simp_set (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) : tactic (simp_lemmas × list name) :=
prod.snd <$> (mk_simp_set_core no_dflt attr_names hs ff)
end mk_simp_set
namespace interactive
open interactive interactive.types expr
meta def simp_core_aux (cfg : simp_config) (discharger : tactic unit) (s : simp_lemmas) (u : list name) (hs : list expr) (tgt : bool) : tactic unit :=
do to_remove ← hs.mfilter $ λ h, do {
h_type ← infer_type h,
(do (new_h_type, pr) ← simplify s u h_type cfg `eq discharger,
assert h.local_pp_name new_h_type,
mk_eq_mp pr h >>= tactic.exact >> return tt)
<|>
(return ff) },
goal_simplified ← if tgt then (simp_target s u cfg discharger >> return tt) <|> (return ff) else return ff,
guard (cfg.fail_if_unchanged = ff ∨ to_remove.length > 0 ∨ goal_simplified) <|> fail "simplify tactic failed to simplify",
to_remove.mmap' (λ h, try (clear h))
meta def simp_core (cfg : simp_config) (discharger : tactic unit)
(no_dflt : bool) (hs : list simp_arg_type) (attr_names : list name)
(locat : loc) : tactic unit :=
match locat with
| loc.wildcard := do (all_hyps, s, u) ← mk_simp_set_core no_dflt attr_names hs tt,
if all_hyps then tactic.simp_all s u cfg discharger
else do hyps ← non_dep_prop_hyps, simp_core_aux cfg discharger s u hyps tt
| _ := do (s, u) ← mk_simp_set no_dflt attr_names hs,
ns ← locat.get_locals,
simp_core_aux cfg discharger s u ns locat.include_goal
end
>> try tactic.triv >> try (tactic.reflexivity reducible)
/--
The `simp` tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants.
`simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`.
`simp [h₁ h₂ ... hₙ]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `hᵢ`'s, where the `hᵢ`'s are expressions. If an `hᵢ` is a defined constant `f`, then the equational lemmas associated with `f` are used. This provides a convenient way to unfold `f`.
`simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses.
`simp *` is a shorthand for `simp [*]`.
`simp only [h₁ h₂ ... hₙ]` is like `simp [h₁ h₂ ... hₙ]` but does not use `[simp]` lemmas
`simp [-id_1, ... -id_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `idᵢ`.
`simp at h₁ h₂ ... hₙ` simplifies the non-dependent hypotheses `h₁ : T₁` ... `hₙ : Tₙ`. The tactic fails if the target or another hypothesis depends on one of them. The token `⊢` or `|-` can be added to the list to include the target.
`simp at *` simplifies all the hypotheses and the target.
`simp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses.
`simp with attr₁ ... attrₙ` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr₁]`, ..., `[attrₙ]` or `[simp]`.
-/
meta def 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 : simp_config_ext := {}) : tactic unit :=
let cfg := if use_iota_eqn.is_none then cfg else {iota_eqn := tt, ..cfg} in
propagate_tags (simp_core cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat)
/--
Just construct the simp set and trace it. Used for debugging.
-/
meta def trace_simp_set (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) : tactic unit :=
do (s, _) ← mk_simp_set no_dflt attr_names hs,
s.pp >>= trace
/--
`simp_intros h₁ h₂ ... hₙ` is similar to `intros h₁ h₂ ... hₙ` except that each hypothesis is simplified as it is introduced, and each introduced hypothesis is used to simplify later ones and the final target.
As with `simp`, a list of simplification lemmas can be provided. The modifiers `only` and `with` behave as with `simp`.
-/
meta def simp_intros (ids : parse ident_*) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list)
(cfg : simp_intros_config := {}) : tactic unit :=
do (s, u) ← mk_simp_set no_dflt attr_names hs,
when (¬u.empty) (fail (sformat! "simp_intros tactic does not support {u}")),
tactic.simp_intros s u ids cfg,
try triv >> try (reflexivity reducible)
private meta def to_simp_arg_list (es : list pexpr) : list simp_arg_type :=
es.map simp_arg_type.expr
/--
`dsimp` is similar to `simp`, except that it only uses definitional equalities.
-/
meta def dsimp (no_dflt : parse only_flag) (es : parse simp_arg_list) (attr_names : parse with_ident_list)
(l : parse location) (cfg : dsimp_config := {}) : tactic unit :=
do (s, u) ← mk_simp_set no_dflt attr_names es,
match l with
| loc.wildcard := do ls ← local_context, n ← revert_lst ls, dsimp_target s u cfg, intron n
| _ := l.apply (λ h, dsimp_hyp h s u cfg) (dsimp_target s u cfg)
end
/--
This tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal.
-/
meta def reflexivity : tactic unit :=
tactic.reflexivity
/--
Shorter name for the tactic `reflexivity`.
-/
meta def refl : tactic unit :=
tactic.reflexivity
/--
This tactic applies to a goal whose target has the form `t ~ u` where `~` is a symmetric relation, that is, a relation which has a symmetry lemma tagged with the attribute `[symm]`. It replaces the target with `u ~ t`.
-/
meta def symmetry : tactic unit :=
tactic.symmetry
/--
This tactic applies to a goal whose target has the form `t ~ u` where `~` is a transitive relation, that is, a relation which has a transitivity lemma tagged with the attribute `[trans]`.
`transitivity s` replaces the goal with the two subgoals `t ~ s` and `s ~ u`. If `s` is omitted, then a metavariable is used instead.
-/
meta def transitivity (q : parse texpr?) : tactic unit :=
tactic.transitivity >> match q with
| none := skip
| some q :=
do (r, lhs, rhs) ← target_lhs_rhs,
i_to_expr q >>= unify rhs
end
/--
Proves a goal with target `s = t` when `s` and `t` are equal up to the associativity and commutativity of their binary operations.
-/
meta def ac_reflexivity : tactic unit :=
tactic.ac_refl
/--
An abbreviation for `ac_reflexivity`.
-/
meta def ac_refl : tactic unit :=
tactic.ac_refl
/--
Tries to prove the main goal using congruence closure.
-/
meta def cc : tactic unit :=
tactic.cc
/--
Given hypothesis `h : x = t` or `h : t = x`, where `x` is a local constant, `subst h` substitutes `x` by `t` everywhere in the main goal and then clears `h`.
-/
meta def subst (q : parse texpr) : tactic unit :=
i_to_expr q >>= tactic.subst >> try (tactic.reflexivity reducible)
/--
Apply `subst` to all hypotheses of the form `h : x = t` or `h : t = x`.
-/
meta def subst_vars : tactic unit :=
tactic.subst_vars
/--
`clear h₁ ... hₙ` tries to clear each hypothesis `hᵢ` from the local context.
-/
meta def clear : parse ident* → tactic unit :=
tactic.clear_lst
private meta def to_qualified_name_core : name → list name → tactic name
| n [] := fail $ "unknown declaration '" ++ to_string n ++ "'"
| n (ns::nss) := do
curr ← return $ ns ++ n,
env ← get_env,
if env.contains curr then return curr
else to_qualified_name_core n nss
private meta def to_qualified_name (n : name) : tactic name :=
do env ← get_env,
if env.contains n then return n
else do
ns ← open_namespaces,
to_qualified_name_core n ns
private meta def to_qualified_names : list name → tactic (list name)
| [] := return []
| (c::cs) := do new_c ← to_qualified_name c, new_cs ← to_qualified_names cs, return (new_c::new_cs)
/--
Similar to `unfold`, but only uses definitional equalities.
-/
meta def dunfold (cs : parse ident*) (l : parse location) (cfg : dunfold_config := {}) : tactic unit :=
match l with
| (loc.wildcard) := do ls ← tactic.local_context,
n ← revert_lst ls,
new_cs ← to_qualified_names cs,
dunfold_target new_cs cfg,
intron n
| _ := do new_cs ← to_qualified_names cs, l.apply (λ h, dunfold_hyp cs h cfg) (dunfold_target new_cs cfg)
end
private meta def delta_hyps : list name → list name → tactic unit
| cs [] := skip
| cs (h::hs) := get_local h >>= delta_hyp cs >> delta_hyps cs hs
/--
Similar to `dunfold`, but performs a raw delta reduction, rather than using an equation associated with the defined constants.
-/
meta def delta : parse ident* → parse location → tactic unit
| cs (loc.wildcard) := do ls ← tactic.local_context,
n ← revert_lst ls,
new_cs ← to_qualified_names cs,
delta_target new_cs,
intron n
| cs l := do new_cs ← to_qualified_names cs, l.apply (delta_hyp new_cs) (delta_target new_cs)
private meta def unfold_projs_hyps (cfg : unfold_proj_config := {}) (hs : list name) : tactic bool :=
hs.mfoldl (λ r h, do h ← get_local h, (unfold_projs_hyp h cfg >> return tt) <|> return r) ff
/--
This tactic unfolds all structure projections.
-/
meta def unfold_projs (l : parse location) (cfg : unfold_proj_config := {}) : tactic unit :=
match l with
| loc.wildcard := do ls ← local_context,
b₁ ← unfold_projs_hyps cfg (ls.map expr.local_pp_name),
b₂ ← (tactic.unfold_projs_target cfg >> return tt) <|> return ff,
when (not b₁ ∧ not b₂) (fail "unfold_projs failed to simplify")
| _ :=
l.try_apply (λ h, unfold_projs_hyp h cfg)
(tactic.unfold_projs_target cfg) <|> fail "unfold_projs failed to simplify"
end
end interactive
meta def ids_to_simp_arg_list (tac_name : name) (cs : list name) : tactic (list simp_arg_type) :=
cs.mmap $ λ c, do
n ← resolve_name c,
hs ← get_eqn_lemmas_for ff n.const_name,
env ← get_env,
let p := env.is_projection n.const_name,
when (hs.empty ∧ p.is_none) (fail (sformat! "{tac_name} tactic failed, {c} does not have equational lemmas nor is a projection")),
return $ simp_arg_type.expr (expr.const c [])
structure unfold_config extends simp_config :=
(zeta := ff)
(proj := ff)
(eta := ff)
(canonize_instances := ff)
(constructor_eq := ff)
namespace interactive
open interactive interactive.types expr
/--
Given defined constants `e₁ ... eₙ`, `unfold e₁ ... eₙ` iteratively unfolds all occurrences in the target of the main goal, using equational lemmas associated with the definitions.
As with `simp`, the `at` modifier can be used to specify locations for the unfolding.
-/
meta def unfold (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {}) : tactic unit :=
do es ← ids_to_simp_arg_list "unfold" cs,
let no_dflt := tt,
simp_core cfg.to_simp_config failed no_dflt es [] locat
/--
Similar to `unfold`, but does not iterate the unfolding.
-/
meta def unfold1 (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {single_pass := tt}) : tactic unit :=
unfold cs locat cfg
/--
If the target of the main goal is an `opt_param`, assigns the default value.
-/
meta def apply_opt_param : tactic unit :=
tactic.apply_opt_param
/--
If the target of the main goal is an `auto_param`, executes the associated tactic.
-/
meta def apply_auto_param : tactic unit :=
tactic.apply_auto_param
/--
Fails if the given tactic succeeds.
-/
meta def fail_if_success (tac : itactic) : tactic unit :=
tactic.fail_if_success tac
/--
Succeeds if the given tactic fails.
-/
meta def success_if_fail (tac : itactic) : tactic unit :=
tactic.success_if_fail tac
meta def guard_expr_eq (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit :=
do e ← to_expr p, guard (alpha_eqv t e)
/--
`guard_target t` fails if the target of the main goal is not `t`.
We use this tactic for writing tests.
-/
meta def guard_target (p : parse texpr) : tactic unit :=
do t ← target, guard_expr_eq t p
/--
`guard_hyp h := t` fails if the hypothesis `h` does not have type `t`.
We use this tactic for writing tests.
-/
meta def guard_hyp (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit :=
do h ← get_local n >>= infer_type, guard_expr_eq h p
/--
`match_target t` fails if target does not match pattern `t`.
-/
meta def match_target (t : parse texpr) (m := reducible) : tactic unit :=
tactic.match_target t m >> skip
/--
`by_cases (h :)? p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch.
This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use `local attribute classical.prop_decidable [instance]`.
-/
meta def by_cases : parse cases_arg_p → tactic unit
| (n, q) := concat_tags $ do
p ← tactic.to_expr_strict q,
tactic.by_cases p (n.get_or_else `h),
pos_g :: neg_g :: rest ← get_goals,
return [(`pos, pos_g), (`neg, neg_g)]
/--
Apply function extensionality and introduce new hypotheses.
The tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to
```
|- ((fun x, ...) = (fun x, ...))
```
The variant `funext h₁ ... hₙ` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses.
-/
meta def funext : parse ident_* → tactic unit
| [] := tactic.funext >> skip
| hs := funext_lst hs >> skip
/--
If the target of the main goal is a proposition `p`, `by_contradiction h` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. If `h` is omitted, a name is generated automatically.
This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use `local attribute classical.prop_decidable [instance]`.
-/
meta def by_contradiction (n : parse ident?) : tactic unit :=
tactic.by_contradiction n >> return ()
/--
An abbreviation for `by_contradiction`.
-/
meta def by_contra (n : parse ident?) : tactic unit :=
by_contradiction n
/--
Type check the given expression, and trace its type.
-/
meta def type_check (p : parse texpr) : tactic unit :=
do e ← to_expr p, tactic.type_check e, infer_type e >>= trace
/--
Fail if there are unsolved goals.
-/
meta def done : tactic unit :=
tactic.done
private meta def show_aux (p : pexpr) : list expr → list expr → tactic unit
| [] r := fail "show tactic failed"
| (g::gs) r := do
do {set_goals [g], g_ty ← target, ty ← i_to_expr p, unify g_ty ty, set_goals (g :: r.reverse ++ gs), tactic.change ty}
<|>
show_aux gs (g::r)
/--
`show t` finds the first goal whose target unifies with `t`. It makes that the main goal, performs the unification, and replaces the target with the unified version of `t`.
-/
meta def «show» (q : parse texpr) : tactic unit :=
do gs ← get_goals,
show_aux q gs []
/--
The tactic `specialize h a₁ ... aₙ` works on local hypothesis `h`. The premises of this hypothesis, either universal quantifications or non-dependent implications, are instantiated by concrete terms coming either from arguments `a₁` ... `aₙ`. The tactic adds a new hypothesis with the same name `h := h a₁ ... aₙ` and tries to clear the previous one.
-/
meta def specialize (p : parse texpr) : tactic unit :=
do e ← i_to_expr p,
let h := expr.get_app_fn e,
if h.is_local_constant
then tactic.note h.local_pp_name none e >> try (tactic.clear h)
else tactic.fail "specialize requires a term of the form `h x_1 .. x_n` where `h` appears in the local context"
meta def congr := tactic.congr
meta def rel_congr := tactic.rel_congr
end interactive
end tactic
section add_interactive
open tactic
/- See add_interactive -/
private meta def add_interactive_aux (new_namespace : name) : list name → command
| [] := return ()
| (n::ns) := do
env ← get_env,
d_name ← resolve_constant n,
(declaration.defn _ ls ty val hints trusted) ← env.get d_name,
(name.mk_string h _) ← return d_name,
let new_name := `tactic.interactive <.> h,
add_decl (declaration.defn new_name ls ty (expr.const d_name (ls.map level.param)) hints trusted),
add_interactive_aux ns
/--
Copy a list of meta definitions in the current namespace to tactic.interactive.
This command is useful when we want to update tactic.interactive without closing the current namespace.
-/
meta def add_interactive (ns : list name) (p : name := `tactic.interactive) : command :=
add_interactive_aux p ns
meta def has_dup : tactic bool :=
do ctx ← local_context,
let p : name_set × bool :=
ctx.foldl (λ ⟨s, r⟩ h,
if r then (s, r)
else if s.contains h.local_pp_name then (s, tt)
else (s.insert h.local_pp_name, ff))
(mk_name_set, ff),
return p.2
/--
Renames hypotheses with the same name.
-/
meta def dedup : tactic unit :=
mwhen has_dup $ do
ctx ← local_context,
n ← revert_lst ctx,
intron n
end add_interactive
namespace tactic
/- Helper tactic for `mk_inj_eq -/
protected meta def apply_inj_lemma : tactic unit :=
do h ← intro `h,
some (lhs, rhs) ← expr.is_eq <$> infer_type h,
(expr.const C _) ← return lhs.get_app_fn,
applyc (name.mk_string "inj" C),
assumption
/- Auxiliary tactic for proving `I.C.inj_eq` lemmas.
These lemmas are automatically generated by the equation compiler.
Example:
```
list.cons.inj_eq : forall h1 h2 t1 t2, (h1::t1 = h2::t2) = (h1 = h2 ∧ t1 = t2) :=
by mk_inj_eq
```
-/
meta def mk_inj_eq : tactic unit :=
`[
intros,
apply propext,
apply iff.intro,
{ tactic.apply_inj_lemma },
{ intro _, try { cases_matching* _ ∧ _ }, refl <|> { congr; { assumption <|> subst_vars } } }
]
end tactic
/- Define inj_eq lemmas for inductive datatypes that were declared before `mk_inj_eq` -/
universes u v
lemma sum.inl.inj_eq {α : Type u} (β : Type v) (a₁ a₂ : α) : (@sum.inl α β a₁ = sum.inl a₂) = (a₁ = a₂) :=
by tactic.mk_inj_eq
lemma sum.inr.inj_eq (α : Type u) {β : Type v} (b₁ b₂ : β) : (@sum.inr α β b₁ = sum.inr b₂) = (b₁ = b₂) :=
by tactic.mk_inj_eq
lemma psum.inl.inj_eq {α : Sort u} (β : Sort v) (a₁ a₂ : α) : (@psum.inl α β a₁ = psum.inl a₂) = (a₁ = a₂) :=
by tactic.mk_inj_eq
lemma psum.inr.inj_eq (α : Sort u) {β : Sort v} (b₁ b₂ : β) : (@psum.inr α β b₁ = psum.inr b₂) = (b₁ = b₂) :=
by tactic.mk_inj_eq
lemma sigma.mk.inj_eq {α : Type u} {β : α → Type v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : (sigma.mk a₁ b₁ = sigma.mk a₂ b₂) = (a₁ = a₂ ∧ b₁ == b₂) :=
by tactic.mk_inj_eq
lemma psigma.mk.inj_eq {α : Sort u} {β : α → Sort v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : (psigma.mk a₁ b₁ = psigma.mk a₂ b₂) = (a₁ = a₂ ∧ b₁ == b₂) :=
by tactic.mk_inj_eq
lemma subtype.mk.inj_eq {α : Sort u} {p : α → Prop} (a₁ : α) (h₁ : p a₁) (a₂ : α) (h₂ : p a₂) : (subtype.mk a₁ h₁ = subtype.mk a₂ h₂) = (a₁ = a₂) :=
by tactic.mk_inj_eq
lemma option.some.inj_eq {α : Type u} (a₁ a₂ : α) : (some a₁ = some a₂) = (a₁ = a₂) :=
by tactic.mk_inj_eq
lemma list.cons.inj_eq {α : Type u} (h₁ : α) (t₁ : list α) (h₂ : α) (t₂ : list α) : (list.cons h₁ t₁ = list.cons h₂ t₂) = (h₁ = h₂ ∧ t₁ = t₂) :=
by tactic.mk_inj_eq
lemma nat.succ.inj_eq (n₁ n₂ : nat) : (nat.succ n₁ = nat.succ n₂) = (n₁ = n₂) :=
by tactic.mk_inj_eq
|
91fb43bafc1aebedb48c7c1b6ecb4e970d13c98d
|
dc06cc9775d64d571bf4778459ec6fde1f344116
|
/src/data/fintype.lean
|
708c68b7763dd48be7b3fcdcba7bec3b1523ba4a
|
[
"Apache-2.0"
] |
permissive
|
mgubi/mathlib
|
8c1ea39035776ad52cf189a7af8cc0eee7dea373
|
7c09ed5eec8434176fbc493e0115555ccc4c8f99
|
refs/heads/master
| 1,642,222,572,514
| 1,563,782,424,000
| 1,563,782,424,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 32,035
|
lean
|
/-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Finite types.
-/
import data.finset algebra.big_operators data.array.lemmas logic.unique
universes u v
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `fintype α` means that `α` is finite, i.e. there are only
finitely many distinct elements of type `α`. The evidence of this
is a finset `elems` (a list up to permutation without duplicates),
together with a proof that everything of type `α` is in the list. -/
class fintype (α : Type*) :=
(elems : finset α)
(complete : ∀ x : α, x ∈ elems)
namespace finset
variable [fintype α]
/-- `univ` is the universal finite set of type `finset α` implied from
the assumption `fintype α`. -/
def univ : finset α := fintype.elems α
@[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) :=
fintype.complete x
@[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ
@[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) :=
by ext; simp
theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a
theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s :=
by simp [ext]
end finset
open finset function
namespace fintype
instance decidable_pi_fintype {α} {β : α → Type*} [fintype α] [∀a, decidable_eq (β a)] :
decidable_eq (Πa, β a) :=
assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a)
(by simp [function.funext_iff, fintype.complete])
instance decidable_forall_fintype [fintype α] {p : α → Prop} [decidable_pred p] :
decidable (∀ a, p a) :=
decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp)
instance decidable_exists_fintype [fintype α] {p : α → Prop} [decidable_pred p] :
decidable (∃ a, p a) :=
decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp)
instance decidable_eq_equiv_fintype [fintype α] [decidable_eq β] :
decidable_eq (α ≃ β) :=
λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext _ _ (congr_fun h), congr_arg _⟩
instance decidable_injective_fintype [fintype α] [decidable_eq α] [decidable_eq β] :
decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance
instance decidable_surjective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] :
decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance
instance decidable_bijective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] :
decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance
instance decidable_left_inverse_fintype [fintype α] [decidable_eq α] (f : α → β) (g : β → α) :
decidable (function.right_inverse f g) :=
show decidable (∀ x, g (f x) = x), by apply_instance
instance decidable_right_inverse_fintype [fintype β] [decidable_eq β] (f : α → β) (g : β → α) :
decidable (function.left_inverse f g) :=
show decidable (∀ x, f (g x) = x), by apply_instance
/-- Construct a proof of `fintype α` from a universal multiset -/
def of_multiset [decidable_eq α] (s : multiset α)
(H : ∀ x : α, x ∈ s) : fintype α :=
⟨s.to_finset, by simpa using H⟩
/-- Construct a proof of `fintype α` from a universal list -/
def of_list [decidable_eq α] (l : list α)
(H : ∀ x : α, x ∈ l) : fintype α :=
⟨l.to_finset, by simpa using H⟩
theorem exists_univ_list (α) [fintype α] :
∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l :=
let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in
by have := and.intro univ.2 mem_univ_val;
exact ⟨_, by rwa ← e at this⟩
/-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/
def card (α) [fintype α] : ℕ := (@univ α _).card
/-- There is (computably) a bijection between `α` and `fin n` where
`n = card α`. Since it is not unique, and depends on which permutation
of the universe list is used, the bijection is wrapped in `trunc` to
preserve computability. -/
def equiv_fin (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) :=
by unfold card finset.card; exact
quot.rec_on_subsingleton (@univ α _).1
(λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk
⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩,
λ i, l.nth_le i.1 i.2,
λ a, by simp,
λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _
(list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩)
mem_univ_val univ.2
theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) :=
by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩
instance (α : Type*) : subsingleton (fintype α) :=
⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext, h₁, h₂]⟩
protected def subtype {p : α → Prop} (s : finset α)
(H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} :=
⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1),
multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩,
λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩
theorem subtype_card {p : α → Prop} (s : finset α)
(H : ∀ x : α, x ∈ s ↔ p x) :
@card {x // p x} (fintype.subtype s H) = s.card :=
multiset.card_pmap _ _ _
theorem card_of_subtype {p : α → Prop} (s : finset α)
(H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] :
card {x // p x} = s.card :=
by rw ← subtype_card s H; congr
/-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/
def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β :=
⟨univ.map ⟨f, H.1⟩,
λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩
/-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/
def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β :=
⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩
noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α :=
by letI := classical.dec; exact
if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα;
exact of_surjective (inv_fun f) (inv_fun_surjective H)
else ⟨∅, λ x, (hα ⟨x⟩).elim⟩
/-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/
def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective
theorem of_equiv_card [fintype α] (f : α ≃ β) :
@card β (of_equiv α f) = card α :=
multiset.card_map _ _
theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β :=
by rw ← of_equiv_card f; congr
theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) :=
⟨λ e, match F, G, e with ⟨⟨s, nd⟩, h⟩, ⟨⟨s', nd'⟩, h'⟩, e' := begin
change multiset.card s = multiset.card s' at e',
revert nd nd' h h' e',
refine quotient.induction_on₂ s s' (λ l₁ l₂
(nd₁ : l₁.nodup) (nd₂ : l₂.nodup)
(h₁ : ∀ x, x ∈ l₁) (h₂ : ∀ x, x ∈ l₂)
(e' : l₁.length = l₂.length), _),
haveI := classical.dec_eq α,
refine ⟨equiv.of_bijective ⟨_, _⟩⟩,
{ refine λ a, l₂.nth_le (l₁.index_of a) _,
rw ← e', exact list.index_of_lt_length.2 (h₁ a) },
{ intros a b h, simpa [h₁] using congr_arg l₁.nth
(list.nodup_iff_nth_le_inj.1 nd₂ _ _ _ _ h) },
{ have := classical.dec_eq β,
refine λ b, ⟨l₁.nth_le (l₂.index_of b) _, _⟩,
{ rw e', exact list.index_of_lt_length.2 (h₂ b) },
{ simp [nd₁] } }
end end, λ ⟨f⟩, card_congr f⟩
def of_subsingleton (a : α) [subsingleton α] : fintype α :=
⟨finset.singleton a, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩
@[simp] theorem fintype.univ_of_subsingleton (a : α) [subsingleton α] :
@univ _ (of_subsingleton a) = finset.singleton a := rfl
@[simp] theorem fintype.card_of_subsingleton (a : α) [subsingleton α] :
@fintype.card _ (of_subsingleton a) = 1 := rfl
end fintype
lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α :=
rfl
lemma finset.card_univ_diff [fintype α] [decidable_eq α] (s : finset α) :
(finset.univ \ s).card = fintype.card α - s.card :=
finset.card_sdiff (subset_univ s)
instance (n : ℕ) : fintype (fin n) :=
⟨⟨list.pmap fin.mk (list.range n) (λ a, list.mem_range.1),
list.nodup_pmap (λ a _ b _, congr_arg fin.val) (list.nodup_range _)⟩,
λ ⟨m, h⟩, list.mem_pmap.2 ⟨m, list.mem_range.2 h, rfl⟩⟩
@[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n :=
by rw [fin.fintype]; simp [fintype.card, card, univ]
@[instance, priority 0] def unique.fintype {α : Type*} [unique α] : fintype α :=
⟨finset.singleton (default α), λ x, by rw [unique.eq_default x]; simp⟩
instance : fintype empty := ⟨∅, empty.rec _⟩
@[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl
@[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl
instance : fintype pempty := ⟨∅, pempty.rec _⟩
@[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl
@[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl
instance : fintype unit := fintype.of_subsingleton ()
@[simp] theorem fintype.univ_unit : @univ unit _ = {()} := rfl
@[simp] theorem fintype.card_unit : fintype.card unit = 1 := rfl
instance : fintype punit := fintype.of_subsingleton punit.star
@[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl
@[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl
instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩
@[simp] theorem fintype.univ_bool : @univ bool _ = {ff, tt} := rfl
instance units_int.fintype : fintype (units ℤ) :=
⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩
instance additive.fintype : Π [fintype α], fintype (additive α) := id
instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id
@[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl
@[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl
def finset.insert_none (s : finset α) : finset (option α) :=
⟨none :: s.1.map some, multiset.nodup_cons.2
⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩
@[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α},
o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s
| none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h)
| (some a) := multiset.mem_cons.trans $ by simp; refl
theorem finset.some_mem_insert_none {s : finset α} {a : α} :
some a ∈ s.insert_none ↔ a ∈ s := by simp
instance {α : Type*} [fintype α] : fintype (option α) :=
⟨univ.insert_none, λ a, by simp⟩
@[simp] theorem fintype.card_option {α : Type*} [fintype α] :
fintype.card (option α) = fintype.card α + 1 :=
(multiset.card_cons _ _).trans (by rw multiset.card_map; refl)
instance {α : Type*} (β : α → Type*)
[fintype α] [∀ a, fintype (β a)] : fintype (sigma β) :=
⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩
@[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*)
[fintype α] [∀ a, fintype (β a)] :
fintype.card (sigma β) = univ.sum (λ a, fintype.card (β a)) :=
card_sigma _ _
instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) :=
⟨univ.product univ, λ ⟨a, b⟩, by simp⟩
@[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] :
fintype.card (α × β) = fintype.card α * fintype.card β :=
card_product _ _
def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α :=
⟨(fintype.elems (α × β)).image prod.fst,
assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩
def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β :=
⟨(fintype.elems (α × β)).image prod.snd,
assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩
instance (α : Type*) [fintype α] : fintype (ulift α) :=
fintype.of_equiv _ equiv.ulift.symm
@[simp] theorem fintype.card_ulift (α : Type*) [fintype α] :
fintype.card (ulift α) = fintype.card α :=
fintype.of_equiv_card _
instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) :=
@fintype.of_equiv _ _ (@sigma.fintype _
(λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _
(λ b, by cases b; apply ulift.fintype))
((equiv.sum_equiv_sigma_bool _ _).symm.trans
(equiv.sum_congr equiv.ulift equiv.ulift))
@[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] :
fintype.card (α ⊕ β) = fintype.card α + fintype.card β :=
by rw [sum.fintype, fintype.of_equiv_card]; simp
lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β)
(hf : function.injective f) : fintype.card α ≤ fintype.card β :=
by haveI := classical.prop_decidable; exact
finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h)
lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) :=
by rw [← fintype.card_unit, fintype.card_eq]; exact
⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩,
λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm,
λ _, subsingleton.elim _ _⟩⟩⟩
lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) :=
⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim,
λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩,
by simp [fintype.card_congr e]⟩
lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α :=
⟨λ h, classical.by_contradiction (λ h₁,
have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩),
lt_irrefl 0 $ by rwa this at h),
λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩
lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) :=
let n := fintype.card α in
have hn : n = fintype.card α := rfl,
match n, hn with
| 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩
| 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in
by rw [hx a, hx b],
λ _, ha ▸ le_refl _⟩
| (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial,
(λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ())
(λ _ _ _, h _ _))⟩
end
lemma fintype.exists_ne_of_card_gt_one [fintype α] (h : fintype.card α > 1) (a : α) :
∃ b : α, b ≠ a :=
let ⟨b, hb⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt h)) in
let ⟨c, hc⟩ := classical.not_forall.1 hb in
by haveI := classical.dec_eq α; exact
if hba : b = a then ⟨c, by cc⟩ else ⟨b, hba⟩
lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f :=
by haveI := classical.prop_decidable; exact
have ∀ {f : α → α}, injective f → surjective f,
from λ f hinj x,
have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _)
((card_image_of_injective univ hinj).symm ▸ le_refl _),
have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _,
exists_of_bex (mem_image.1 h₂),
⟨this,
λ hsurj, injective_of_has_left_inverse
⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse
(this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩
lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f :=
by simp [bijective, fintype.injective_iff_surjective]
lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f :=
by simp [bijective, fintype.injective_iff_surjective]
lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) :
injective f ↔ surjective f :=
have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective,
⟨λ hinj, by simpa [function.comp] using
surjective_comp e.surjective (this.1 (injective_comp e.symm.injective hinj)),
λ hsurj, by simpa [function.comp] using
injective_comp e.injective (this.2 (surjective_comp e.symm.surjective hsurj))⟩
instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} :=
fintype.of_list l.attach l.mem_attach
instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} :=
fintype.of_multiset s.attach s.mem_attach
instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} :=
⟨s.attach, s.mem_attach⟩
instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) :=
finset.subtype.fintype s
@[simp] lemma fintype.card_coe (s : finset α) :
fintype.card (↑s : set α) = s.card := card_attach
instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) :=
⟨if h : p then finset.singleton ⟨h⟩ else ∅, λ ⟨h⟩, by simp [h]⟩
instance Prop.fintype : fintype Prop :=
⟨⟨true::false::0, by simp [true_ne_false]⟩,
classical.cases (by simp) (by simp)⟩
def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s :=
fintype.subtype (univ.filter (∈ s)) (by simp)
instance pi.fintype {α : Type*} {β : α → Type*}
[fintype α] [decidable_eq α] [∀a, fintype (β a)] : fintype (Πa, β a) :=
@fintype.of_equiv _ _
⟨univ.pi $ λa:α, @univ (β a) _,
λ f, finset.mem_pi.2 $ λ a ha, mem_univ _⟩
⟨λ f a, f a (mem_univ _), λ f a _, f a, λ f, rfl, λ f, rfl⟩
@[simp] lemma fintype.card_pi {β : α → Type*} [fintype α] [decidable_eq α]
[f : Π a, fintype (β a)] : fintype.card (Π a, β a) = univ.prod (λ a, fintype.card (β a)) :=
by letI f' : fintype (Πa∈univ, β a) :=
⟨(univ.pi $ λa, univ), assume f, finset.mem_pi.2 $ assume a ha, mem_univ _⟩;
exact calc fintype.card (Π a, β a) = fintype.card (Π a ∈ univ, β a) : fintype.card_congr
⟨λ f a ha, f a, λ f a, f a (mem_univ a), λ _, rfl, λ _, rfl⟩
... = univ.prod (λ a, fintype.card (β a)) : finset.card_pi _ _
@[simp] lemma fintype.card_fun [fintype α] [decidable_eq α] [fintype β] :
fintype.card (α → β) = fintype.card β ^ fintype.card α :=
by rw [fintype.card_pi, finset.prod_const, nat.pow_eq_pow]; refl
instance d_array.fintype {n : ℕ} {α : fin n → Type*}
[∀n, fintype (α n)] : fintype (d_array n α) :=
fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm
instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) :=
d_array.fintype
instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) :=
fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm
@[simp] lemma card_vector [fintype α] (n : ℕ) :
fintype.card (vector α n) = fintype.card α ^ n :=
by rw fintype.of_equiv_card; simp
instance quotient.fintype [fintype α] (s : setoid α)
[decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) :=
fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩))
instance finset.fintype [fintype α] : fintype (finset α) :=
⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩
instance subtype.fintype [fintype α] (p : α → Prop) [decidable_pred p] : fintype {x // p x} :=
set_fintype _
instance set.fintype [fintype α] [decidable_eq α] : fintype (set α) :=
pi.fintype
instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*)
[Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) :=
if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩
else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩
def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)] :
∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance)
| [] f := ⟦λ i, false.elim⟧
| (i::l) f := begin
refine quotient.lift_on₂ (f i (list.mem_cons_self _ _))
(quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h)))
_ _,
exact λ a l, ⟦λ j h,
if e : j = i then by rw e; exact a else
l _ (h.resolve_left e)⟧,
refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _),
by_cases e : j = i; simp [e],
{ subst j, exact h₁ },
{ exact h₂ _ _ }
end
theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)] :
∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧
| [] f := quotient.sound (λ i h, h.elim)
| (i::l) f := begin
simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l],
refine quotient.sound (λ j h, _),
by_cases e : j = i; simp [e],
subst j, refl
end
def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)]
(f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) :=
quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι,
@quotient (Π i ∈ l, α i) (by apply_instance))
finset.univ.1
(λ l, quotient.fin_choice_aux l (λ i _, f i))
(λ a b h, begin
have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)),
simp [quotient.out_eq] at this,
simp [this],
let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧,
refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)),
congr' 1, exact quotient.sound h,
end))
(λ f, ⟦λ i, f i (finset.mem_univ _)⟧)
(λ a b h, quotient.sound $ λ i, h _ _)
theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι]
{α : ι → Type*} [∀ i, setoid (α i)]
(f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ :=
begin
let q, swap, change quotient.lift_on q _ _ = _,
have : q = ⟦λ i h, f i⟧,
{ dsimp [q],
exact quotient.induction_on
(@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) },
simp [this], exact setoid.refl _
end
@[simp, to_additive finset.sum_attach_univ]
lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) :
univ.attach.prod (λ x, f x) = univ.prod (λ x, f ⟨x, (mem_univ _)⟩) :=
prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩)
section equiv
open list equiv equiv.perm
variables [decidable_eq α] [decidable_eq β]
def perms_of_list : list α → list (perm α)
| [] := [1]
| (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f))
lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact
| [] := rfl
| (a :: l) := by rw [length_cons, nat.fact_succ];
simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul]
lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l
| [] f h := list.mem_singleton.2 $ equiv.ext _ _$ λ x, by simp [imp_false, *] at *
| (a::l) f h :=
if hfa : f a = a
then
mem_append_left _ $ mem_perms_of_list_of_mem
(λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx))
else
have hfa' : f (f a) ≠ f a, from mt (λ h, f.injective h) hfa,
have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l,
from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx,
have hfxa : f x ≠ f a, from mt (λ h, f.injective h) hxa,
list.mem_of_ne_of_mem hxa
(h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)),
suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f,
by simpa [perms_of_list],
(@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2
(λ hfl, ⟨f a,
if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa))
else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc,
⟨swap a (f a) * f, mem_perms_of_list_of_mem this,
by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul]⟩⟩)
lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l
| [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp
| (a::l) f h :=
(mem_append.1 h).elim
(λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx))
(λ h x hx,
let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in
let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in
if hxa : x = a then by simp [hxa]
else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy
else mem_cons_of_mem _ $
mem_of_mem_perms_of_list hg₁ $
by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def];
split_ifs; cc)
lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l :=
⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩
lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup
| [] hl := by simp [perms_of_list]
| (a::l) hl :=
have hl' : l.nodup, from nodup_of_nodup_cons hl,
have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl',
have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a,
from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1),
by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact
⟨hln', ⟨λ _ _, nodup_map (λ _ _, (mul_left_inj _).1) hln',
λ i j hj hij x hx₁ hx₂,
let ⟨f, hf⟩ := list.mem_map.1 hx₁ in
let ⟨g, hg⟩ := list.mem_map.1 hx₂ in
have hix : x a = nth_le l i (lt_trans hij hj),
by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left],
have hiy : x a = nth_le l j hj,
by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left],
absurd (hf.2.trans (hg.2.symm)) $
λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $
by rw [← hix, hiy]⟩,
λ f hf₁ hf₂,
let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in
let ⟨g, hg⟩ := list.mem_map.1 hx' in
have hgxa : g⁻¹ x = a, from f.injective $
by rw [hmeml hf₁, ← hg.2]; simp,
have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx),
(list.nodup_cons.1 hl).1 $
hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩
def perms_of_finset (s : finset α) : finset (perm α) :=
quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩)
(λ a b hab, hfunext (congr_arg _ (quotient.sound hab))
(λ ha hb _, heq_of_eq $ finset.ext.2 $
by simp [mem_perms_of_list_iff,mem_of_perm hab]))
s.2
lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α},
f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s :=
by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff
lemma card_perms_of_finset : ∀ (s : finset α),
(perms_of_finset s).card = s.card.fact :=
by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l
def fintype_perm [fintype α] : fintype (perm α) :=
⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩
instance [fintype α] [fintype β] : fintype (α ≃ β) :=
if h : fintype.card β = fintype.card α
then trunc.rec_on_subsingleton (fintype.equiv_fin α)
(λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β)
(λ eβ, @fintype.of_equiv _ (perm α) fintype_perm
(equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β))))
else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩
lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact :=
subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸
card_perms_of_finset _
lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) :
fintype.card (α ≃ β) = (fintype.card α).fact :=
fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm
end equiv
namespace fintype
section choose
open fintype
open equiv
variables [fintype α] [decidable_eq α] (p : α → Prop) [decidable_pred p]
def choose_x (hp : ∃! a : α, p a) : {a // p a} :=
⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩
def choose (hp : ∃! a, p a) : α := choose_x p hp
lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) :=
(choose_x p hp).property
end choose
section bijection_inverse
open function
variables [fintype α] [decidable_eq α]
variables [fintype β] [decidable_eq β]
variables {f : α → β}
/-- `
`bij_inv f` is the unique inverse to a bijection `f`. This acts
as a computable alternative to `function.inv_fun`. -/
def bij_inv (f_bij : bijective f) (b : β) : α :=
fintype.choose (λ a, f a = b)
begin
rcases f_bij.right b with ⟨a', fa_eq_b⟩,
rw ← fa_eq_b,
exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩
end
lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f :=
λ a, f_bij.left (choose_spec (λ a', f a' = f a) _)
lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f :=
λ b, choose_spec (λ a', f a' = b) _
lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) :=
⟨injective_of_left_inverse (right_inverse_bij_inv _),
surjective_of_has_right_inverse ⟨f, left_inverse_bij_inv _⟩⟩
end bijection_inverse
lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop)
[is_trans α r] [is_irrefl α r] : well_founded r :=
by classical; exact
have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card,
from λ x y hxy, finset.card_lt_card $
by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le,
finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy];
exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩,
subrelation.wf this (measure_wf _)
lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) :=
well_founded_of_trans_of_irrefl _
@[instance, priority 0] lemma linear_order.is_well_order [fintype α] [linear_order α] :
is_well_order α (<) :=
{ wf := preorder.well_founded }
end fintype
class infinite (α : Type*) : Prop :=
(not_fintype : fintype α → false)
@[simp] lemma not_nonempty_fintype {α : Type*} : ¬nonempty (fintype α) ↔ infinite α :=
⟨λf, ⟨λ x, f ⟨x⟩⟩, λ⟨f⟩ ⟨x⟩, f x⟩
namespace infinite
lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s :=
classical.not_forall.1 $ λ h, not_fintype ⟨s, h⟩
instance nonempty (α : Type*) [infinite α] : nonempty α :=
nonempty_of_exists (exists_not_mem_finset (∅ : finset α))
lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α :=
⟨λ I, by exactI not_fintype (fintype.of_injective f hf)⟩
lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α :=
⟨λ I, by classical; exactI not_fintype (fintype.of_surjective f hf)⟩
end infinite
instance nat.infinite : infinite ℕ :=
⟨λ ⟨s, hs⟩, not_le_of_gt (nat.lt_succ_self (s.sum id)) $
@finset.single_le_sum _ _ _ id _ _ (λ _ _, nat.zero_le _) _ (hs _)⟩
instance int.infinite : infinite ℤ :=
infinite.of_injective int.of_nat (λ _ _, int.of_nat_inj)
|
c82f9a9a75467dde75176ee7658cd05db2bc5234
|
d9d511f37a523cd7659d6f573f990e2a0af93c6f
|
/src/data/equiv/mul_add.lean
|
2dd719e82dd101596fde77cac2880ce2bd19055a
|
[
"Apache-2.0"
] |
permissive
|
hikari0108/mathlib
|
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
|
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
|
refs/heads/master
| 1,690,483,608,260
| 1,631,541,580,000
| 1,631,541,580,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 24,692
|
lean
|
/-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov
-/
import algebra.group.type_tags
import algebra.group_with_zero
/-!
# Multiplicative and additive equivs
In this file we define two extensions of `equiv` called `add_equiv` and `mul_equiv`, which are
datatypes representing isomorphisms of `add_monoid`s/`add_group`s and `monoid`s/`group`s.
## Notations
* ``infix ` ≃* `:25 := mul_equiv``
* ``infix ` ≃+ `:25 := add_equiv``
The extended equivs all have coercions to functions, and the coercions are the canonical
notation when treating the isomorphisms as maps.
## Implementation notes
The fields for `mul_equiv`, `add_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as
these are deprecated.
## Tags
equiv, mul_equiv, add_equiv
-/
variables {A : Type*} {B : Type*} {M : Type*} {N : Type*}
{P : Type*} {Q : Type*} {G : Type*} {H : Type*}
/-- Makes a multiplicative inverse from a bijection which preserves multiplication. -/
@[to_additive "Makes an additive inverse from a bijection which preserves addition."]
def mul_hom.inverse [has_mul M] [has_mul N] (f : mul_hom M N) (g : N → M)
(h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : mul_hom N M :=
{ to_fun := g,
map_mul' := λ x y,
calc g (x * y) = g (f (g x) * f (g y)) : by rw [h₂ x, h₂ y]
... = g (f (g x * g y)) : by rw f.map_mul
... = g x * g y : h₁ _, }
/-- The inverse of a bijective `monoid_hom` is a `monoid_hom`. -/
@[to_additive "The inverse of a bijective `add_monoid_hom` is an `add_monoid_hom`.", simps]
def monoid_hom.inverse {A B : Type*} [monoid A] [monoid B] (f : A →* B) (g : B → A)
(h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) :
B →* A :=
{ to_fun := g,
map_one' := by rw [← f.map_one, h₁],
.. (f : mul_hom A B).inverse g h₁ h₂, }
set_option old_structure_cmd true
/-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/
@[ancestor equiv add_hom]
structure add_equiv (A B : Type*) [has_add A] [has_add B] extends A ≃ B, add_hom A B
/-- The `equiv` underlying an `add_equiv`. -/
add_decl_doc add_equiv.to_equiv
/-- The `add_hom` underlying a `add_equiv`. -/
add_decl_doc add_equiv.to_add_hom
/-- `mul_equiv α β` is the type of an equiv `α ≃ β` which preserves multiplication. -/
@[ancestor equiv mul_hom, to_additive]
structure mul_equiv (M N : Type*) [has_mul M] [has_mul N] extends M ≃ N, mul_hom M N
/-- The `equiv` underlying a `mul_equiv`. -/
add_decl_doc mul_equiv.to_equiv
/-- The `mul_hom` underlying a `mul_equiv`. -/
add_decl_doc mul_equiv.to_mul_hom
infix ` ≃* `:25 := mul_equiv
infix ` ≃+ `:25 := add_equiv
namespace mul_equiv
@[to_additive]
instance [has_mul M] [has_mul N] : has_coe_to_fun (M ≃* N) := ⟨_, mul_equiv.to_fun⟩
variables [has_mul M] [has_mul N] [has_mul P] [has_mul Q]
@[simp, to_additive]
lemma to_fun_eq_coe {f : M ≃* N} : f.to_fun = f := rfl
@[simp, to_additive]
lemma coe_to_equiv {f : M ≃* N} : ⇑f.to_equiv = f := rfl
@[simp, to_additive]
lemma coe_to_mul_hom {f : M ≃* N} : ⇑f.to_mul_hom = f := rfl
/-- A multiplicative isomorphism preserves multiplication (canonical form). -/
@[simp, to_additive]
lemma map_mul (f : M ≃* N) : ∀ x y, f (x * y) = f x * f y := f.map_mul'
/-- Makes a multiplicative isomorphism from a bijection which preserves multiplication. -/
@[to_additive "Makes an additive isomorphism from a bijection which preserves addition."]
def mk' (f : M ≃ N) (h : ∀ x y, f (x * y) = f x * f y) : M ≃* N :=
⟨f.1, f.2, f.3, f.4, h⟩
@[to_additive]
protected lemma bijective (e : M ≃* N) : function.bijective e := e.to_equiv.bijective
@[to_additive]
protected lemma injective (e : M ≃* N) : function.injective e := e.to_equiv.injective
@[to_additive]
protected lemma surjective (e : M ≃* N) : function.surjective e := e.to_equiv.surjective
/-- The identity map is a multiplicative isomorphism. -/
@[refl, to_additive "The identity map is an additive isomorphism."]
def refl (M : Type*) [has_mul M] : M ≃* M :=
{ map_mul' := λ _ _, rfl,
..equiv.refl _}
@[to_additive]
instance : inhabited (M ≃* M) := ⟨refl M⟩
/-- The inverse of an isomorphism is an isomorphism. -/
@[symm, to_additive "The inverse of an isomorphism is an isomorphism."]
def symm (h : M ≃* N) : N ≃* M :=
{ map_mul' := (h.to_mul_hom.inverse h.to_equiv.symm h.left_inv h.right_inv).map_mul,
.. h.to_equiv.symm}
@[simp, to_additive]
lemma inv_fun_eq_symm {f : M ≃* N} : f.inv_fun = f.symm := rfl
/-- See Note [custom simps projection] -/
-- we don't hyperlink the note in the additive version, since that breaks syntax highlighting
-- in the whole file.
@[to_additive "See Note custom simps projection"]
def simps.symm_apply (e : M ≃* N) : N → M := e.symm
initialize_simps_projections add_equiv (to_fun → apply, inv_fun → symm_apply)
initialize_simps_projections mul_equiv (to_fun → apply, inv_fun → symm_apply)
@[simp, to_additive]
theorem to_equiv_symm (f : M ≃* N) : f.symm.to_equiv = f.to_equiv.symm := rfl
@[simp, to_additive]
theorem coe_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃) = f := rfl
@[simp, to_additive]
lemma symm_symm : ∀ (f : M ≃* N), f.symm.symm = f
| ⟨f, g, h₁, h₂, h₃⟩ := rfl
@[to_additive]
lemma symm_bijective : function.bijective (symm : (M ≃* N) → (N ≃* M)) :=
equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩
@[simp, to_additive]
theorem symm_mk (f : M → N) (g h₁ h₂ h₃) :
(mul_equiv.mk f g h₁ h₂ h₃).symm =
{ to_fun := g, inv_fun := f, ..(mul_equiv.mk f g h₁ h₂ h₃).symm} := rfl
/-- Transitivity of multiplication-preserving isomorphisms -/
@[trans, to_additive "Transitivity of addition-preserving isomorphisms"]
def trans (h1 : M ≃* N) (h2 : N ≃* P) : (M ≃* P) :=
{ map_mul' := λ x y, show h2 (h1 (x * y)) = h2 (h1 x) * h2 (h1 y),
by rw [h1.map_mul, h2.map_mul],
..h1.to_equiv.trans h2.to_equiv }
/-- e.right_inv in canonical form -/
@[simp, to_additive]
lemma apply_symm_apply (e : M ≃* N) : ∀ y, e (e.symm y) = y :=
e.to_equiv.apply_symm_apply
/-- e.left_inv in canonical form -/
@[simp, to_additive]
lemma symm_apply_apply (e : M ≃* N) : ∀ x, e.symm (e x) = x :=
e.to_equiv.symm_apply_apply
@[simp, to_additive]
theorem symm_comp_self (e : M ≃* N) : e.symm ∘ e = id := funext e.symm_apply_apply
@[simp, to_additive]
theorem self_comp_symm (e : M ≃* N) : e ∘ e.symm = id := funext e.apply_symm_apply
@[simp, to_additive]
theorem coe_refl : ⇑(refl M) = id := rfl
@[to_additive]
theorem refl_apply (m : M) : refl M m = m := rfl
@[simp, to_additive]
theorem coe_trans (e₁ : M ≃* N) (e₂ : N ≃* P) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl
@[to_additive]
theorem trans_apply (e₁ : M ≃* N) (e₂ : N ≃* P) (m : M) : e₁.trans e₂ m = e₂ (e₁ m) := rfl
@[simp, to_additive] theorem symm_trans_apply (e₁ : M ≃* N) (e₂ : N ≃* P) (p : P) :
(e₁.trans e₂).symm p = e₁.symm (e₂.symm p) := rfl
@[simp, to_additive] theorem apply_eq_iff_eq (e : M ≃* N) {x y : M} : e x = e y ↔ x = y :=
e.injective.eq_iff
@[to_additive]
lemma apply_eq_iff_symm_apply (e : M ≃* N) {x : M} {y : N} : e x = y ↔ x = e.symm y :=
e.to_equiv.apply_eq_iff_eq_symm_apply
@[to_additive]
lemma symm_apply_eq (e : M ≃* N) {x y} : e.symm x = y ↔ x = e y :=
e.to_equiv.symm_apply_eq
@[to_additive]
lemma eq_symm_apply (e : M ≃* N) {x y} : y = e.symm x ↔ e y = x :=
e.to_equiv.eq_symm_apply
/-- Two multiplicative isomorphisms agree if they are defined by the
same underlying function. -/
@[ext, to_additive
"Two additive isomorphisms agree if they are defined by the same underlying function."]
lemma ext {f g : mul_equiv M N} (h : ∀ x, f x = g x) : f = g :=
begin
have h₁ : f.to_equiv = g.to_equiv := equiv.ext h,
cases f, cases g, congr,
{ exact (funext h) },
{ exact congr_arg equiv.inv_fun h₁ }
end
attribute [ext] add_equiv.ext
@[to_additive]
lemma ext_iff {f g : mul_equiv M N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, ext⟩
@[simp, to_additive] lemma mk_coe (e : M ≃* N) (e' h₁ h₂ h₃) :
(⟨e, e', h₁, h₂, h₃⟩ : M ≃* N) = e := ext $ λ _, rfl
@[simp, to_additive] lemma mk_coe' (e : M ≃* N) (f h₁ h₂ h₃) :
(mul_equiv.mk f ⇑e h₁ h₂ h₃ : N ≃* M) = e.symm :=
symm_bijective.injective $ ext $ λ x, rfl
@[to_additive]
protected lemma congr_arg {f : mul_equiv M N} : Π {x x' : M}, x = x' → f x = f x'
| _ _ rfl := rfl
@[to_additive]
protected lemma congr_fun {f g : mul_equiv M N} (h : f = g) (x : M) : f x = g x := h ▸ rfl
/-- The `mul_equiv` between two monoids with a unique element. -/
@[to_additive "The `add_equiv` between two add_monoids with a unique element."]
def mul_equiv_of_unique_of_unique {M N}
[unique M] [unique N] [has_mul M] [has_mul N] : M ≃* N :=
{ map_mul' := λ _ _, subsingleton.elim _ _,
..equiv_of_unique_of_unique }
/-- There is a unique monoid homomorphism between two monoids with a unique element. -/
@[to_additive] instance {M N} [unique M] [unique N] [has_mul M] [has_mul N] : unique (M ≃* N) :=
{ default := mul_equiv_of_unique_of_unique ,
uniq := λ _, ext $ λ x, subsingleton.elim _ _}
/-!
## Monoids
-/
/-- A multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism). -/
@[simp, to_additive]
lemma map_one {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) : h 1 = 1 :=
by rw [←mul_one (h 1), ←h.apply_symm_apply 1, ←h.map_mul, one_mul]
@[simp, to_additive]
lemma map_eq_one_iff {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) {x : M} :
h x = 1 ↔ x = 1 :=
h.map_one ▸ h.to_equiv.apply_eq_iff_eq
@[to_additive]
lemma map_ne_one_iff {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) {x : M} :
h x ≠ 1 ↔ x ≠ 1 :=
⟨mt h.map_eq_one_iff.2, mt h.map_eq_one_iff.1⟩
/-- A bijective `monoid` homomorphism is an isomorphism -/
@[to_additive "A bijective `add_monoid` homomorphism is an isomorphism"]
noncomputable def of_bijective {M N} [mul_one_class M] [mul_one_class N] (f : M →* N)
(hf : function.bijective f) : M ≃* N :=
{ map_mul' := f.map_mul',
..equiv.of_bijective f hf }
/--
Extract the forward direction of a multiplicative equivalence
as a multiplication-preserving function.
-/
@[to_additive "Extract the forward direction of an additive equivalence
as an addition-preserving function."]
def to_monoid_hom {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) : (M →* N) :=
{ map_one' := h.map_one, .. h }
@[simp, to_additive]
lemma coe_to_monoid_hom {M N} [mul_one_class M] [mul_one_class N] (e : M ≃* N) :
⇑e.to_monoid_hom = e :=
rfl
@[to_additive] lemma to_monoid_hom_injective {M N} [mul_one_class M] [mul_one_class N] :
function.injective (to_monoid_hom : (M ≃* N) → M →* N) :=
λ f g h, mul_equiv.ext (monoid_hom.ext_iff.1 h)
/--
A multiplicative analogue of `equiv.arrow_congr`,
where the equivalence between the targets is multiplicative.
-/
@[to_additive "An additive analogue of `equiv.arrow_congr`,
where the equivalence between the targets is additive.", simps apply]
def arrow_congr {M N P Q : Type*} [mul_one_class P] [mul_one_class Q]
(f : M ≃ N) (g : P ≃* Q) : (M → P) ≃* (N → Q) :=
{ to_fun := λ h n, g (h (f.symm n)),
inv_fun := λ k m, g.symm (k (f m)),
left_inv := λ h, by { ext, simp, },
right_inv := λ k, by { ext, simp, },
map_mul' := λ h k, by { ext, simp, }, }
/--
A multiplicative analogue of `equiv.arrow_congr`,
for multiplicative maps from a monoid to a commutative monoid.
-/
@[to_additive "An additive analogue of `equiv.arrow_congr`,
for additive maps from an additive monoid to a commutative additive monoid.", simps apply]
def monoid_hom_congr {M N P Q} [mul_one_class M] [mul_one_class N] [comm_monoid P] [comm_monoid Q]
(f : M ≃* N) (g : P ≃* Q) : (M →* P) ≃* (N →* Q) :=
{ to_fun := λ h,
g.to_monoid_hom.comp (h.comp f.symm.to_monoid_hom),
inv_fun := λ k,
g.symm.to_monoid_hom.comp (k.comp f.to_monoid_hom),
left_inv := λ h, by { ext, simp, },
right_inv := λ k, by { ext, simp, },
map_mul' := λ h k, by { ext, simp, }, }
/-- A family of multiplicative equivalences `Π j, (Ms j ≃* Ns j)` generates a
multiplicative equivalence between `Π j, Ms j` and `Π j, Ns j`.
This is the `mul_equiv` version of `equiv.Pi_congr_right`, and the dependent version of
`mul_equiv.arrow_congr`.
-/
@[to_additive add_equiv.Pi_congr_right "A family of additive equivalences `Π j, (Ms j ≃+ Ns j)`
generates an additive equivalence between `Π j, Ms j` and `Π j, Ns j`.
This is the `add_equiv` version of `equiv.Pi_congr_right`, and the dependent version of
`add_equiv.arrow_congr`.", simps apply]
def Pi_congr_right {η : Type*}
{Ms Ns : η → Type*} [Π j, mul_one_class (Ms j)] [Π j, mul_one_class (Ns j)]
(es : ∀ j, Ms j ≃* Ns j) : (Π j, Ms j) ≃* (Π j, Ns j) :=
{ to_fun := λ x j, es j (x j),
inv_fun := λ x j, (es j).symm (x j),
map_mul' := λ x y, funext $ λ j, (es j).map_mul (x j) (y j),
.. equiv.Pi_congr_right (λ j, (es j).to_equiv) }
@[simp]
lemma Pi_congr_right_refl {η : Type*} {Ms : η → Type*} [Π j, mul_one_class (Ms j)] :
Pi_congr_right (λ j, mul_equiv.refl (Ms j)) = mul_equiv.refl _ := rfl
@[simp]
lemma Pi_congr_right_symm {η : Type*}
{Ms Ns : η → Type*} [Π j, mul_one_class (Ms j)] [Π j, mul_one_class (Ns j)]
(es : ∀ j, Ms j ≃* Ns j) : (Pi_congr_right es).symm = (Pi_congr_right $ λ i, (es i).symm) := rfl
@[simp]
lemma Pi_congr_right_trans {η : Type*}
{Ms Ns Ps : η → Type*} [Π j, mul_one_class (Ms j)] [Π j, mul_one_class (Ns j)]
[Π j, mul_one_class (Ps j)]
(es : ∀ j, Ms j ≃* Ns j) (fs : ∀ j, Ns j ≃* Ps j) :
(Pi_congr_right es).trans (Pi_congr_right fs) = (Pi_congr_right $ λ i, (es i).trans (fs i)) := rfl
/-!
# Groups
-/
/-- A multiplicative equivalence of groups preserves inversion. -/
@[simp, to_additive]
lemma map_inv [group G] [group H] (h : G ≃* H) (x : G) : h x⁻¹ = (h x)⁻¹ :=
h.to_monoid_hom.map_inv x
end mul_equiv
-- We don't use `to_additive` to generate definition because it fails to tell Lean about
-- equational lemmas
/-- Given a pair of additive monoid homomorphisms `f`, `g` such that `g.comp f = id` and
`f.comp g = id`, returns an additive equivalence with `to_fun = f` and `inv_fun = g`. This
constructor is useful if the underlying type(s) have specialized `ext` lemmas for additive
monoid homomorphisms. -/
def add_monoid_hom.to_add_equiv [add_zero_class M] [add_zero_class N] (f : M →+ N) (g : N →+ M)
(h₁ : g.comp f = add_monoid_hom.id _) (h₂ : f.comp g = add_monoid_hom.id _) :
M ≃+ N :=
{ to_fun := f,
inv_fun := g,
left_inv := add_monoid_hom.congr_fun h₁,
right_inv := add_monoid_hom.congr_fun h₂,
map_add' := f.map_add }
/-- Given a pair of monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`,
returns an multiplicative equivalence with `to_fun = f` and `inv_fun = g`. This constructor is
useful if the underlying type(s) have specialized `ext` lemmas for monoid homomorphisms. -/
@[to_additive, simps {fully_applied := ff}]
def monoid_hom.to_mul_equiv [mul_one_class M] [mul_one_class N] (f : M →* N) (g : N →* M)
(h₁ : g.comp f = monoid_hom.id _) (h₂ : f.comp g = monoid_hom.id _) :
M ≃* N :=
{ to_fun := f,
inv_fun := g,
left_inv := monoid_hom.congr_fun h₁,
right_inv := monoid_hom.congr_fun h₂,
map_mul' := f.map_mul }
/-- An additive equivalence of additive groups preserves subtraction. -/
lemma add_equiv.map_sub [add_group A] [add_group B] (h : A ≃+ B) (x y : A) :
h (x - y) = h x - h y :=
h.to_add_monoid_hom.map_sub x y
/-- A group is isomorphic to its group of units. -/
@[to_additive to_add_units "An additive group is isomorphic to its group of additive units"]
def to_units [group G] : G ≃* units G :=
{ to_fun := λ x, ⟨x, x⁻¹, mul_inv_self _, inv_mul_self _⟩,
inv_fun := coe,
left_inv := λ x, rfl,
right_inv := λ u, units.ext rfl,
map_mul' := λ x y, units.ext rfl }
@[simp, to_additive coe_to_add_units] lemma coe_to_units [group G] (g : G) :
(to_units g : G) = g := rfl
protected lemma group.is_unit {G} [group G] (x : G) : is_unit x := (to_units x).is_unit
namespace units
@[simp, to_additive] lemma coe_inv [group G] (u : units G) :
↑u⁻¹ = (u⁻¹ : G) :=
to_units.symm.map_inv u
variables [monoid M] [monoid N] [monoid P]
/-- A multiplicative equivalence of monoids defines a multiplicative equivalence
of their groups of units. -/
def map_equiv (h : M ≃* N) : units M ≃* units N :=
{ inv_fun := map h.symm.to_monoid_hom,
left_inv := λ u, ext $ h.left_inv u,
right_inv := λ u, ext $ h.right_inv u,
.. map h.to_monoid_hom }
/-- Left multiplication by a unit of a monoid is a permutation of the underlying type. -/
@[to_additive "Left addition of an additive unit is a permutation of the underlying type.",
simps apply {fully_applied := ff}]
def mul_left (u : units M) : equiv.perm M :=
{ to_fun := λx, u * x,
inv_fun := λx, ↑u⁻¹ * x,
left_inv := u.inv_mul_cancel_left,
right_inv := u.mul_inv_cancel_left }
@[simp, to_additive]
lemma mul_left_symm (u : units M) : u.mul_left.symm = u⁻¹.mul_left :=
equiv.ext $ λ x, rfl
/-- Right multiplication by a unit of a monoid is a permutation of the underlying type. -/
@[to_additive "Right addition of an additive unit is a permutation of the underlying type.",
simps apply {fully_applied := ff}]
def mul_right (u : units M) : equiv.perm M :=
{ to_fun := λx, x * u,
inv_fun := λx, x * ↑u⁻¹,
left_inv := λ x, mul_inv_cancel_right x u,
right_inv := λ x, inv_mul_cancel_right x u }
@[simp, to_additive]
lemma mul_right_symm (u : units M) : u.mul_right.symm = u⁻¹.mul_right :=
equiv.ext $ λ x, rfl
end units
namespace equiv
section group
variables [group G]
/-- Left multiplication in a `group` is a permutation of the underlying type. -/
@[to_additive "Left addition in an `add_group` is a permutation of the underlying type."]
protected def mul_left (a : G) : perm G := (to_units a).mul_left
@[simp, to_additive]
lemma coe_mul_left (a : G) : ⇑(equiv.mul_left a) = (*) a := rfl
/-- extra simp lemma that `dsimp` can use. `simp` will never use this. -/
@[simp, nolint simp_nf, to_additive]
lemma mul_left_symm_apply (a : G) : ((equiv.mul_left a).symm : G → G) = (*) a⁻¹ := rfl
@[simp, to_additive]
lemma mul_left_symm (a : G) : (equiv.mul_left a).symm = equiv.mul_left a⁻¹ :=
ext $ λ x, rfl
/-- Right multiplication in a `group` is a permutation of the underlying type. -/
@[to_additive "Right addition in an `add_group` is a permutation of the underlying type."]
protected def mul_right (a : G) : perm G := (to_units a).mul_right
@[simp, to_additive]
lemma coe_mul_right (a : G) : ⇑(equiv.mul_right a) = λ x, x * a := rfl
@[simp, to_additive]
lemma mul_right_symm (a : G) : (equiv.mul_right a).symm = equiv.mul_right a⁻¹ :=
ext $ λ x, rfl
/-- extra simp lemma that `dsimp` can use. `simp` will never use this. -/
@[simp, nolint simp_nf, to_additive]
lemma mul_right_symm_apply (a : G) : ((equiv.mul_right a).symm : G → G) = λ x, x * a⁻¹ := rfl
attribute [nolint simp_nf] add_left_symm_apply add_right_symm_apply
variable (G)
/-- Inversion on a `group` is a permutation of the underlying type. -/
@[to_additive "Negation on an `add_group` is a permutation of the underlying type.",
simps apply {fully_applied := ff}]
protected def inv : perm G :=
{ to_fun := λa, a⁻¹,
inv_fun := λa, a⁻¹,
left_inv := assume a, inv_inv a,
right_inv := assume a, inv_inv a }
variable {G}
@[simp, to_additive]
lemma inv_symm : (equiv.inv G).symm = equiv.inv G := rfl
/-- A version of `equiv.mul_left a b⁻¹` that is defeq to `a / b`. -/
@[to_additive /-" A version of `equiv.add_left a (-b)` that is defeq to `a - b`. "-/, simps]
protected def div_left (a : G) : G ≃ G :=
{ to_fun := λ b, a / b,
inv_fun := λ b, b⁻¹ * a,
left_inv := λ b, by simp [div_eq_mul_inv],
right_inv := λ b, by simp [div_eq_mul_inv] }
@[to_additive]
lemma div_left_eq_inv_trans_mul_left (a : G) :
equiv.div_left a = (equiv.inv G).trans (equiv.mul_left a) :=
ext $ λ _, div_eq_mul_inv _ _
/-- A version of `equiv.mul_right a⁻¹ b` that is defeq to `b / a`. -/
@[to_additive /-" A version of `equiv.add_right (-a) b` that is defeq to `b - a`. "-/, simps]
protected def div_right (a : G) : G ≃ G :=
{ to_fun := λ b, b / a,
inv_fun := λ b, b * a,
left_inv := λ b, by simp [div_eq_mul_inv],
right_inv := λ b, by simp [div_eq_mul_inv] }
@[to_additive]
lemma div_right_eq_mul_right_inv (a : G) : equiv.div_right a = equiv.mul_right a⁻¹ :=
ext $ λ _, div_eq_mul_inv _ _
end group
section group_with_zero
variables [group_with_zero G]
/-- Left multiplication by a nonzero element in a `group_with_zero` is a permutation of the
underlying type. -/
@[simps {fully_applied := ff}]
protected def mul_left' (a : G) (ha : a ≠ 0) : perm G :=
{ to_fun := λ x, a * x,
inv_fun := λ x, a⁻¹ * x,
left_inv := λ x, by { dsimp, rw [← mul_assoc, inv_mul_cancel ha, one_mul] },
right_inv := λ x, by { dsimp, rw [← mul_assoc, mul_inv_cancel ha, one_mul] } }
/-- Right multiplication by a nonzero element in a `group_with_zero` is a permutation of the
underlying type. -/
@[simps {fully_applied := ff}]
protected def mul_right' (a : G) (ha : a ≠ 0) : perm G :=
{ to_fun := λ x, x * a,
inv_fun := λ x, x * a⁻¹,
left_inv := λ x, by { dsimp, rw [mul_assoc, mul_inv_cancel ha, mul_one] },
right_inv := λ x, by { dsimp, rw [mul_assoc, inv_mul_cancel ha, mul_one] } }
end group_with_zero
end equiv
/-- When the group is commutative, `equiv.inv` is a `mul_equiv`. There is a variant of this
`mul_equiv.inv' G : G ≃* Gᵒᵖ` for the non-commutative case. -/
@[to_additive "When the `add_group` is commutative, `equiv.neg` is an `add_equiv`."]
def mul_equiv.inv (G : Type*) [comm_group G] : G ≃* G :=
{ to_fun := has_inv.inv,
inv_fun := has_inv.inv,
map_mul' := mul_inv,
..equiv.inv G}
section type_tags
/-- Reinterpret `G ≃+ H` as `multiplicative G ≃* multiplicative H`. -/
def add_equiv.to_multiplicative [add_zero_class G] [add_zero_class H] :
(G ≃+ H) ≃ (multiplicative G ≃* multiplicative H) :=
{ to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative,
f.symm.to_add_monoid_hom.to_multiplicative, f.3, f.4, f.5⟩,
inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, by { ext, refl, }, }
/-- Reinterpret `G ≃* H` as `additive G ≃+ additive H`. -/
def mul_equiv.to_additive [mul_one_class G] [mul_one_class H] :
(G ≃* H) ≃ (additive G ≃+ additive H) :=
{ to_fun := λ f, ⟨f.to_monoid_hom.to_additive, f.symm.to_monoid_hom.to_additive, f.3, f.4, f.5⟩,
inv_fun := λ f, ⟨f.to_add_monoid_hom, f.symm.to_add_monoid_hom, f.3, f.4, f.5⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, by { ext, refl, }, }
/-- Reinterpret `additive G ≃+ H` as `G ≃* multiplicative H`. -/
def add_equiv.to_multiplicative' [mul_one_class G] [add_zero_class H] :
(additive G ≃+ H) ≃ (G ≃* multiplicative H) :=
{ to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative',
f.symm.to_add_monoid_hom.to_multiplicative'', f.3, f.4, f.5⟩,
inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, by { ext, refl, }, }
/-- Reinterpret `G ≃* multiplicative H` as `additive G ≃+ H` as. -/
def mul_equiv.to_additive' [mul_one_class G] [add_zero_class H] :
(G ≃* multiplicative H) ≃ (additive G ≃+ H) :=
add_equiv.to_multiplicative'.symm
/-- Reinterpret `G ≃+ additive H` as `multiplicative G ≃* H`. -/
def add_equiv.to_multiplicative'' [add_zero_class G] [mul_one_class H] :
(G ≃+ additive H) ≃ (multiplicative G ≃* H) :=
{ to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative'',
f.symm.to_add_monoid_hom.to_multiplicative', f.3, f.4, f.5⟩,
inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, by { ext, refl, }, }
/-- Reinterpret `multiplicative G ≃* H` as `G ≃+ additive H` as. -/
def mul_equiv.to_additive'' [add_zero_class G] [mul_one_class H] :
(multiplicative G ≃* H) ≃ (G ≃+ additive H) :=
add_equiv.to_multiplicative''.symm
end type_tags
|
d3edd538e60078f7450ce2f1675201fef55e90f0
|
9dc8cecdf3c4634764a18254e94d43da07142918
|
/src/topology/algebra/uniform_mul_action.lean
|
dc90954b31cd73a51483d5dce412d57c919a8ba4
|
[
"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
| 7,187
|
lean
|
/-
Copyright (c) 2022 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import algebra.hom.group_instances
import topology.algebra.uniform_group
import topology.uniform_space.completion
/-!
# Multiplicative action on the completion of a uniform space
In this file we define typeclasses `has_uniform_continuous_const_vadd` and
`has_uniform_continuous_const_smul` and prove that a multiplicative action on `X` with uniformly
continuous `(•) c` can be extended to a multiplicative action on `uniform_space.completion X`.
In later files once the additive group structure is set up, we provide
* `uniform_space.completion.distrib_mul_action`
* `uniform_space.completion.mul_action_with_zero`
* `uniform_space.completion.module`
TODO: Generalise the results here from the concrete `completion` to any `abstract_completion`.
-/
universes u v w x y z
noncomputable theory
variables (R : Type u) (M : Type v) (N : Type w) (X : Type x) (Y : Type y)
[uniform_space X] [uniform_space Y]
/-- An additive action such that for all `c`, the map `λ x, c +ᵥ x` is uniformly continuous. -/
class has_uniform_continuous_const_vadd [uniform_space X] [has_vadd M X] : Prop :=
(uniform_continuous_const_vadd : ∀ (c : M), uniform_continuous ((+ᵥ) c : X → X))
/-- A multiplicative action such that for all `c`, the map `λ x, c • x` is uniformly continuous. -/
@[to_additive]
class has_uniform_continuous_const_smul [uniform_space X] [has_smul M X] : Prop :=
(uniform_continuous_const_smul : ∀ (c : M), uniform_continuous ((•) c : X → X))
export has_uniform_continuous_const_vadd (uniform_continuous_const_vadd)
has_uniform_continuous_const_smul (uniform_continuous_const_smul)
instance add_monoid.has_uniform_continuous_const_smul_nat [add_group X] [uniform_add_group X] :
has_uniform_continuous_const_smul ℕ X :=
⟨uniform_continuous_const_nsmul⟩
instance add_group.has_uniform_continuous_const_smul_int [add_group X] [uniform_add_group X] :
has_uniform_continuous_const_smul ℤ X :=
⟨uniform_continuous_const_zsmul⟩
/-- A `distrib_mul_action` that is continuous on a uniform group is uniformly continuous.
This can't be an instance due to it forming a loop with
`has_uniform_continuous_const_smul.to_has_continuous_const_smul` -/
lemma has_uniform_continuous_const_smul_of_continuous_const_smul [monoid R] [add_comm_group M]
[distrib_mul_action R M] [uniform_space M] [uniform_add_group M] [has_continuous_const_smul R M] :
has_uniform_continuous_const_smul R M :=
⟨λ r, uniform_continuous_of_continuous_at_zero (distrib_mul_action.to_add_monoid_hom M r)
(continuous.continuous_at (continuous_const_smul r))⟩
/-- The action of `semiring.to_module` is uniformly continuous. -/
instance ring.has_uniform_continuous_const_smul [ring R] [uniform_space R]
[uniform_add_group R] [has_continuous_mul R] : has_uniform_continuous_const_smul R R :=
has_uniform_continuous_const_smul_of_continuous_const_smul _ _
/-- The action of `semiring.to_opposite_module` is uniformly continuous. -/
instance ring.has_uniform_continuous_const_op_smul [ring R] [uniform_space R]
[uniform_add_group R] [has_continuous_mul R] : has_uniform_continuous_const_smul Rᵐᵒᵖ R :=
has_uniform_continuous_const_smul_of_continuous_const_smul _ _
section has_smul
variable [has_smul M X]
@[priority 100, to_additive]
instance has_uniform_continuous_const_smul.to_has_continuous_const_smul
[has_uniform_continuous_const_smul M X] : has_continuous_const_smul M X :=
⟨λ c, (uniform_continuous_const_smul c).continuous⟩
variables {M X Y}
@[to_additive] lemma uniform_continuous.const_smul [has_uniform_continuous_const_smul M X]
{f : Y → X} (hf : uniform_continuous f) (c : M) :
uniform_continuous (c • f) :=
(uniform_continuous_const_smul c).comp hf
/-- If a scalar is central, then its right action is uniform continuous when its left action is. -/
@[priority 100]
instance has_uniform_continuous_const_smul.op [has_smul Mᵐᵒᵖ X] [is_central_scalar M X]
[has_uniform_continuous_const_smul M X] : has_uniform_continuous_const_smul Mᵐᵒᵖ X :=
⟨mul_opposite.rec $ λ c, begin
change uniform_continuous (λ m, mul_opposite.op c • m),
simp_rw op_smul_eq_smul,
exact uniform_continuous_const_smul c,
end⟩
@[to_additive] instance mul_opposite.has_uniform_continuous_const_smul
[has_uniform_continuous_const_smul M X] : has_uniform_continuous_const_smul M Xᵐᵒᵖ :=
⟨λ c, mul_opposite.uniform_continuous_op.comp $ mul_opposite.uniform_continuous_unop.const_smul c⟩
end has_smul
@[to_additive] instance uniform_group.to_has_uniform_continuous_const_smul
{G : Type u} [group G] [uniform_space G] [uniform_group G] :
has_uniform_continuous_const_smul G G :=
⟨λ c, uniform_continuous_const.mul uniform_continuous_id⟩
namespace uniform_space
namespace completion
section has_smul
variable [has_smul M X]
@[to_additive] instance : has_smul M (completion X) :=
⟨λ c, completion.map ((•) c)⟩
lemma smul_def (c : M) (x : completion X) : c • x = completion.map ((•) c) x := rfl
@[to_additive] instance : has_uniform_continuous_const_smul M (completion X) :=
⟨λ c, uniform_continuous_map⟩
instance [has_smul N X] [has_smul M N]
[has_uniform_continuous_const_smul M X] [has_uniform_continuous_const_smul N X]
[is_scalar_tower M N X] : is_scalar_tower M N (completion X) :=
⟨λ m n x, begin
have : _ = (_ : completion X → completion X) :=
map_comp (uniform_continuous_const_smul m) (uniform_continuous_const_smul n),
refine eq.trans _ (congr_fun this.symm x),
exact congr_arg (λ f, completion.map f x) (by exact funext (smul_assoc _ _)),
end⟩
instance [has_smul N X] [smul_comm_class M N X]
[has_uniform_continuous_const_smul M X] [has_uniform_continuous_const_smul N X] :
smul_comm_class M N (completion X) :=
⟨λ m n x, begin
have hmn : m • n • x =
(( completion.map (has_smul.smul m)) ∘ (completion.map (has_smul.smul n))) x := rfl,
have hnm : n • m • x =
(( completion.map (has_smul.smul n)) ∘ (completion.map (has_smul.smul m))) x := rfl,
rw [hmn, hnm, map_comp, map_comp],
exact congr_arg (λ f, completion.map f x) (by exact funext (smul_comm _ _)),
repeat{ exact uniform_continuous_const_smul _},
end⟩
instance [has_smul Mᵐᵒᵖ X] [is_central_scalar M X] : is_central_scalar M (completion X) :=
⟨λ c a, congr_arg (λ f, completion.map f a) $ by exact funext (op_smul_eq_smul c)⟩
variables {M X} [has_uniform_continuous_const_smul M X]
@[simp, norm_cast, to_additive]
lemma coe_smul (c : M) (x : X) : ↑(c • x) = (c • x : completion X) :=
(map_coe (uniform_continuous_const_smul c) x).symm
end has_smul
@[to_additive] instance [monoid M] [mul_action M X] [has_uniform_continuous_const_smul M X] :
mul_action M (completion X) :=
{ smul := (•),
one_smul := ext' (continuous_const_smul _) continuous_id $ λ a, by rw [← coe_smul, one_smul],
mul_smul := λ x y, ext' (continuous_const_smul _) ((continuous_const_smul _).const_smul _) $
λ a, by simp only [← coe_smul, mul_smul] }
end completion
end uniform_space
|
ca6e2504b80780ec13b84dc99001b3309f7093f3
|
437dc96105f48409c3981d46fb48e57c9ac3a3e4
|
/src/data/real/cardinality.lean
|
d7f6e8e97ace8f1fc5a948677115a87663064fb4
|
[
"Apache-2.0"
] |
permissive
|
dan-c-k/mathlib
|
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
|
96efc220f6225bc7a5ed8349900391a33a38cc56
|
refs/heads/master
| 1,658,082,847,093
| 1,589,013,201,000
| 1,589,013,201,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 4,888
|
lean
|
/-
Copyright (c) 2019 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
The cardinality of the reals.
-/
import set_theory.ordinal
import analysis.specific_limits
import data.rat.denumerable
open nat set
noncomputable theory
namespace cardinal
variables {c : ℝ} {f g : ℕ → bool} {n : ℕ}
def cantor_function_aux (c : ℝ) (f : ℕ → bool) (n : ℕ) : ℝ := cond (f n) (c ^ n) 0
@[simp] lemma cantor_function_aux_tt (h : f n = tt) : cantor_function_aux c f n = c ^ n :=
by simp [cantor_function_aux, h]
@[simp] lemma cantor_function_aux_ff (h : f n = ff) : cantor_function_aux c f n = 0 :=
by simp [cantor_function_aux, h]
lemma cantor_function_aux_nonneg (h : 0 ≤ c) : 0 ≤ cantor_function_aux c f n :=
by { cases h' : f n; simp [h'], apply pow_nonneg h }
lemma cantor_function_aux_eq (h : f n = g n) :
cantor_function_aux c f n = cantor_function_aux c g n :=
by simp [cantor_function_aux, h]
lemma cantor_function_aux_succ (f : ℕ → bool) :
(λ n, cantor_function_aux c f (n + 1)) = λ n, c * cantor_function_aux c (λ n, f (n + 1)) n :=
by { ext n, cases h : f (n + 1); simp [h, _root_.pow_succ] }
lemma summable_cantor_function (f : ℕ → bool) (h1 : 0 ≤ c) (h2 : c < 1) :
summable (cantor_function_aux c f) :=
begin
apply (summable_geometric h1 h2).summable_of_eq_zero_or_self,
intro n, cases h : f n; simp [h]
end
def cantor_function (c : ℝ) (f : ℕ → bool) : ℝ := ∑' n, cantor_function_aux c f n
lemma cantor_function_le (h1 : 0 ≤ c) (h2 : c < 1) (h3 : ∀ n, f n → g n) :
cantor_function c f ≤ cantor_function c g :=
begin
apply tsum_le_tsum _ (summable_cantor_function f h1 h2) (summable_cantor_function g h1 h2),
intro n, cases h : f n, simp [h, cantor_function_aux_nonneg h1],
replace h3 : g n = tt := h3 n h, simp [h, h3]
end
lemma cantor_function_succ (f : ℕ → bool) (h1 : 0 ≤ c) (h2 : c < 1) :
cantor_function c f = cond (f 0) 1 0 + c * cantor_function c (λ n, f (n+1)) :=
begin
rw [cantor_function, tsum_eq_zero_add (summable_cantor_function f h1 h2)],
rw [cantor_function_aux_succ, tsum_mul_left _ (summable_cantor_function _ h1 h2)], refl
end
lemma increasing_cantor_function (h1 : 0 < c) (h2 : c < 1 / 2) {n : ℕ} {f g : ℕ → bool}
(hn : ∀(k < n), f k = g k) (fn : f n = ff) (gn : g n = tt) :
cantor_function c f < cantor_function c g :=
begin
have h3 : c < 1, { apply lt_trans h2, norm_num },
induction n with n ih generalizing f g,
{ let f_max : ℕ → bool := λ n, nat.rec ff (λ _ _, tt) n,
have hf_max : ∀n, f n → f_max n,
{ intros n hn, cases n, rw [fn] at hn, contradiction, apply rfl },
let g_min : ℕ → bool := λ n, nat.rec tt (λ _ _, ff) n,
have hg_min : ∀n, g_min n → g n,
{ intros n hn, cases n, rw [gn], apply rfl, contradiction },
apply lt_of_le_of_lt (cantor_function_le (le_of_lt h1) h3 hf_max),
apply lt_of_lt_of_le _ (cantor_function_le (le_of_lt h1) h3 hg_min),
have : c / (1 - c) < 1,
{ rw [div_lt_one_iff_lt, lt_sub_iff_add_lt],
{ convert add_lt_add h2 h2, norm_num },
rwa sub_pos },
convert this,
{ rw [cantor_function_succ _ (le_of_lt h1) h3, div_eq_mul_inv,
←tsum_geometric (le_of_lt h1) h3],
apply zero_add },
{ apply tsum_eq_single 0, intros n hn, cases n, contradiction, refl, apply_instance }},
rw [cantor_function_succ f (le_of_lt h1) h3, cantor_function_succ g (le_of_lt h1) h3],
rw [hn 0 $ zero_lt_succ n],
apply add_lt_add_left, rw mul_lt_mul_left h1, exact ih (λ k hk, hn _ $ succ_lt_succ hk) fn gn
end
lemma injective_cantor_function (h1 : 0 < c) (h2 : c < 1 / 2) :
function.injective (cantor_function c) :=
begin
intros f g hfg, classical, by_contra h, revert hfg,
have : ∃n, f n ≠ g n,
{ rw [←not_forall], intro h', apply h, ext, apply h' },
let n := nat.find this,
have hn : ∀ (k : ℕ), k < n → f k = g k,
{ intros k hk, apply of_not_not, exact nat.find_min this hk },
cases fn : f n,
{ apply ne_of_lt, refine increasing_cantor_function h1 h2 hn fn _,
apply eq_tt_of_not_eq_ff, rw [←fn], apply ne.symm, exact nat.find_spec this },
{ apply ne_of_gt, refine increasing_cantor_function h1 h2 (λ k hk, (hn k hk).symm) _ fn,
apply eq_ff_of_not_eq_tt, rw [←fn], apply ne.symm, exact nat.find_spec this }
end
lemma mk_real : mk ℝ = 2 ^ omega.{0} :=
begin
apply le_antisymm,
{ dsimp [real], apply le_trans mk_quotient_le, apply le_trans (mk_subtype_le _),
rw [←power_def, mk_nat, mk_rat, power_self_eq (le_refl _)] },
{ convert mk_le_of_injective (injective_cantor_function _ _),
rw [←power_def, mk_bool, mk_nat], exact 1 / 3, norm_num, norm_num }
end
lemma not_countable_real : ¬ countable (set.univ : set ℝ) :=
by { rw [countable_iff, not_le, mk_univ, mk_real], apply cantor }
end cardinal
|
c181167aef7b00706705d2b2f957e4f30869f95d
|
fa02ed5a3c9c0adee3c26887a16855e7841c668b
|
/src/data/qpf/univariate/basic.lean
|
d865d2a3eaf10705711aae0dd3ced9b19f7e121d
|
[
"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
| 21,835
|
lean
|
/-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
import data.pfunctor.univariate
/-!
# Quotients of Polynomial Functors
We assume the following:
`P` : a polynomial functor
`W` : its W-type
`M` : its M-type
`F` : a functor
We define:
`q` : `qpf` data, representing `F` as a quotient of `P`
The main goal is to construct:
`fix` : the initial algebra with structure map `F fix → fix`.
`cofix` : the final coalgebra with structure map `cofix → F cofix`
We also show that the composition of qpfs is a qpf, and that the quotient of a qpf
is a qpf.
The present theory focuses on the univariate case for qpfs
## References
* [Jeremy Avigad, Mario M. Carneiro and Simon Hudon, *Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019]
-/
universe u
/--
Quotients of polynomial functors.
Roughly speaking, saying that `F` is a quotient of a polynomial functor means that for each `α`,
elements of `F α` are represented by pairs `⟨a, f⟩`, where `a` is the shape of the object and
`f` indexes the relevant elements of `α`, in a suitably natural manner.
-/
class qpf (F : Type u → Type u) [functor F] :=
(P : pfunctor.{u})
(abs : Π {α}, P.obj α → F α)
(repr : Π {α}, F α → P.obj α)
(abs_repr : ∀ {α} (x : F α), abs (repr x) = x)
(abs_map : ∀ {α β} (f : α → β) (p : P.obj α), abs (f <$> p) = f <$> abs p)
namespace qpf
variables {F : Type u → Type u} [functor F] [q : qpf F]
include q
open functor (liftp liftr)
/-
Show that every qpf is a lawful functor.
Note: every functor has a field, `map_const`, and is_lawful_functor has the defining
characterization. We can only propagate the assumption.
-/
theorem id_map {α : Type*} (x : F α) : id <$> x = x :=
by { rw ←abs_repr x, cases repr x with a f, rw [←abs_map], reflexivity }
theorem comp_map {α β γ : Type*} (f : α → β) (g : β → γ) (x : F α) :
(g ∘ f) <$> x = g <$> f <$> x :=
by { rw ←abs_repr x, cases repr x with a f, rw [←abs_map, ←abs_map, ←abs_map], reflexivity }
theorem is_lawful_functor
(h : ∀ α β : Type u, @functor.map_const F _ α _ = functor.map ∘ function.const β) :
is_lawful_functor F :=
{ map_const_eq := h,
id_map := @id_map F _ _,
comp_map := @comp_map F _ _ }
/-
Lifting predicates and relations
-/
section
open functor
theorem liftp_iff {α : Type u} (p : α → Prop) (x : F α) :
liftp p x ↔ ∃ a f, x = abs ⟨a, f⟩ ∧ ∀ i, p (f i) :=
begin
split,
{ rintros ⟨y, hy⟩, cases h : repr y with a f,
use [a, λ i, (f i).val], split,
{ rw [←hy, ←abs_repr y, h, ←abs_map], reflexivity },
intro i, apply (f i).property },
rintros ⟨a, f, h₀, h₁⟩, dsimp at *,
use abs (⟨a, λ i, ⟨f i, h₁ i⟩⟩),
rw [←abs_map, h₀], reflexivity
end
theorem liftp_iff' {α : Type u} (p : α → Prop) (x : F α) :
liftp p x ↔ ∃ u : q.P.obj α, abs u = x ∧ ∀ i, p (u.snd i) :=
begin
split,
{ rintros ⟨y, hy⟩, cases h : repr y with a f,
use ⟨a, λ i, (f i).val⟩, dsimp, split,
{ rw [←hy, ←abs_repr y, h, ←abs_map], reflexivity },
intro i, apply (f i).property },
rintros ⟨⟨a, f⟩, h₀, h₁⟩, dsimp at *,
use abs (⟨a, λ i, ⟨f i, h₁ i⟩⟩),
rw [←abs_map, ←h₀], reflexivity
end
theorem liftr_iff {α : Type u} (r : α → α → Prop) (x y : F α) :
liftr r x y ↔ ∃ a f₀ f₁, x = abs ⟨a, f₀⟩ ∧ y = abs ⟨a, f₁⟩ ∧ ∀ i, r (f₀ i) (f₁ i) :=
begin
split,
{ rintros ⟨u, xeq, yeq⟩, cases h : repr u with a f,
use [a, λ i, (f i).val.fst, λ i, (f i).val.snd],
split, { rw [←xeq, ←abs_repr u, h, ←abs_map], refl },
split, { rw [←yeq, ←abs_repr u, h, ←abs_map], refl },
intro i, exact (f i).property },
rintros ⟨a, f₀, f₁, xeq, yeq, h⟩,
use abs ⟨a, λ i, ⟨(f₀ i, f₁ i), h i⟩⟩,
dsimp, split,
{ rw [xeq, ←abs_map], refl },
rw [yeq, ←abs_map], refl
end
end
/-
Think of trees in the `W` type corresponding to `P` as representatives of elements of the
least fixed point of `F`, and assign a canonical representative to each equivalence class
of trees.
-/
/-- does recursion on `q.P.W` using `g : F α → α` rather than `g : P α → α` -/
def recF {α : Type*} (g : F α → α) : q.P.W → α
| ⟨a, f⟩ := g (abs ⟨a, λ x, recF (f x)⟩)
theorem recF_eq {α : Type*} (g : F α → α) (x : q.P.W) :
recF g x = g (abs (recF g <$> x.dest)) :=
by cases x; reflexivity
theorem recF_eq' {α : Type*} (g : F α → α) (a : q.P.A) (f : q.P.B a → q.P.W) :
recF g ⟨a, f⟩ = g (abs (recF g <$> ⟨a, f⟩)) :=
rfl
/-- two trees are equivalent if their F-abstractions are -/
inductive Wequiv : q.P.W → q.P.W → Prop
| ind (a : q.P.A) (f f' : q.P.B a → q.P.W) :
(∀ x, Wequiv (f x) (f' x)) → Wequiv ⟨a, f⟩ ⟨a, f'⟩
| abs (a : q.P.A) (f : q.P.B a → q.P.W) (a' : q.P.A) (f' : q.P.B a' → q.P.W) :
abs ⟨a, f⟩ = abs ⟨a', f'⟩ → Wequiv ⟨a, f⟩ ⟨a', f'⟩
| trans (u v w : q.P.W) : Wequiv u v → Wequiv v w → Wequiv u w
/-- recF is insensitive to the representation -/
theorem recF_eq_of_Wequiv {α : Type u} (u : F α → α) (x y : q.P.W) :
Wequiv x y → recF u x = recF u y :=
begin
cases x with a f, cases y with b g,
intro h, induction h,
case qpf.Wequiv.ind : a f f' h ih
{ simp only [recF_eq', pfunctor.map_eq, function.comp, ih] },
case qpf.Wequiv.abs : a f a' f' h
{ simp only [recF_eq', abs_map, h] },
case qpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂
{ exact eq.trans ih₁ ih₂ }
end
theorem Wequiv.abs' (x y : q.P.W) (h : abs x.dest = abs y.dest) :
Wequiv x y :=
by { cases x, cases y, apply Wequiv.abs, apply h }
theorem Wequiv.refl (x : q.P.W) : Wequiv x x :=
by cases x with a f; exact Wequiv.abs a f a f rfl
theorem Wequiv.symm (x y : q.P.W) : Wequiv x y → Wequiv y x :=
begin
cases x with a f, cases y with b g,
intro h, induction h,
case qpf.Wequiv.ind : a f f' h ih
{ exact Wequiv.ind _ _ _ ih },
case qpf.Wequiv.abs : a f a' f' h
{ exact Wequiv.abs _ _ _ _ h.symm },
case qpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂
{ exact qpf.Wequiv.trans _ _ _ ih₂ ih₁}
end
/-- maps every element of the W type to a canonical representative -/
def Wrepr : q.P.W → q.P.W := recF (pfunctor.W.mk ∘ repr)
theorem Wrepr_equiv (x : q.P.W) : Wequiv (Wrepr x) x :=
begin
induction x with a f ih,
apply Wequiv.trans,
{ change Wequiv (Wrepr ⟨a, f⟩) (pfunctor.W.mk (Wrepr <$> ⟨a, f⟩)),
apply Wequiv.abs',
have : Wrepr ⟨a, f⟩ = pfunctor.W.mk (repr (abs (Wrepr <$> ⟨a, f⟩))) := rfl,
rw [this, pfunctor.W.dest_mk, abs_repr],
reflexivity },
apply Wequiv.ind, exact ih
end
/--
Define the fixed point as the quotient of trees under the equivalence relation `Wequiv`.
-/
def W_setoid : setoid q.P.W :=
⟨Wequiv, @Wequiv.refl _ _ _, @Wequiv.symm _ _ _, @Wequiv.trans _ _ _⟩
local attribute [instance] W_setoid
/-- inductive type defined as initial algebra of a Quotient of Polynomial Functor -/
@[nolint has_inhabited_instance]
def fix (F : Type u → Type u) [functor F] [q : qpf F] := quotient (W_setoid : setoid q.P.W)
/-- recursor of a type defined by a qpf -/
def fix.rec {α : Type*} (g : F α → α) : fix F → α :=
quot.lift (recF g) (recF_eq_of_Wequiv g)
/-- access the underlying W-type of a fixpoint data type -/
def fix_to_W : fix F → q.P.W :=
quotient.lift Wrepr (recF_eq_of_Wequiv (λ x, @pfunctor.W.mk q.P (repr x)))
/-- constructor of a type defined by a qpf -/
def fix.mk (x : F (fix F)) : fix F := quot.mk _ (pfunctor.W.mk (fix_to_W <$> repr x))
/-- destructor of a type defined by a qpf -/
def fix.dest : fix F → F (fix F) := fix.rec (functor.map fix.mk)
theorem fix.rec_eq {α : Type*} (g : F α → α) (x : F (fix F)) :
fix.rec g (fix.mk x) = g (fix.rec g <$> x) :=
have recF g ∘ fix_to_W = fix.rec g,
by { apply funext, apply quotient.ind, intro x, apply recF_eq_of_Wequiv,
rw fix_to_W, apply Wrepr_equiv },
begin
conv { to_lhs, rw [fix.rec, fix.mk], dsimp },
cases h : repr x with a f,
rw [pfunctor.map_eq, recF_eq, ←pfunctor.map_eq, pfunctor.W.dest_mk, ←pfunctor.comp_map,
abs_map, ←h, abs_repr, this]
end
theorem fix.ind_aux (a : q.P.A) (f : q.P.B a → q.P.W) :
fix.mk (abs ⟨a, λ x, ⟦f x⟧⟩) = ⟦⟨a, f⟩⟧ :=
have fix.mk (abs ⟨a, λ x, ⟦f x⟧⟩) = ⟦Wrepr ⟨a, f⟩⟧,
begin
apply quot.sound, apply Wequiv.abs',
rw [pfunctor.W.dest_mk, abs_map, abs_repr, ←abs_map, pfunctor.map_eq],
conv { to_rhs, simp only [Wrepr, recF_eq, pfunctor.W.dest_mk, abs_repr] },
reflexivity
end,
by { rw this, apply quot.sound, apply Wrepr_equiv }
theorem fix.ind_rec {α : Type u} (g₁ g₂ : fix F → α)
(h : ∀ x : F (fix F), g₁ <$> x = g₂ <$> x → g₁ (fix.mk x) = g₂ (fix.mk x)) :
∀ x, g₁ x = g₂ x :=
begin
apply quot.ind,
intro x,
induction x with a f ih,
change g₁ ⟦⟨a, f⟩⟧ = g₂ ⟦⟨a, f⟩⟧,
rw [←fix.ind_aux a f], apply h,
rw [←abs_map, ←abs_map, pfunctor.map_eq, pfunctor.map_eq],
dsimp [function.comp],
congr' with x, apply ih
end
theorem fix.rec_unique {α : Type u} (g : F α → α) (h : fix F → α)
(hyp : ∀ x, h (fix.mk x) = g (h <$> x)) :
fix.rec g = h :=
begin
ext x,
apply fix.ind_rec,
intros x hyp',
rw [hyp, ←hyp', fix.rec_eq]
end
theorem fix.mk_dest (x : fix F) : fix.mk (fix.dest x) = x :=
begin
change (fix.mk ∘ fix.dest) x = id x,
apply fix.ind_rec,
intro x, dsimp,
rw [fix.dest, fix.rec_eq, id_map, comp_map],
intro h, rw h
end
theorem fix.dest_mk (x : F (fix F)) : fix.dest (fix.mk x) = x :=
begin
unfold fix.dest, rw [fix.rec_eq, ←fix.dest, ←comp_map],
conv { to_rhs, rw ←(id_map x) },
congr' with x, apply fix.mk_dest
end
theorem fix.ind (p : fix F → Prop)
(h : ∀ x : F (fix F), liftp p x → p (fix.mk x)) :
∀ x, p x :=
begin
apply quot.ind,
intro x,
induction x with a f ih,
change p ⟦⟨a, f⟩⟧,
rw [←fix.ind_aux a f],
apply h,
rw liftp_iff,
refine ⟨_, _, rfl, _⟩,
apply ih
end
end qpf
/-
Construct the final coalgebra to a qpf.
-/
namespace qpf
variables {F : Type u → Type u} [functor F] [q : qpf F]
include q
open functor (liftp liftr)
/-- does recursion on `q.P.M` using `g : α → F α` rather than `g : α → P α` -/
def corecF {α : Type*} (g : α → F α) : α → q.P.M :=
pfunctor.M.corec (λ x, repr (g x))
theorem corecF_eq {α : Type*} (g : α → F α) (x : α) :
pfunctor.M.dest (corecF g x) = corecF g <$> repr (g x) :=
by rw [corecF, pfunctor.M.dest_corec]
/- Equivalence -/
/-- A pre-congruence on q.P.M *viewed as an F-coalgebra*. Not necessarily symmetric. -/
def is_precongr (r : q.P.M → q.P.M → Prop) : Prop :=
∀ ⦃x y⦄, r x y →
abs (quot.mk r <$> pfunctor.M.dest x) = abs (quot.mk r <$> pfunctor.M.dest y)
/-- The maximal congruence on q.P.M -/
def Mcongr : q.P.M → q.P.M → Prop :=
λ x y, ∃ r, is_precongr r ∧ r x y
/-- coinductive type defined as the final coalgebra of a qpf -/
def cofix (F : Type u → Type u) [functor F] [q : qpf F]:= quot (@Mcongr F _ q)
instance [inhabited q.P.A] : inhabited (cofix F) := ⟨ quot.mk _ (default _) ⟩
/-- corecursor for type defined by `cofix` -/
def cofix.corec {α : Type*} (g : α → F α) (x : α) : cofix F :=
quot.mk _ (corecF g x)
/-- destructor for type defined by `cofix` -/
def cofix.dest : cofix F → F (cofix F) :=
quot.lift
(λ x, quot.mk Mcongr <$> (abs (pfunctor.M.dest x)))
begin
rintros x y ⟨r, pr, rxy⟩, dsimp,
have : ∀ x y, r x y → Mcongr x y,
{ intros x y h, exact ⟨r, pr, h⟩ },
rw [←quot.factor_mk_eq _ _ this], dsimp,
conv { to_lhs, rw [comp_map, ←abs_map, pr rxy, abs_map, ←comp_map] }
end
theorem cofix.dest_corec {α : Type u} (g : α → F α) (x : α) :
cofix.dest (cofix.corec g x) = cofix.corec g <$> g x :=
begin
conv { to_lhs, rw [cofix.dest, cofix.corec] }, dsimp,
rw [corecF_eq, abs_map, abs_repr, ←comp_map], reflexivity
end
private theorem cofix.bisim_aux
(r : cofix F → cofix F → Prop)
(h' : ∀ x, r x x)
(h : ∀ x y, r x y → quot.mk r <$> cofix.dest x = quot.mk r <$> cofix.dest y) :
∀ x y, r x y → x = y :=
begin
intro x, apply quot.induction_on x, clear x,
intros x y, apply quot.induction_on y, clear y,
intros y rxy,
apply quot.sound,
let r' := λ x y, r (quot.mk _ x) (quot.mk _ y),
have : is_precongr r',
{ intros a b r'ab,
have h₀: quot.mk r <$> quot.mk Mcongr <$> abs (pfunctor.M.dest a) =
quot.mk r <$> quot.mk Mcongr <$> abs (pfunctor.M.dest b) := h _ _ r'ab,
have h₁ : ∀ u v : q.P.M, Mcongr u v → quot.mk r' u = quot.mk r' v,
{ intros u v cuv, apply quot.sound, dsimp [r'], rw quot.sound cuv, apply h' },
let f : quot r → quot r' := quot.lift (quot.lift (quot.mk r') h₁)
begin
intro c, apply quot.induction_on c, clear c,
intros c d, apply quot.induction_on d, clear d,
intros d rcd, apply quot.sound, apply rcd
end,
have : f ∘ quot.mk r ∘ quot.mk Mcongr = quot.mk r' := rfl,
rw [←this, pfunctor.comp_map _ _ f, pfunctor.comp_map _ _ (quot.mk r),
abs_map, abs_map, abs_map, h₀],
rw [pfunctor.comp_map _ _ f, pfunctor.comp_map _ _ (quot.mk r),
abs_map, abs_map, abs_map] },
refine ⟨r', this, rxy⟩
end
theorem cofix.bisim_rel
(r : cofix F → cofix F → Prop)
(h : ∀ x y, r x y → quot.mk r <$> cofix.dest x = quot.mk r <$> cofix.dest y) :
∀ x y, r x y → x = y :=
let r' x y := x = y ∨ r x y in
begin
intros x y rxy,
apply cofix.bisim_aux r',
{ intro x, left, reflexivity },
{ intros x y r'xy,
cases r'xy, { rw r'xy },
have : ∀ x y, r x y → r' x y := λ x y h, or.inr h,
rw ←quot.factor_mk_eq _ _ this, dsimp,
rw [@comp_map _ _ q _ _ _ (quot.mk r), @comp_map _ _ q _ _ _ (quot.mk r)],
rw h _ _ r'xy },
right, exact rxy
end
theorem cofix.bisim
(r : cofix F → cofix F → Prop)
(h : ∀ x y, r x y → liftr r (cofix.dest x) (cofix.dest y)) :
∀ x y, r x y → x = y :=
begin
apply cofix.bisim_rel,
intros x y rxy,
rcases (liftr_iff r _ _).mp (h x y rxy) with ⟨a, f₀, f₁, dxeq, dyeq, h'⟩,
rw [dxeq, dyeq, ←abs_map, ←abs_map, pfunctor.map_eq, pfunctor.map_eq],
congr' 2 with i,
apply quot.sound,
apply h'
end
theorem cofix.bisim' {α : Type*} (Q : α → Prop) (u v : α → cofix F)
(h : ∀ x, Q x → ∃ a f f',
cofix.dest (u x) = abs ⟨a, f⟩ ∧
cofix.dest (v x) = abs ⟨a, f'⟩ ∧
∀ i, ∃ x', Q x' ∧ f i = u x' ∧ f' i = v x') :
∀ x, Q x → u x = v x :=
λ x Qx,
let R := λ w z : cofix F, ∃ x', Q x' ∧ w = u x' ∧ z = v x' in
cofix.bisim R
(λ x y ⟨x', Qx', xeq, yeq⟩,
begin
rcases h x' Qx' with ⟨a, f, f', ux'eq, vx'eq, h'⟩,
rw liftr_iff,
refine ⟨a, f, f', xeq.symm ▸ ux'eq, yeq.symm ▸ vx'eq, h'⟩,
end)
_ _ ⟨x, Qx, rfl, rfl⟩
end qpf
/-
Composition of qpfs.
-/
namespace qpf
variables {F₂ : Type u → Type u} [functor F₂] [q₂ : qpf F₂]
variables {F₁ : Type u → Type u} [functor F₁] [q₁ : qpf F₁]
include q₂ q₁
/-- composition of qpfs gives another qpf -/
def comp : qpf (functor.comp F₂ F₁) :=
{ P := pfunctor.comp (q₂.P) (q₁.P),
abs := λ α,
begin
dsimp [functor.comp],
intro p,
exact abs ⟨p.1.1, λ x, abs ⟨p.1.2 x, λ y, p.2 ⟨x, y⟩⟩⟩
end,
repr := λ α,
begin
dsimp [functor.comp],
intro y,
refine ⟨⟨(repr y).1, λ u, (repr ((repr y).2 u)).1⟩, _⟩,
dsimp [pfunctor.comp],
intro x,
exact (repr ((repr y).2 x.1)).snd x.2
end,
abs_repr := λ α,
begin
abstract {
dsimp [functor.comp],
intro x,
conv { to_rhs, rw ←abs_repr x},
cases h : repr x with a f,
dsimp,
congr' with x,
cases h' : repr (f x) with b g,
dsimp, rw [←h', abs_repr] }
end,
abs_map := λ α β f,
begin
abstract {
dsimp [functor.comp, pfunctor.comp],
intro p,
cases p with a g, dsimp,
cases a with b h, dsimp,
symmetry,
transitivity,
symmetry,
apply abs_map,
congr,
rw pfunctor.map_eq,
dsimp [function.comp],
simp [abs_map],
split,
reflexivity,
ext x,
rw ←abs_map,
reflexivity }
end
}
end qpf
/-
Quotients.
We show that if `F` is a qpf and `G` is a suitable quotient of `F`, then `G` is a qpf.
-/
namespace qpf
variables {F : Type u → Type u} [functor F] [q : qpf F]
variables {G : Type u → Type u} [functor G]
variable {FG_abs : Π {α}, F α → G α}
variable {FG_repr : Π {α}, G α → F α}
/-- Given a qpf `F` and a well-behaved surjection `FG_abs` from F α to
functor G α, `G` is a qpf. We can consider `G` a quotient on `F` where
elements `x y : F α` are in the same equivalence class if
`FG_abs x = FG_abs y` -/
def quotient_qpf
(FG_abs_repr : Π {α} (x : G α), FG_abs (FG_repr x) = x)
(FG_abs_map : ∀ {α β} (f : α → β) (x : F α), FG_abs (f <$> x) = f <$> FG_abs x) :
qpf G :=
{ P := q.P,
abs := λ {α} p, FG_abs (abs p),
repr := λ {α} x, repr (FG_repr x),
abs_repr := λ {α} x, by rw [abs_repr, FG_abs_repr],
abs_map := λ {α β} f x, by { rw [abs_map, FG_abs_map] } }
end qpf
/-
Support.
-/
namespace qpf
variables {F : Type u → Type u} [functor F] [q : qpf F]
include q
open functor (liftp liftr supp)
open set
theorem mem_supp {α : Type u} (x : F α) (u : α) :
u ∈ supp x ↔ ∀ a f, abs ⟨a, f⟩ = x → u ∈ f '' univ :=
begin
rw [supp], dsimp, split,
{ intros h a f haf,
have : liftp (λ u, u ∈ f '' univ) x,
{ rw liftp_iff, refine ⟨a, f, haf.symm, λ i, mem_image_of_mem _ (mem_univ _)⟩ },
exact h this },
intros h p, rw liftp_iff,
rintros ⟨a, f, xeq, h'⟩,
rcases h a f xeq.symm with ⟨i, _, hi⟩,
rw ←hi, apply h'
end
theorem supp_eq {α : Type u} (x : F α) : supp x = { u | ∀ a f, abs ⟨a, f⟩ = x → u ∈ f '' univ } :=
by ext; apply mem_supp
theorem has_good_supp_iff {α : Type u} (x : F α) :
(∀ p, liftp p x ↔ ∀ u ∈ supp x, p u) ↔
∃ a f, abs ⟨a, f⟩ = x ∧ ∀ a' f', abs ⟨a', f'⟩ = x → f '' univ ⊆ f' '' univ :=
begin
split,
{ intro h,
have : liftp (supp x) x, by rw h; intro u; exact id,
rw liftp_iff at this, rcases this with ⟨a, f, xeq, h'⟩,
refine ⟨a, f, xeq.symm, _⟩,
intros a' f' h'',
rintros u ⟨i, _, hfi⟩,
have : u ∈ supp x, by rw ←hfi; apply h',
exact (mem_supp x u).mp this _ _ h'' },
rintros ⟨a, f, xeq, h⟩ p, rw liftp_iff, split,
{ rintros ⟨a', f', xeq', h'⟩ u usuppx,
rcases (mem_supp x u).mp usuppx a' f' xeq'.symm with ⟨i, _, f'ieq⟩,
rw ←f'ieq, apply h' },
intro h',
refine ⟨a, f, xeq.symm, _⟩, intro i,
apply h', rw mem_supp,
intros a' f' xeq',
apply h a' f' xeq',
apply mem_image_of_mem _ (mem_univ _)
end
variable (q)
/-- A qpf is said to be uniform if every polynomial functor
representing a single value all have the same range. -/
def is_uniform : Prop := ∀ ⦃α : Type u⦄ (a a' : q.P.A)
(f : q.P.B a → α) (f' : q.P.B a' → α),
abs ⟨a, f⟩ = abs ⟨a', f'⟩ → f '' univ = f' '' univ
/-- does `abs` preserve `liftp`? -/
def liftp_preservation : Prop :=
∀ ⦃α⦄ (p : α → Prop) (x : q.P.obj α), liftp p (abs x) ↔ liftp p x
/-- does `abs` preserve `supp`? -/
def supp_preservation : Prop :=
∀ ⦃α⦄ (x : q.P.obj α), supp (abs x) = supp x
variable [q]
theorem supp_eq_of_is_uniform (h : q.is_uniform) {α : Type u} (a : q.P.A) (f : q.P.B a → α) :
supp (abs ⟨a, f⟩) = f '' univ :=
begin
ext u, rw [mem_supp], split,
{ intro h', apply h' _ _ rfl },
intros h' a' f' e,
rw [←h _ _ _ _ e.symm], apply h'
end
theorem liftp_iff_of_is_uniform (h : q.is_uniform) {α : Type u} (x : F α) (p : α → Prop) :
liftp p x ↔ ∀ u ∈ supp x, p u :=
begin
rw [liftp_iff, ←abs_repr x],
cases repr x with a f, split,
{ rintros ⟨a', f', abseq, hf⟩ u,
rw [supp_eq_of_is_uniform h, h _ _ _ _ abseq],
rintros ⟨i, _, hi⟩, rw ←hi, apply hf },
intro h',
refine ⟨a, f, rfl, λ i, h' _ _⟩,
rw supp_eq_of_is_uniform h,
exact ⟨i, mem_univ i, rfl⟩
end
theorem supp_map (h : q.is_uniform) {α β : Type u} (g : α → β) (x : F α) :
supp (g <$> x) = g '' supp x :=
begin
rw ←abs_repr x, cases repr x with a f, rw [←abs_map, pfunctor.map_eq],
rw [supp_eq_of_is_uniform h, supp_eq_of_is_uniform h, image_comp]
end
theorem supp_preservation_iff_uniform :
q.supp_preservation ↔ q.is_uniform :=
begin
split,
{ intros h α a a' f f' h',
rw [← pfunctor.supp_eq,← pfunctor.supp_eq,← h,h',h] },
{ rintros h α ⟨a,f⟩, rwa [supp_eq_of_is_uniform,pfunctor.supp_eq], }
end
theorem supp_preservation_iff_liftp_preservation :
q.supp_preservation ↔ q.liftp_preservation :=
begin
split; intro h,
{ rintros α p ⟨a,f⟩,
have h' := h, rw supp_preservation_iff_uniform at h',
dsimp only [supp_preservation,supp] at h,
rwa [liftp_iff_of_is_uniform,supp_eq_of_is_uniform,pfunctor.liftp_iff'];
try { assumption },
{ simp only [image_univ, mem_range, exists_imp_distrib],
split; intros; subst_vars; solve_by_elim } },
{ rintros α ⟨a,f⟩,
simp only [liftp_preservation] at h,
simp only [supp,h] }
end
theorem liftp_preservation_iff_uniform :
q.liftp_preservation ↔ q.is_uniform :=
by rw [← supp_preservation_iff_liftp_preservation, supp_preservation_iff_uniform]
end qpf
|
ee4ebd79dbe5a0be85bc191603a2e21249ed9d78
|
c777c32c8e484e195053731103c5e52af26a25d1
|
/src/analysis/analytic/composition.lean
|
72c45ccf16d3131400bce594fe5fa82fb43c786e
|
[
"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
| 58,816
|
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, Johan Commelin
-/
import analysis.analytic.basic
import combinatorics.composition
/-!
# Composition of analytic functions
In this file we prove that the composition of analytic functions is analytic.
The argument is the following. Assume `g z = ∑' qₙ (z, ..., z)` and `f y = ∑' pₖ (y, ..., y)`. Then
`g (f y) = ∑' qₙ (∑' pₖ (y, ..., y), ..., ∑' pₖ (y, ..., y))
= ∑' qₙ (p_{i₁} (y, ..., y), ..., p_{iₙ} (y, ..., y))`.
For each `n` and `i₁, ..., iₙ`, define a `i₁ + ... + iₙ` multilinear function mapping
`(y₀, ..., y_{i₁ + ... + iₙ - 1})` to
`qₙ (p_{i₁} (y₀, ..., y_{i₁-1}), p_{i₂} (y_{i₁}, ..., y_{i₁ + i₂ - 1}), ..., p_{iₙ} (....)))`.
Then `g ∘ f` is obtained by summing all these multilinear functions.
To formalize this, we use compositions of an integer `N`, i.e., its decompositions into
a sum `i₁ + ... + iₙ` of positive integers. Given such a composition `c` and two formal
multilinear series `q` and `p`, let `q.comp_along_composition p c` be the above multilinear
function. Then the `N`-th coefficient in the power series expansion of `g ∘ f` is the sum of these
terms over all `c : composition N`.
To complete the proof, we need to show that this power series has a positive radius of convergence.
This follows from the fact that `composition N` has cardinality `2^(N-1)` and estimates on
the norm of `qₙ` and `pₖ`, which give summability. We also need to show that it indeed converges to
`g ∘ f`. For this, we note that the composition of partial sums converges to `g ∘ f`, and that it
corresponds to a part of the whole sum, on a subset that increases to the whole space. By
summability of the norms, this implies the overall convergence.
## Main results
* `q.comp p` is the formal composition of the formal multilinear series `q` and `p`.
* `has_fpower_series_at.comp` states that if two functions `g` and `f` admit power series expansions
`q` and `p`, then `g ∘ f` admits a power series expansion given by `q.comp p`.
* `analytic_at.comp` states that the composition of analytic functions is analytic.
* `formal_multilinear_series.comp_assoc` states that composition is associative on formal
multilinear series.
## Implementation details
The main technical difficulty is to write down things. In particular, we need to define precisely
`q.comp_along_composition p c` and to show that it is indeed a continuous multilinear
function. This requires a whole interface built on the class `composition`. Once this is set,
the main difficulty is to reorder the sums, writing the composition of the partial sums as a sum
over some subset of `Σ n, composition n`. We need to check that the reordering is a bijection,
running over difficulties due to the dependent nature of the types under consideration, that are
controlled thanks to the interface for `composition`.
The associativity of composition on formal multilinear series is a nontrivial result: it does not
follow from the associativity of composition of analytic functions, as there is no uniqueness for
the formal multilinear series representing a function (and also, it holds even when the radius of
convergence of the series is `0`). Instead, we give a direct proof, which amounts to reordering
double sums in a careful way. The change of variables is a canonical (combinatorial) bijection
`composition.sigma_equiv_sigma_pi` between `(Σ (a : composition n), composition a.length)` and
`(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i))`, and is described
in more details below in the paragraph on associativity.
-/
noncomputable theory
variables {𝕜 : Type*} {E F G H : Type*}
open filter list
open_locale topology big_operators classical nnreal ennreal
section topological
variables [comm_ring 𝕜] [add_comm_group E] [add_comm_group F] [add_comm_group G]
variables [module 𝕜 E] [module 𝕜 F] [module 𝕜 G]
variables [topological_space E] [topological_space F] [topological_space G]
/-! ### Composing formal multilinear series -/
namespace formal_multilinear_series
variables [topological_add_group E] [has_continuous_const_smul 𝕜 E]
variables [topological_add_group F] [has_continuous_const_smul 𝕜 F]
variables [topological_add_group G] [has_continuous_const_smul 𝕜 G]
/-!
In this paragraph, we define the composition of formal multilinear series, by summing over all
possible compositions of `n`.
-/
/-- Given a formal multilinear series `p`, a composition `c` of `n` and the index `i` of a
block of `c`, we may define a function on `fin n → E` by picking the variables in the `i`-th block
of `n`, and applying the corresponding coefficient of `p` to these variables. This function is
called `p.apply_composition c v i` for `v : fin n → E` and `i : fin c.length`. -/
def apply_composition
(p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) :
(fin n → E) → (fin (c.length) → F) :=
λ v i, p (c.blocks_fun i) (v ∘ (c.embedding i))
lemma apply_composition_ones (p : formal_multilinear_series 𝕜 E F) (n : ℕ) :
p.apply_composition (composition.ones n) =
λ v i, p 1 (λ _, v (fin.cast_le (composition.length_le _) i)) :=
begin
funext v i,
apply p.congr (composition.ones_blocks_fun _ _),
intros j hjn hj1,
obtain rfl : j = 0, { linarith },
refine congr_arg v _,
rw [fin.ext_iff, fin.coe_cast_le, composition.ones_embedding, fin.coe_mk],
end
lemma apply_composition_single (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (hn : 0 < n)
(v : fin n → E) : p.apply_composition (composition.single n hn) v = λ j, p n v :=
begin
ext j,
refine p.congr (by simp) (λ i hi1 hi2, _),
dsimp,
congr' 1,
convert composition.single_embedding hn ⟨i, hi2⟩,
cases j,
have : j_val = 0 := le_bot_iff.1 (nat.lt_succ_iff.1 j_property),
unfold_coes,
congr; try { assumption <|> simp },
end
@[simp] lemma remove_zero_apply_composition
(p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) :
p.remove_zero.apply_composition c = p.apply_composition c :=
begin
ext v i,
simp [apply_composition, zero_lt_one.trans_le (c.one_le_blocks_fun i), remove_zero_of_pos],
end
/-- Technical lemma stating how `p.apply_composition` commutes with updating variables. This
will be the key point to show that functions constructed from `apply_composition` retain
multilinearity. -/
lemma apply_composition_update
(p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n)
(j : fin n) (v : fin n → E) (z : E) :
p.apply_composition c (function.update v j z) =
function.update (p.apply_composition c v) (c.index j)
(p (c.blocks_fun (c.index j))
(function.update (v ∘ (c.embedding (c.index j))) (c.inv_embedding j) z)) :=
begin
ext k,
by_cases h : k = c.index j,
{ rw h,
let r : fin (c.blocks_fun (c.index j)) → fin n := c.embedding (c.index j),
simp only [function.update_same],
change p (c.blocks_fun (c.index j)) ((function.update v j z) ∘ r) = _,
let j' := c.inv_embedding j,
suffices B : (function.update v j z) ∘ r = function.update (v ∘ r) j' z,
by rw B,
suffices C : (function.update v (r j') z) ∘ r = function.update (v ∘ r) j' z,
by { convert C, exact (c.embedding_comp_inv j).symm },
exact function.update_comp_eq_of_injective _ (c.embedding _).injective _ _ },
{ simp only [h, function.update_eq_self, function.update_noteq, ne.def, not_false_iff],
let r : fin (c.blocks_fun k) → fin n := c.embedding k,
change p (c.blocks_fun k) ((function.update v j z) ∘ r) = p (c.blocks_fun k) (v ∘ r),
suffices B : (function.update v j z) ∘ r = v ∘ r, by rw B,
apply function.update_comp_eq_of_not_mem_range,
rwa c.mem_range_embedding_iff' }
end
@[simp] lemma comp_continuous_linear_map_apply_composition {n : ℕ}
(p : formal_multilinear_series 𝕜 F G) (f : E →L[𝕜] F) (c : composition n) (v : fin n → E) :
(p.comp_continuous_linear_map f).apply_composition c v = p.apply_composition c (f ∘ v) :=
by simp [apply_composition]
end formal_multilinear_series
namespace continuous_multilinear_map
open formal_multilinear_series
variables [topological_add_group E] [has_continuous_const_smul 𝕜 E]
variables [topological_add_group F] [has_continuous_const_smul 𝕜 F]
/-- Given a formal multilinear series `p`, a composition `c` of `n` and a continuous multilinear
map `f` in `c.length` variables, one may form a continuous multilinear map in `n` variables by
applying the right coefficient of `p` to each block of the composition, and then applying `f` to
the resulting vector. It is called `f.comp_along_composition p c`. -/
def comp_along_composition {n : ℕ}
(p : formal_multilinear_series 𝕜 E F) (c : composition n)
(f : continuous_multilinear_map 𝕜 (λ (i : fin c.length), F) G) :
continuous_multilinear_map 𝕜 (λ i : fin n, E) G :=
{ to_fun := λ v, f (p.apply_composition c v),
map_add' := λ _ v i x y, by
{ cases subsingleton.elim ‹_› (fin.decidable_eq _),
simp only [apply_composition_update, continuous_multilinear_map.map_add] },
map_smul' := λ _ v i c x, by
{ cases subsingleton.elim ‹_› (fin.decidable_eq _),
simp only [apply_composition_update, continuous_multilinear_map.map_smul] },
cont := f.cont.comp $ continuous_pi $ λ i, (coe_continuous _).comp $ continuous_pi $ λ j,
continuous_apply _, }
@[simp] lemma comp_along_composition_apply {n : ℕ}
(p : formal_multilinear_series 𝕜 E F) (c : composition n)
(f : continuous_multilinear_map 𝕜 (λ (i : fin c.length), F) G) (v : fin n → E) :
(f.comp_along_composition p c) v = f (p.apply_composition c v) := rfl
end continuous_multilinear_map
namespace formal_multilinear_series
variables [topological_add_group E] [has_continuous_const_smul 𝕜 E]
variables [topological_add_group F] [has_continuous_const_smul 𝕜 F]
variables [topological_add_group G] [has_continuous_const_smul 𝕜 G]
/-- Given two formal multilinear series `q` and `p` and a composition `c` of `n`, one may
form a continuous multilinear map in `n` variables by applying the right coefficient of `p` to each
block of the composition, and then applying `q c.length` to the resulting vector. It is
called `q.comp_along_composition p c`. -/
def comp_along_composition {n : ℕ}
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F)
(c : composition n) : continuous_multilinear_map 𝕜 (λ i : fin n, E) G :=
(q c.length).comp_along_composition p c
@[simp] lemma comp_along_composition_apply {n : ℕ}
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F)
(c : composition n) (v : fin n → E) :
(q.comp_along_composition p c) v = q c.length (p.apply_composition c v) := rfl
/-- Formal composition of two formal multilinear series. The `n`-th coefficient in the composition
is defined to be the sum of `q.comp_along_composition p c` over all compositions of
`n`. In other words, this term (as a multilinear function applied to `v_0, ..., v_{n-1}`) is
`∑'_{k} ∑'_{i₁ + ... + iₖ = n} qₖ (p_{i_1} (...), ..., p_{i_k} (...))`, where one puts all variables
`v_0, ..., v_{n-1}` in increasing order in the dots.
In general, the composition `q ∘ p` only makes sense when the constant coefficient of `p` vanishes.
We give a general formula but which ignores the value of `p 0` instead.
-/
protected def comp (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) :
formal_multilinear_series 𝕜 E G :=
λ n, ∑ c : composition n, q.comp_along_composition p c
/-- The `0`-th coefficient of `q.comp p` is `q 0`. Since these maps are multilinear maps in zero
variables, but on different spaces, we can not state this directly, so we state it when applied to
arbitrary vectors (which have to be the zero vector). -/
lemma comp_coeff_zero (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F)
(v : fin 0 → E) (v' : fin 0 → F) :
(q.comp p) 0 v = q 0 v' :=
begin
let c : composition 0 := composition.ones 0,
dsimp [formal_multilinear_series.comp],
have : {c} = (finset.univ : finset (composition 0)),
{ apply finset.eq_of_subset_of_card_le; simp [finset.card_univ, composition_card 0] },
rw [← this, finset.sum_singleton, comp_along_composition_apply],
symmetry, congr'
end
@[simp] lemma comp_coeff_zero'
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 0 → E) :
(q.comp p) 0 v = q 0 (λ i, 0) :=
q.comp_coeff_zero p v _
/-- The `0`-th coefficient of `q.comp p` is `q 0`. When `p` goes from `E` to `E`, this can be
expressed as a direct equality -/
lemma comp_coeff_zero'' (q : formal_multilinear_series 𝕜 E F)
(p : formal_multilinear_series 𝕜 E E) :
(q.comp p) 0 = q 0 :=
by { ext v, exact q.comp_coeff_zero p _ _ }
/-- The first coefficient of a composition of formal multilinear series is the composition of the
first coefficients seen as continuous linear maps. -/
lemma comp_coeff_one (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F)
(v : fin 1 → E) : (q.comp p) 1 v = q 1 (λ i, p 1 v) :=
begin
have : {composition.ones 1} = (finset.univ : finset (composition 1)) :=
finset.eq_univ_of_card _ (by simp [composition_card]),
simp only [formal_multilinear_series.comp, comp_along_composition_apply, ← this,
finset.sum_singleton],
refine q.congr (by simp) (λ i hi1 hi2, _),
simp only [apply_composition_ones],
exact p.congr rfl (λ j hj1 hj2, by congr)
end
/-- Only `0`-th coefficient of `q.comp p` depends on `q 0`. -/
lemma remove_zero_comp_of_pos (q : formal_multilinear_series 𝕜 F G)
(p : formal_multilinear_series 𝕜 E F) {n : ℕ} (hn : 0 < n) :
q.remove_zero.comp p n = q.comp p n :=
begin
ext v,
simp only [formal_multilinear_series.comp, comp_along_composition,
continuous_multilinear_map.comp_along_composition_apply, continuous_multilinear_map.sum_apply],
apply finset.sum_congr rfl (λ c hc, _),
rw remove_zero_of_pos _ (c.length_pos_of_pos hn)
end
@[simp] lemma comp_remove_zero (q : formal_multilinear_series 𝕜 F G)
(p : formal_multilinear_series 𝕜 E F) :
q.comp p.remove_zero = q.comp p :=
by { ext n, simp [formal_multilinear_series.comp] }
end formal_multilinear_series
end topological
variables [nontrivially_normed_field 𝕜]
[normed_add_comm_group E] [normed_space 𝕜 E]
[normed_add_comm_group F] [normed_space 𝕜 F]
[normed_add_comm_group G] [normed_space 𝕜 G]
[normed_add_comm_group H] [normed_space 𝕜 H]
namespace formal_multilinear_series
/-- The norm of `f.comp_along_composition p c` is controlled by the product of
the norms of the relevant bits of `f` and `p`. -/
lemma comp_along_composition_bound {n : ℕ}
(p : formal_multilinear_series 𝕜 E F) (c : composition n)
(f : continuous_multilinear_map 𝕜 (λ (i : fin c.length), F) G) (v : fin n → E) :
‖f.comp_along_composition p c v‖ ≤
‖f‖ * (∏ i, ‖p (c.blocks_fun i)‖) * (∏ i : fin n, ‖v i‖) :=
calc ‖f.comp_along_composition p c v‖ = ‖f (p.apply_composition c v)‖ : rfl
... ≤ ‖f‖ * ∏ i, ‖p.apply_composition c v i‖ : continuous_multilinear_map.le_op_norm _ _
... ≤ ‖f‖ * ∏ i, ‖p (c.blocks_fun i)‖ *
∏ j : fin (c.blocks_fun i), ‖(v ∘ (c.embedding i)) j‖ :
begin
apply mul_le_mul_of_nonneg_left _ (norm_nonneg _),
refine finset.prod_le_prod (λ i hi, norm_nonneg _) (λ i hi, _),
apply continuous_multilinear_map.le_op_norm,
end
... = ‖f‖ * (∏ i, ‖p (c.blocks_fun i)‖) *
∏ i (j : fin (c.blocks_fun i)), ‖(v ∘ (c.embedding i)) j‖ :
by rw [finset.prod_mul_distrib, mul_assoc]
... = ‖f‖ * (∏ i, ‖p (c.blocks_fun i)‖) * (∏ i : fin n, ‖v i‖) :
by { rw [← c.blocks_fin_equiv.prod_comp, ← finset.univ_sigma_univ, finset.prod_sigma],
congr }
/-- The norm of `q.comp_along_composition p c` is controlled by the product of
the norms of the relevant bits of `q` and `p`. -/
lemma comp_along_composition_norm {n : ℕ}
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F)
(c : composition n) :
‖q.comp_along_composition p c‖ ≤ ‖q c.length‖ * ∏ i, ‖p (c.blocks_fun i)‖ :=
continuous_multilinear_map.op_norm_le_bound _
(mul_nonneg (norm_nonneg _) (finset.prod_nonneg (λ i hi, norm_nonneg _)))
(comp_along_composition_bound _ _ _)
lemma comp_along_composition_nnnorm {n : ℕ}
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F)
(c : composition n) :
‖q.comp_along_composition p c‖₊ ≤ ‖q c.length‖₊ * ∏ i, ‖p (c.blocks_fun i)‖₊ :=
by { rw ← nnreal.coe_le_coe, push_cast, exact q.comp_along_composition_norm p c }
/-!
### The identity formal power series
We will now define the identity power series, and show that it is a neutral element for left and
right composition.
-/
section
variables (𝕜 E)
/-- The identity formal multilinear series, with all coefficients equal to `0` except for `n = 1`
where it is (the continuous multilinear version of) the identity. -/
def id : formal_multilinear_series 𝕜 E E
| 0 := 0
| 1 := (continuous_multilinear_curry_fin1 𝕜 E E).symm (continuous_linear_map.id 𝕜 E)
| _ := 0
/-- The first coefficient of `id 𝕜 E` is the identity. -/
@[simp] lemma id_apply_one (v : fin 1 → E) : (formal_multilinear_series.id 𝕜 E) 1 v = v 0 := rfl
/-- The `n`th coefficient of `id 𝕜 E` is the identity when `n = 1`. We state this in a dependent
way, as it will often appear in this form. -/
lemma id_apply_one' {n : ℕ} (h : n = 1) (v : fin n → E) :
(id 𝕜 E) n v = v ⟨0, h.symm ▸ zero_lt_one⟩ :=
begin
subst n,
apply id_apply_one
end
/-- For `n ≠ 1`, the `n`-th coefficient of `id 𝕜 E` is zero, by definition. -/
@[simp] lemma id_apply_ne_one {n : ℕ} (h : n ≠ 1) : (formal_multilinear_series.id 𝕜 E) n = 0 :=
by { cases n, { refl }, cases n, { contradiction }, refl }
end
@[simp] theorem comp_id (p : formal_multilinear_series 𝕜 E F) : p.comp (id 𝕜 E) = p :=
begin
ext1 n,
dsimp [formal_multilinear_series.comp],
rw finset.sum_eq_single (composition.ones n),
show comp_along_composition p (id 𝕜 E) (composition.ones n) = p n,
{ ext v,
rw comp_along_composition_apply,
apply p.congr (composition.ones_length n),
intros,
rw apply_composition_ones,
refine congr_arg v _,
rw [fin.ext_iff, fin.coe_cast_le, fin.coe_mk, fin.coe_mk], },
show ∀ (b : composition n),
b ∈ finset.univ → b ≠ composition.ones n → comp_along_composition p (id 𝕜 E) b = 0,
{ assume b _ hb,
obtain ⟨k, hk, lt_k⟩ : ∃ (k : ℕ) (H : k ∈ composition.blocks b), 1 < k :=
composition.ne_ones_iff.1 hb,
obtain ⟨i, i_lt, hi⟩ : ∃ (i : ℕ) (h : i < b.blocks.length), b.blocks.nth_le i h = k :=
nth_le_of_mem hk,
let j : fin b.length := ⟨i, b.blocks_length ▸ i_lt⟩,
have A : 1 < b.blocks_fun j := by convert lt_k,
ext v,
rw [comp_along_composition_apply, continuous_multilinear_map.zero_apply],
apply continuous_multilinear_map.map_coord_zero _ j,
dsimp [apply_composition],
rw id_apply_ne_one _ _ (ne_of_gt A),
refl },
{ simp }
end
@[simp] theorem id_comp (p : formal_multilinear_series 𝕜 E F) (h : p 0 = 0) : (id 𝕜 F).comp p = p :=
begin
ext1 n,
by_cases hn : n = 0,
{ rw [hn, h],
ext v,
rw [comp_coeff_zero', id_apply_ne_one _ _ zero_ne_one],
refl },
{ dsimp [formal_multilinear_series.comp],
have n_pos : 0 < n := bot_lt_iff_ne_bot.mpr hn,
rw finset.sum_eq_single (composition.single n n_pos),
show comp_along_composition (id 𝕜 F) p (composition.single n n_pos) = p n,
{ ext v,
rw [comp_along_composition_apply, id_apply_one' _ _ (composition.single_length n_pos)],
dsimp [apply_composition],
refine p.congr rfl (λ i him hin, congr_arg v $ _),
ext, simp },
show ∀ (b : composition n),
b ∈ finset.univ → b ≠ composition.single n n_pos → comp_along_composition (id 𝕜 F) p b = 0,
{ assume b _ hb,
have A : b.length ≠ 1, by simpa [composition.eq_single_iff_length] using hb,
ext v,
rw [comp_along_composition_apply, id_apply_ne_one _ _ A],
refl },
{ simp } }
end
/-! ### Summability properties of the composition of formal power series-/
section
/-- If two formal multilinear series have positive radius of convergence, then the terms appearing
in the definition of their composition are also summable (when multiplied by a suitable positive
geometric term). -/
theorem comp_summable_nnreal
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F)
(hq : 0 < q.radius) (hp : 0 < p.radius) :
∃ r > (0 : ℝ≥0),
summable (λ i : Σ n, composition n, ‖q.comp_along_composition p i.2‖₊ * r ^ i.1) :=
begin
/- This follows from the fact that the growth rate of `‖qₙ‖` and `‖pₙ‖` is at most geometric,
giving a geometric bound on each `‖q.comp_along_composition p op‖`, together with the
fact that there are `2^(n-1)` compositions of `n`, giving at most a geometric loss. -/
rcases ennreal.lt_iff_exists_nnreal_btwn.1 (lt_min zero_lt_one hq) with ⟨rq, rq_pos, hrq⟩,
rcases ennreal.lt_iff_exists_nnreal_btwn.1 (lt_min zero_lt_one hp) with ⟨rp, rp_pos, hrp⟩,
simp only [lt_min_iff, ennreal.coe_lt_one_iff, ennreal.coe_pos] at hrp hrq rp_pos rq_pos,
obtain ⟨Cq, hCq0, hCq⟩ : ∃ Cq > 0, ∀ n, ‖q n‖₊ * rq^n ≤ Cq :=
q.nnnorm_mul_pow_le_of_lt_radius hrq.2,
obtain ⟨Cp, hCp1, hCp⟩ : ∃ Cp ≥ 1, ∀ n, ‖p n‖₊ * rp^n ≤ Cp,
{ rcases p.nnnorm_mul_pow_le_of_lt_radius hrp.2 with ⟨Cp, -, hCp⟩,
exact ⟨max Cp 1, le_max_right _ _, λ n, (hCp n).trans (le_max_left _ _)⟩ },
let r0 : ℝ≥0 := (4 * Cp)⁻¹,
have r0_pos : 0 < r0 := inv_pos.2 (mul_pos zero_lt_four (zero_lt_one.trans_le hCp1)),
set r : ℝ≥0 := rp * rq * r0,
have r_pos : 0 < r := mul_pos (mul_pos rp_pos rq_pos) r0_pos,
have I : ∀ (i : Σ (n : ℕ), composition n),
‖q.comp_along_composition p i.2‖₊ * r ^ i.1 ≤ Cq / 4 ^ i.1,
{ rintros ⟨n, c⟩,
have A,
calc ‖q c.length‖₊ * rq ^ n ≤ ‖q c.length‖₊* rq ^ c.length :
mul_le_mul' le_rfl (pow_le_pow_of_le_one rq.2 hrq.1.le c.length_le)
... ≤ Cq : hCq _,
have B,
calc ((∏ i, ‖p (c.blocks_fun i)‖₊) * rp ^ n)
= ∏ i, ‖p (c.blocks_fun i)‖₊ * rp ^ c.blocks_fun i :
by simp only [finset.prod_mul_distrib, finset.prod_pow_eq_pow_sum, c.sum_blocks_fun]
... ≤ ∏ i : fin c.length, Cp : finset.prod_le_prod' (λ i _, hCp _)
... = Cp ^ c.length : by simp
... ≤ Cp ^ n : pow_le_pow hCp1 c.length_le,
calc ‖q.comp_along_composition p c‖₊ * r ^ n
≤ (‖q c.length‖₊ * ∏ i, ‖p (c.blocks_fun i)‖₊) * r ^ n :
mul_le_mul' (q.comp_along_composition_nnnorm p c) le_rfl
... = (‖q c.length‖₊ * rq ^ n) * ((∏ i, ‖p (c.blocks_fun i)‖₊) * rp ^ n) * r0 ^ n :
by { simp only [r, mul_pow], ring }
... ≤ Cq * Cp ^ n * r0 ^ n : mul_le_mul' (mul_le_mul' A B) le_rfl
... = Cq / 4 ^ n :
begin
simp only [r0],
field_simp [mul_pow, (zero_lt_one.trans_le hCp1).ne'],
ring
end },
refine ⟨r, r_pos, nnreal.summable_of_le I _⟩,
simp_rw div_eq_mul_inv,
refine summable.mul_left _ _,
have : ∀ n : ℕ, has_sum (λ c : composition n, (4 ^ n : ℝ≥0)⁻¹) (2 ^ (n - 1) / 4 ^ n),
{ intro n,
convert has_sum_fintype (λ c : composition n, (4 ^ n : ℝ≥0)⁻¹),
simp [finset.card_univ, composition_card, div_eq_mul_inv] },
refine nnreal.summable_sigma.2 ⟨λ n, (this n).summable, (nnreal.summable_nat_add_iff 1).1 _⟩,
convert (nnreal.summable_geometric (nnreal.div_lt_one_of_lt one_lt_two)).mul_left (1 / 4),
ext1 n,
rw [(this _).tsum_eq, add_tsub_cancel_right],
field_simp [← mul_assoc, pow_succ', mul_pow, show (4 : ℝ≥0) = 2 * 2, from (two_mul 2).symm,
mul_right_comm]
end
end
/-- Bounding below the radius of the composition of two formal multilinear series assuming
summability over all compositions. -/
theorem le_comp_radius_of_summable
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (r : ℝ≥0)
(hr : summable (λ i : (Σ n, composition n), ‖q.comp_along_composition p i.2‖₊ * r ^ i.1)) :
(r : ℝ≥0∞) ≤ (q.comp p).radius :=
begin
refine le_radius_of_bound_nnreal _
(∑' i : (Σ n, composition n), ‖comp_along_composition q p i.snd‖₊ * r ^ i.fst) (λ n, _),
calc ‖formal_multilinear_series.comp q p n‖₊ * r ^ n ≤
∑' (c : composition n), ‖comp_along_composition q p c‖₊ * r ^ n :
begin
rw [tsum_fintype, ← finset.sum_mul],
exact mul_le_mul' (nnnorm_sum_le _ _) le_rfl
end
... ≤ ∑' (i : Σ (n : ℕ), composition n), ‖comp_along_composition q p i.snd‖₊ * r ^ i.fst :
nnreal.tsum_comp_le_tsum_of_inj hr sigma_mk_injective
end
/-!
### Composing analytic functions
Now, we will prove that the composition of the partial sums of `q` and `p` up to order `N` is
given by a sum over some large subset of `Σ n, composition n` of `q.comp_along_composition p`, to
deduce that the series for `q.comp p` indeed converges to `g ∘ f` when `q` is a power series for
`g` and `p` is a power series for `f`.
This proof is a big reindexing argument of a sum. Since it is a bit involved, we define first
the source of the change of variables (`comp_partial_source`), its target
(`comp_partial_target`) and the change of variables itself (`comp_change_of_variables`) before
giving the main statement in `comp_partial_sum`. -/
/-- Source set in the change of variables to compute the composition of partial sums of formal
power series.
See also `comp_partial_sum`. -/
def comp_partial_sum_source (m M N : ℕ) : finset (Σ n, (fin n) → ℕ) :=
finset.sigma (finset.Ico m M) (λ (n : ℕ), fintype.pi_finset (λ (i : fin n), finset.Ico 1 N) : _)
@[simp] lemma mem_comp_partial_sum_source_iff (m M N : ℕ) (i : Σ n, (fin n) → ℕ) :
i ∈ comp_partial_sum_source m M N ↔
(m ≤ i.1 ∧ i.1 < M) ∧ ∀ (a : fin i.1), 1 ≤ i.2 a ∧ i.2 a < N :=
by simp only [comp_partial_sum_source, finset.mem_Ico, fintype.mem_pi_finset, finset.mem_sigma,
iff_self]
/-- Change of variables appearing to compute the composition of partial sums of formal
power series -/
def comp_change_of_variables (m M N : ℕ) (i : Σ n, (fin n) → ℕ)
(hi : i ∈ comp_partial_sum_source m M N) : (Σ n, composition n) :=
begin
rcases i with ⟨n, f⟩,
rw mem_comp_partial_sum_source_iff at hi,
refine ⟨∑ j, f j, of_fn (λ a, f a), λ i hi', _, by simp [sum_of_fn]⟩,
obtain ⟨j, rfl⟩ : ∃ (j : fin n), f j = i, by rwa [mem_of_fn, set.mem_range] at hi',
exact (hi.2 j).1
end
@[simp] lemma comp_change_of_variables_length
(m M N : ℕ) {i : Σ n, (fin n) → ℕ} (hi : i ∈ comp_partial_sum_source m M N) :
composition.length (comp_change_of_variables m M N i hi).2 = i.1 :=
begin
rcases i with ⟨k, blocks_fun⟩,
dsimp [comp_change_of_variables],
simp only [composition.length, map_of_fn, length_of_fn]
end
lemma comp_change_of_variables_blocks_fun
(m M N : ℕ) {i : Σ n, (fin n) → ℕ} (hi : i ∈ comp_partial_sum_source m M N) (j : fin i.1) :
(comp_change_of_variables m M N i hi).2.blocks_fun
⟨j, (comp_change_of_variables_length m M N hi).symm ▸ j.2⟩ = i.2 j :=
begin
rcases i with ⟨n, f⟩,
dsimp [composition.blocks_fun, composition.blocks, comp_change_of_variables],
simp only [map_of_fn, nth_le_of_fn', function.comp_app],
apply congr_arg,
exact fin.eta _ _
end
/-- Target set in the change of variables to compute the composition of partial sums of formal
power series, here given a a set. -/
def comp_partial_sum_target_set (m M N : ℕ) : set (Σ n, composition n) :=
{i | (m ≤ i.2.length) ∧ (i.2.length < M) ∧ (∀ (j : fin i.2.length), i.2.blocks_fun j < N)}
lemma comp_partial_sum_target_subset_image_comp_partial_sum_source
(m M N : ℕ) (i : Σ n, composition n) (hi : i ∈ comp_partial_sum_target_set m M N) :
∃ j (hj : j ∈ comp_partial_sum_source m M N), i = comp_change_of_variables m M N j hj :=
begin
rcases i with ⟨n, c⟩,
refine ⟨⟨c.length, c.blocks_fun⟩, _, _⟩,
{ simp only [comp_partial_sum_target_set, set.mem_set_of_eq] at hi,
simp only [mem_comp_partial_sum_source_iff, hi.left, hi.right, true_and, and_true],
exact λ a, c.one_le_blocks' _ },
{ dsimp [comp_change_of_variables],
rw composition.sigma_eq_iff_blocks_eq,
simp only [composition.blocks_fun, composition.blocks, subtype.coe_eta, nth_le_map'],
conv_lhs { rw ← of_fn_nth_le c.blocks } }
end
/-- Target set in the change of variables to compute the composition of partial sums of formal
power series, here given a a finset.
See also `comp_partial_sum`. -/
def comp_partial_sum_target (m M N : ℕ) : finset (Σ n, composition n) :=
set.finite.to_finset $ ((finset.finite_to_set _).dependent_image _).subset $
comp_partial_sum_target_subset_image_comp_partial_sum_source m M N
@[simp] lemma mem_comp_partial_sum_target_iff {m M N : ℕ} {a : Σ n, composition n} :
a ∈ comp_partial_sum_target m M N ↔
m ≤ a.2.length ∧ a.2.length < M ∧ (∀ (j : fin a.2.length), a.2.blocks_fun j < N) :=
by simp [comp_partial_sum_target, comp_partial_sum_target_set]
/-- `comp_change_of_variables m M N` is a bijection between `comp_partial_sum_source m M N`
and `comp_partial_sum_target m M N`, yielding equal sums for functions that correspond to each
other under the bijection. As `comp_change_of_variables m M N` is a dependent function, stating
that it is a bijection is not directly possible, but the consequence on sums can be stated
more easily. -/
lemma comp_change_of_variables_sum {α : Type*} [add_comm_monoid α] (m M N : ℕ)
(f : (Σ (n : ℕ), fin n → ℕ) → α) (g : (Σ n, composition n) → α)
(h : ∀ e (he : e ∈ comp_partial_sum_source m M N),
f e = g (comp_change_of_variables m M N e he)) :
∑ e in comp_partial_sum_source m M N, f e = ∑ e in comp_partial_sum_target m M N, g e :=
begin
apply finset.sum_bij (comp_change_of_variables m M N),
-- We should show that the correspondance we have set up is indeed a bijection
-- between the index sets of the two sums.
-- 1 - show that the image belongs to `comp_partial_sum_target m N N`
{ rintros ⟨k, blocks_fun⟩ H,
rw mem_comp_partial_sum_source_iff at H,
simp only [mem_comp_partial_sum_target_iff, composition.length, composition.blocks, H.left,
map_of_fn, length_of_fn, true_and, comp_change_of_variables],
assume j,
simp only [composition.blocks_fun, (H.right _).right, nth_le_of_fn'] },
-- 2 - show that the composition gives the `comp_along_composition` application
{ rintros ⟨k, blocks_fun⟩ H,
rw h },
-- 3 - show that the map is injective
{ rintros ⟨k, blocks_fun⟩ ⟨k', blocks_fun'⟩ H H' heq,
obtain rfl : k = k',
{ have := (comp_change_of_variables_length m M N H).symm,
rwa [heq, comp_change_of_variables_length] at this, },
congr,
funext i,
calc blocks_fun i = (comp_change_of_variables m M N _ H).2.blocks_fun _ :
(comp_change_of_variables_blocks_fun m M N H i).symm
... = (comp_change_of_variables m M N _ H').2.blocks_fun _ :
begin
apply composition.blocks_fun_congr; try { rw heq },
refl
end
... = blocks_fun' i : comp_change_of_variables_blocks_fun m M N H' i },
-- 4 - show that the map is surjective
{ assume i hi,
apply comp_partial_sum_target_subset_image_comp_partial_sum_source m M N i,
simpa [comp_partial_sum_target] using hi }
end
/-- The auxiliary set corresponding to the composition of partial sums asymptotically contains
all possible compositions. -/
lemma comp_partial_sum_target_tendsto_at_top :
tendsto (λ N, comp_partial_sum_target 0 N N) at_top at_top :=
begin
apply monotone.tendsto_at_top_finset,
{ assume m n hmn a ha,
have : ∀ i, i < m → i < n := λ i hi, lt_of_lt_of_le hi hmn,
tidy },
{ rintros ⟨n, c⟩,
simp only [mem_comp_partial_sum_target_iff],
obtain ⟨n, hn⟩ : bdd_above ↑(finset.univ.image (λ (i : fin c.length), c.blocks_fun i)) :=
finset.bdd_above _,
refine ⟨max n c.length + 1, bot_le, lt_of_le_of_lt (le_max_right n c.length) (lt_add_one _),
λ j, lt_of_le_of_lt (le_trans _ (le_max_left _ _)) (lt_add_one _)⟩,
apply hn,
simp only [finset.mem_image_of_mem, finset.mem_coe, finset.mem_univ] }
end
/-- Composing the partial sums of two multilinear series coincides with the sum over all
compositions in `comp_partial_sum_target 0 N N`. This is precisely the motivation for the
definition of `comp_partial_sum_target`. -/
lemma comp_partial_sum
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (N : ℕ) (z : E) :
q.partial_sum N (∑ i in finset.Ico 1 N, p i (λ j, z)) =
∑ i in comp_partial_sum_target 0 N N, q.comp_along_composition p i.2 (λ j, z) :=
begin
-- we expand the composition, using the multilinearity of `q` to expand along each coordinate.
suffices H : ∑ n in finset.range N, ∑ r in fintype.pi_finset (λ (i : fin n), finset.Ico 1 N),
q n (λ (i : fin n), p (r i) (λ j, z)) =
∑ i in comp_partial_sum_target 0 N N, q.comp_along_composition p i.2 (λ j, z),
by simpa only [formal_multilinear_series.partial_sum,
continuous_multilinear_map.map_sum_finset] using H,
-- rewrite the first sum as a big sum over a sigma type, in the finset
-- `comp_partial_sum_target 0 N N`
rw [finset.range_eq_Ico, finset.sum_sigma'],
-- use `comp_change_of_variables_sum`, saying that this change of variables respects sums
apply comp_change_of_variables_sum 0 N N,
rintros ⟨k, blocks_fun⟩ H,
apply congr _ (comp_change_of_variables_length 0 N N H).symm,
intros,
rw ← comp_change_of_variables_blocks_fun 0 N N H,
refl
end
end formal_multilinear_series
open formal_multilinear_series
/-- If two functions `g` and `f` have power series `q` and `p` respectively at `f x` and `x`, then
`g ∘ f` admits the power series `q.comp p` at `x`. -/
theorem has_fpower_series_at.comp {g : F → G} {f : E → F}
{q : formal_multilinear_series 𝕜 F G} {p : formal_multilinear_series 𝕜 E F} {x : E}
(hg : has_fpower_series_at g q (f x)) (hf : has_fpower_series_at f p x) :
has_fpower_series_at (g ∘ f) (q.comp p) x :=
begin
/- Consider `rf` and `rg` such that `f` and `g` have power series expansion on the disks
of radius `rf` and `rg`. -/
rcases hg with ⟨rg, Hg⟩,
rcases hf with ⟨rf, Hf⟩,
/- The terms defining `q.comp p` are geometrically summable in a disk of some radius `r`. -/
rcases q.comp_summable_nnreal p Hg.radius_pos Hf.radius_pos with ⟨r, r_pos : 0 < r, hr⟩,
/- We will consider `y` which is smaller than `r` and `rf`, and also small enough that
`f (x + y)` is close enough to `f x` to be in the disk where `g` is well behaved. Let
`min (r, rf, δ)` be this new radius.-/
have : continuous_at f x := Hf.analytic_at.continuous_at,
obtain ⟨δ, δpos, hδ⟩ : ∃ (δ : ℝ≥0∞) (H : 0 < δ),
∀ {z : E}, z ∈ emetric.ball x δ → f z ∈ emetric.ball (f x) rg,
{ have : emetric.ball (f x) rg ∈ 𝓝 (f x) := emetric.ball_mem_nhds _ Hg.r_pos,
rcases emetric.mem_nhds_iff.1 (Hf.analytic_at.continuous_at this) with ⟨δ, δpos, Hδ⟩,
exact ⟨δ, δpos, λ z hz, Hδ hz⟩ },
let rf' := min rf δ,
have min_pos : 0 < min rf' r,
by simp only [r_pos, Hf.r_pos, δpos, lt_min_iff, ennreal.coe_pos, and_self],
/- We will show that `g ∘ f` admits the power series `q.comp p` in the disk of
radius `min (r, rf', δ)`. -/
refine ⟨min rf' r, _⟩,
refine ⟨le_trans (min_le_right rf' r)
(formal_multilinear_series.le_comp_radius_of_summable q p r hr), min_pos, λ y hy, _⟩,
/- Let `y` satisfy `‖y‖ < min (r, rf', δ)`. We want to show that `g (f (x + y))` is the sum of
`q.comp p` applied to `y`. -/
-- First, check that `y` is small enough so that estimates for `f` and `g` apply.
have y_mem : y ∈ emetric.ball (0 : E) rf :=
(emetric.ball_subset_ball (le_trans (min_le_left _ _) (min_le_left _ _))) hy,
have fy_mem : f (x + y) ∈ emetric.ball (f x) rg,
{ apply hδ,
have : y ∈ emetric.ball (0 : E) δ :=
(emetric.ball_subset_ball (le_trans (min_le_left _ _) (min_le_right _ _))) hy,
simpa [edist_eq_coe_nnnorm_sub, edist_eq_coe_nnnorm] },
/- Now the proof starts. To show that the sum of `q.comp p` at `y` is `g (f (x + y))`, we will
write `q.comp p` applied to `y` as a big sum over all compositions. Since the sum is
summable, to get its convergence it suffices to get the convergence along some increasing sequence
of sets. We will use the sequence of sets `comp_partial_sum_target 0 n n`, along which the sum is
exactly the composition of the partial sums of `q` and `p`, by design. To show that it converges
to `g (f (x + y))`, pointwise convergence would not be enough, but we have uniform convergence
to save the day. -/
-- First step: the partial sum of `p` converges to `f (x + y)`.
have A : tendsto (λ n, ∑ a in finset.Ico 1 n, p a (λ b, y)) at_top (𝓝 (f (x + y) - f x)),
{ have L : ∀ᶠ n in at_top, ∑ a in finset.range n, p a (λ b, y) - f x =
∑ a in finset.Ico 1 n, p a (λ b, y),
{ rw eventually_at_top,
refine ⟨1, λ n hn, _⟩,
symmetry,
rw [eq_sub_iff_add_eq', finset.range_eq_Ico, ← Hf.coeff_zero (λi, y),
finset.sum_eq_sum_Ico_succ_bot hn] },
have : tendsto (λ n, ∑ a in finset.range n, p a (λ b, y) - f x) at_top (𝓝 (f (x + y) - f x)) :=
(Hf.has_sum y_mem).tendsto_sum_nat.sub tendsto_const_nhds,
exact tendsto.congr' L this },
-- Second step: the composition of the partial sums of `q` and `p` converges to `g (f (x + y))`.
have B : tendsto (λ n, q.partial_sum n (∑ a in finset.Ico 1 n, p a (λ b, y)))
at_top (𝓝 (g (f (x + y)))),
{ -- we use the fact that the partial sums of `q` converge locally uniformly to `g`, and that
-- composition passes to the limit under locally uniform convergence.
have B₁ : continuous_at (λ (z : F), g (f x + z)) (f (x + y) - f x),
{ refine continuous_at.comp _ (continuous_const.add continuous_id).continuous_at,
simp only [add_sub_cancel'_right, id.def],
exact Hg.continuous_on.continuous_at (is_open.mem_nhds (emetric.is_open_ball) fy_mem) },
have B₂ : f (x + y) - f x ∈ emetric.ball (0 : F) rg,
by simpa [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] using fy_mem,
rw [← emetric.is_open_ball.nhds_within_eq B₂] at A,
convert Hg.tendsto_locally_uniformly_on.tendsto_comp B₁.continuous_within_at B₂ A,
simp only [add_sub_cancel'_right] },
-- Third step: the sum over all compositions in `comp_partial_sum_target 0 n n` converges to
-- `g (f (x + y))`. As this sum is exactly the composition of the partial sum, this is a direct
-- consequence of the second step
have C : tendsto (λ n,
∑ i in comp_partial_sum_target 0 n n, q.comp_along_composition p i.2 (λ j, y))
at_top (𝓝 (g (f (x + y)))),
by simpa [comp_partial_sum] using B,
-- Fourth step: the sum over all compositions is `g (f (x + y))`. This follows from the
-- convergence along a subsequence proved in the third step, and the fact that the sum is Cauchy
-- thanks to the summability properties.
have D : has_sum (λ i : (Σ n, composition n),
q.comp_along_composition p i.2 (λ j, y)) (g (f (x + y))),
{ have cau : cauchy_seq (λ (s : finset (Σ n, composition n)),
∑ i in s, q.comp_along_composition p i.2 (λ j, y)),
{ apply cauchy_seq_finset_of_norm_bounded _ (nnreal.summable_coe.2 hr) _,
simp only [coe_nnnorm, nnreal.coe_mul, nnreal.coe_pow],
rintros ⟨n, c⟩,
calc ‖(comp_along_composition q p c) (λ (j : fin n), y)‖
≤ ‖comp_along_composition q p c‖ * ∏ j : fin n, ‖y‖ :
by apply continuous_multilinear_map.le_op_norm
... ≤ ‖comp_along_composition q p c‖ * (r : ℝ) ^ n :
begin
apply mul_le_mul_of_nonneg_left _ (norm_nonneg _),
rw [finset.prod_const, finset.card_fin],
apply pow_le_pow_of_le_left (norm_nonneg _),
rw [emetric.mem_ball, edist_eq_coe_nnnorm] at hy,
have := (le_trans (le_of_lt hy) (min_le_right _ _)),
rwa [ennreal.coe_le_coe, ← nnreal.coe_le_coe, coe_nnnorm] at this
end },
exact tendsto_nhds_of_cauchy_seq_of_subseq cau
comp_partial_sum_target_tendsto_at_top C },
-- Fifth step: the sum over `n` of `q.comp p n` can be expressed as a particular resummation of
-- the sum over all compositions, by grouping together the compositions of the same
-- integer `n`. The convergence of the whole sum therefore implies the converence of the sum
-- of `q.comp p n`
have E : has_sum (λ n, (q.comp p) n (λ j, y)) (g (f (x + y))),
{ apply D.sigma,
assume n,
dsimp [formal_multilinear_series.comp],
convert has_sum_fintype _,
simp only [continuous_multilinear_map.sum_apply],
refl },
exact E
end
/-- If two functions `g` and `f` are analytic respectively at `f x` and `x`, then `g ∘ f` is
analytic at `x`. -/
theorem analytic_at.comp {g : F → G} {f : E → F} {x : E}
(hg : analytic_at 𝕜 g (f x)) (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (g ∘ f) x :=
let ⟨q, hq⟩ := hg, ⟨p, hp⟩ := hf in (hq.comp hp).analytic_at
/-!
### Associativity of the composition of formal multilinear series
In this paragraph, we prove the associativity of the composition of formal power series.
By definition,
```
(r.comp q).comp p n v
= ∑_{i₁ + ... + iₖ = n} (r.comp q)ₖ (p_{i₁} (v₀, ..., v_{i₁ -1}), p_{i₂} (...), ..., p_{iₖ}(...))
= ∑_{a : composition n} (r.comp q) a.length (apply_composition p a v)
```
decomposing `r.comp q` in the same way, we get
```
(r.comp q).comp p n v
= ∑_{a : composition n} ∑_{b : composition a.length}
r b.length (apply_composition q b (apply_composition p a v))
```
On the other hand,
```
r.comp (q.comp p) n v = ∑_{c : composition n} r c.length (apply_composition (q.comp p) c v)
```
Here, `apply_composition (q.comp p) c v` is a vector of length `c.length`, whose `i`-th term is
given by `(q.comp p) (c.blocks_fun i) (v_l, v_{l+1}, ..., v_{m-1})` where `{l, ..., m-1}` is the
`i`-th block in the composition `c`, of length `c.blocks_fun i` by definition. To compute this term,
we expand it as `∑_{dᵢ : composition (c.blocks_fun i)} q dᵢ.length (apply_composition p dᵢ v')`,
where `v' = (v_l, v_{l+1}, ..., v_{m-1})`. Therefore, we get
```
r.comp (q.comp p) n v =
∑_{c : composition n} ∑_{d₀ : composition (c.blocks_fun 0),
..., d_{c.length - 1} : composition (c.blocks_fun (c.length - 1))}
r c.length (λ i, q dᵢ.length (apply_composition p dᵢ v'ᵢ))
```
To show that these terms coincide, we need to explain how to reindex the sums to put them in
bijection (and then the terms we are summing will correspond to each other). Suppose we have a
composition `a` of `n`, and a composition `b` of `a.length`. Then `b` indicates how to group
together some blocks of `a`, giving altogether `b.length` blocks of blocks. These blocks of blocks
can be called `d₀, ..., d_{a.length - 1}`, and one obtains a composition `c` of `n` by saying that
each `dᵢ` is one single block. Conversely, if one starts from `c` and the `dᵢ`s, one can concatenate
the `dᵢ`s to obtain a composition `a` of `n`, and register the lengths of the `dᵢ`s in a composition
`b` of `a.length`.
An example might be enlightening. Suppose `a = [2, 2, 3, 4, 2]`. It is a composition of
length 5 of 13. The content of the blocks may be represented as `0011222333344`.
Now take `b = [2, 3]` as a composition of `a.length = 5`. It says that the first 2 blocks of `a`
should be merged, and the last 3 blocks of `a` should be merged, giving a new composition of `13`
made of two blocks of length `4` and `9`, i.e., `c = [4, 9]`. But one can also remember that
the new first block was initially made of two blocks of size `2`, so `d₀ = [2, 2]`, and the new
second block was initially made of three blocks of size `3`, `4` and `2`, so `d₁ = [3, 4, 2]`.
This equivalence is called `composition.sigma_equiv_sigma_pi n` below.
We start with preliminary results on compositions, of a very specialized nature, then define the
equivalence `composition.sigma_equiv_sigma_pi n`, and we deduce finally the associativity of
composition of formal multilinear series in `formal_multilinear_series.comp_assoc`.
-/
namespace composition
variable {n : ℕ}
/-- Rewriting equality in the dependent type `Σ (a : composition n), composition a.length)` in
non-dependent terms with lists, requiring that the blocks coincide. -/
lemma sigma_composition_eq_iff (i j : Σ (a : composition n), composition a.length) :
i = j ↔ i.1.blocks = j.1.blocks ∧ i.2.blocks = j.2.blocks :=
begin
refine ⟨by rintro rfl; exact ⟨rfl, rfl⟩, _⟩,
rcases i with ⟨a, b⟩,
rcases j with ⟨a', b'⟩,
rintros ⟨h, h'⟩,
have H : a = a', by { ext1, exact h },
induction H, congr, ext1, exact h'
end
/-- Rewriting equality in the dependent type
`Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)` in
non-dependent terms with lists, requiring that the lists of blocks coincide. -/
lemma sigma_pi_composition_eq_iff
(u v : Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) :
u = v ↔ of_fn (λ i, (u.2 i).blocks) = of_fn (λ i, (v.2 i).blocks) :=
begin
refine ⟨λ H, by rw H, λ H, _⟩,
rcases u with ⟨a, b⟩,
rcases v with ⟨a', b'⟩,
dsimp at H,
have h : a = a',
{ ext1,
have : map list.sum (of_fn (λ (i : fin (composition.length a)), (b i).blocks)) =
map list.sum (of_fn (λ (i : fin (composition.length a')), (b' i).blocks)), by rw H,
simp only [map_of_fn] at this,
change of_fn (λ (i : fin (composition.length a)), (b i).blocks.sum) =
of_fn (λ (i : fin (composition.length a')), (b' i).blocks.sum) at this,
simpa [composition.blocks_sum, composition.of_fn_blocks_fun] using this },
induction h,
simp only [true_and, eq_self_iff_true, heq_iff_eq],
ext i : 2,
have : nth_le (of_fn (λ (i : fin (composition.length a)), (b i).blocks)) i (by simp [i.is_lt]) =
nth_le (of_fn (λ (i : fin (composition.length a)), (b' i).blocks)) i (by simp [i.is_lt]) :=
nth_le_of_eq H _,
rwa [nth_le_of_fn, nth_le_of_fn] at this
end
/-- When `a` is a composition of `n` and `b` is a composition of `a.length`, `a.gather b` is the
composition of `n` obtained by gathering all the blocks of `a` corresponding to a block of `b`.
For instance, if `a = [6, 5, 3, 5, 2]` and `b = [2, 3]`, one should gather together
the first two blocks of `a` and its last three blocks, giving `a.gather b = [11, 10]`. -/
def gather (a : composition n) (b : composition a.length) : composition n :=
{ blocks := (a.blocks.split_wrt_composition b).map sum,
blocks_pos :=
begin
rw forall_mem_map_iff,
intros j hj,
suffices H : ∀ i ∈ j, 1 ≤ i, from
calc 0 < j.length : length_pos_of_mem_split_wrt_composition hj
... ≤ j.sum : length_le_sum_of_one_le _ H,
intros i hi,
apply a.one_le_blocks,
rw ← a.blocks.join_split_wrt_composition b,
exact mem_join_of_mem hj hi,
end,
blocks_sum := by { rw [← sum_join, join_split_wrt_composition, a.blocks_sum] } }
lemma length_gather (a : composition n) (b : composition a.length) :
length (a.gather b) = b.length :=
show (map list.sum (a.blocks.split_wrt_composition b)).length = b.blocks.length,
by rw [length_map, length_split_wrt_composition]
/-- An auxiliary function used in the definition of `sigma_equiv_sigma_pi` below, associating to
two compositions `a` of `n` and `b` of `a.length`, and an index `i` bounded by the length of
`a.gather b`, the subcomposition of `a` made of those blocks belonging to the `i`-th block of
`a.gather b`. -/
def sigma_composition_aux (a : composition n) (b : composition a.length)
(i : fin (a.gather b).length) :
composition ((a.gather b).blocks_fun i) :=
{ blocks := nth_le (a.blocks.split_wrt_composition b) i
(by { rw [length_split_wrt_composition, ← length_gather], exact i.2 }),
blocks_pos := assume i hi, a.blocks_pos
(by { rw ← a.blocks.join_split_wrt_composition b,
exact mem_join_of_mem (nth_le_mem _ _ _) hi }),
blocks_sum := by simp only [composition.blocks_fun, nth_le_map', composition.gather] }
lemma length_sigma_composition_aux (a : composition n) (b : composition a.length)
(i : fin b.length) :
composition.length (composition.sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ i.2⟩) =
composition.blocks_fun b i :=
show list.length (nth_le (split_wrt_composition a.blocks b) i _) = blocks_fun b i,
by { rw [nth_le_map_rev list.length, nth_le_of_eq (map_length_split_wrt_composition _ _)], refl }
lemma blocks_fun_sigma_composition_aux (a : composition n) (b : composition a.length)
(i : fin b.length) (j : fin (blocks_fun b i)) :
blocks_fun (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ i.2⟩)
⟨j, (length_sigma_composition_aux a b i).symm ▸ j.2⟩ = blocks_fun a (embedding b i j) :=
show nth_le (nth_le _ _ _) _ _ = nth_le a.blocks _ _,
by { rw [nth_le_of_eq (nth_le_split_wrt_composition _ _ _), nth_le_drop', nth_le_take'], refl }
/-- Auxiliary lemma to prove that the composition of formal multilinear series is associative.
Consider a composition `a` of `n` and a composition `b` of `a.length`. Grouping together some
blocks of `a` according to `b` as in `a.gather b`, one can compute the total size of the blocks
of `a` up to an index `size_up_to b i + j` (where the `j` corresponds to a set of blocks of `a`
that do not fill a whole block of `a.gather b`). The first part corresponds to a sum of blocks
in `a.gather b`, and the second one to a sum of blocks in the next block of
`sigma_composition_aux a b`. This is the content of this lemma. -/
lemma size_up_to_size_up_to_add (a : composition n) (b : composition a.length)
{i j : ℕ} (hi : i < b.length) (hj : j < blocks_fun b ⟨i, hi⟩) :
size_up_to a (size_up_to b i + j) = size_up_to (a.gather b) i +
(size_up_to (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ hi⟩) j) :=
begin
induction j with j IHj,
{ show sum (take ((b.blocks.take i).sum) a.blocks) =
sum (take i (map sum (split_wrt_composition a.blocks b))),
induction i with i IH,
{ refl },
{ have A : i < b.length := nat.lt_of_succ_lt hi,
have B : i < list.length (map list.sum (split_wrt_composition a.blocks b)), by simp [A],
have C : 0 < blocks_fun b ⟨i, A⟩ := composition.blocks_pos' _ _ _,
rw [sum_take_succ _ _ B, ← IH A C],
have : take (sum (take i b.blocks)) a.blocks =
take (sum (take i b.blocks)) (take (sum (take (i+1) b.blocks)) a.blocks),
{ rw [take_take, min_eq_left],
apply monotone_sum_take _ (nat.le_succ _) },
rw [this, nth_le_map', nth_le_split_wrt_composition,
← take_append_drop (sum (take i b.blocks))
((take (sum (take (nat.succ i) b.blocks)) a.blocks)), sum_append],
congr,
rw [take_append_drop] } },
{ have A : j < blocks_fun b ⟨i, hi⟩ := lt_trans (lt_add_one j) hj,
have B : j < length (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ hi⟩),
by { convert A, rw [← length_sigma_composition_aux], refl },
have C : size_up_to b i + j < size_up_to b (i + 1),
{ simp only [size_up_to_succ b hi, add_lt_add_iff_left],
exact A },
have D : size_up_to b i + j < length a := lt_of_lt_of_le C (b.size_up_to_le _),
have : size_up_to b i + nat.succ j = (size_up_to b i + j).succ := rfl,
rw [this, size_up_to_succ _ D, IHj A, size_up_to_succ _ B],
simp only [sigma_composition_aux, add_assoc, add_left_inj, fin.coe_mk],
rw [nth_le_of_eq (nth_le_split_wrt_composition _ _ _), nth_le_drop', nth_le_take _ _ C] }
end
/--
Natural equivalence between `(Σ (a : composition n), composition a.length)` and
`(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i))`, that shows up as a
change of variables in the proof that composition of formal multilinear series is associative.
Consider a composition `a` of `n` and a composition `b` of `a.length`. Then `b` indicates how to
group together some blocks of `a`, giving altogether `b.length` blocks of blocks. These blocks of
blocks can be called `d₀, ..., d_{a.length - 1}`, and one obtains a composition `c` of `n` by
saying that each `dᵢ` is one single block. The map `⟨a, b⟩ → ⟨c, (d₀, ..., d_{a.length - 1})⟩` is
the direct map in the equiv.
Conversely, if one starts from `c` and the `dᵢ`s, one can join the `dᵢ`s to obtain a composition
`a` of `n`, and register the lengths of the `dᵢ`s in a composition `b` of `a.length`. This is the
inverse map of the equiv.
-/
def sigma_equiv_sigma_pi (n : ℕ) :
(Σ (a : composition n), composition a.length) ≃
(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) :=
{ to_fun := λ i, ⟨i.1.gather i.2, i.1.sigma_composition_aux i.2⟩,
inv_fun := λ i, ⟨
{ blocks := (of_fn (λ j, (i.2 j).blocks)).join,
blocks_pos :=
begin
simp only [and_imp, list.mem_join, exists_imp_distrib, forall_mem_of_fn_iff],
exact λ i j hj, composition.blocks_pos _ hj
end,
blocks_sum := by simp [sum_of_fn, composition.blocks_sum, composition.sum_blocks_fun] },
{ blocks := of_fn (λ j, (i.2 j).length),
blocks_pos := forall_mem_of_fn_iff.2
(λ j, composition.length_pos_of_pos _ (composition.blocks_pos' _ _ _)),
blocks_sum := by { dsimp only [composition.length], simp [sum_of_fn] } }⟩,
left_inv :=
begin
-- the fact that we have a left inverse is essentially `join_split_wrt_composition`,
-- but we need to massage it to take care of the dependent setting.
rintros ⟨a, b⟩,
rw sigma_composition_eq_iff,
dsimp,
split,
{ have A := length_map list.sum (split_wrt_composition a.blocks b),
conv_rhs { rw [← join_split_wrt_composition a.blocks b,
← of_fn_nth_le (split_wrt_composition a.blocks b)] },
congr,
{ exact A },
{ exact (fin.heq_fun_iff A).2 (λ i, rfl) } },
{ have B : composition.length (composition.gather a b) = list.length b.blocks :=
composition.length_gather _ _,
conv_rhs { rw [← of_fn_nth_le b.blocks] },
congr' 1,
apply (fin.heq_fun_iff B).2 (λ i, _),
rw [sigma_composition_aux, composition.length, nth_le_map_rev list.length,
nth_le_of_eq (map_length_split_wrt_composition _ _)], refl }
end,
right_inv :=
begin
-- the fact that we have a right inverse is essentially `split_wrt_composition_join`,
-- but we need to massage it to take care of the dependent setting.
rintros ⟨c, d⟩,
have : map list.sum (of_fn (λ (i : fin (composition.length c)), (d i).blocks)) = c.blocks,
by simp [map_of_fn, (∘), composition.blocks_sum, composition.of_fn_blocks_fun],
rw sigma_pi_composition_eq_iff,
dsimp,
congr,
{ ext1,
dsimp [composition.gather],
rwa split_wrt_composition_join,
simp only [map_of_fn] },
{ rw fin.heq_fun_iff,
{ assume i,
dsimp [composition.sigma_composition_aux],
rw [nth_le_of_eq (split_wrt_composition_join _ _ _)],
{ simp only [nth_le_of_fn'] },
{ simp only [map_of_fn] } },
{ congr,
ext1,
dsimp [composition.gather],
rwa split_wrt_composition_join,
simp only [map_of_fn] } }
end }
end composition
namespace formal_multilinear_series
open composition
theorem comp_assoc (r : formal_multilinear_series 𝕜 G H) (q : formal_multilinear_series 𝕜 F G)
(p : formal_multilinear_series 𝕜 E F) :
(r.comp q).comp p = r.comp (q.comp p) :=
begin
ext n v,
/- First, rewrite the two compositions appearing in the theorem as two sums over complicated
sigma types, as in the description of the proof above. -/
let f : (Σ (a : composition n), composition a.length) → H :=
λ c, r c.2.length (apply_composition q c.2 (apply_composition p c.1 v)),
let g : (Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) → H :=
λ c, r c.1.length (λ (i : fin c.1.length),
q (c.2 i).length (apply_composition p (c.2 i) (v ∘ c.1.embedding i))),
suffices : ∑ c, f c = ∑ c, g c,
by simpa only [formal_multilinear_series.comp, continuous_multilinear_map.sum_apply,
comp_along_composition_apply, continuous_multilinear_map.map_sum, finset.sum_sigma',
apply_composition],
/- Now, we use `composition.sigma_equiv_sigma_pi n` to change
variables in the second sum, and check that we get exactly the same sums. -/
rw ← (sigma_equiv_sigma_pi n).sum_comp,
/- To check that we have the same terms, we should check that we apply the same component of
`r`, and the same component of `q`, and the same component of `p`, to the same coordinate of
`v`. This is true by definition, but at each step one needs to convince Lean that the types
one considers are the same, using a suitable congruence lemma to avoid dependent type issues.
This dance has to be done three times, one for `r`, one for `q` and one for `p`.-/
apply finset.sum_congr rfl,
rintros ⟨a, b⟩ _,
dsimp [f, g, sigma_equiv_sigma_pi],
-- check that the `r` components are the same. Based on `composition.length_gather`
apply r.congr (composition.length_gather a b).symm,
intros i hi1 hi2,
-- check that the `q` components are the same. Based on `length_sigma_composition_aux`
apply q.congr (length_sigma_composition_aux a b _).symm,
intros j hj1 hj2,
-- check that the `p` components are the same. Based on `blocks_fun_sigma_composition_aux`
apply p.congr (blocks_fun_sigma_composition_aux a b _ _).symm,
intros k hk1 hk2,
-- finally, check that the coordinates of `v` one is using are the same. Based on
-- `size_up_to_size_up_to_add`.
refine congr_arg v (fin.eq_of_veq _),
dsimp [composition.embedding],
rw [size_up_to_size_up_to_add _ _ hi1 hj1, add_assoc],
end
end formal_multilinear_series
|
0cd42814a862f0deb4328086e5061e4a824cc03d
|
94e33a31faa76775069b071adea97e86e218a8ee
|
/src/field_theory/finite/trace.lean
|
1212063d27aa6ab5b8c2eb87f8e14b1291afeb28
|
[
"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
| 939
|
lean
|
/-
Copyright (c) 2022 Michael Stoll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Stoll
-/
import ring_theory.trace
import field_theory.finite.basic
import field_theory.finite.galois_field
/-!
# The trace map for finite fields
We state the fact that the trace map from a finite field of
characteristic `p` to `zmod p` is nondegenerate.
## Tags
finite field, trace
-/
namespace finite_field
/-- The trace map from a finite field to its prime field is nongedenerate. -/
lemma trace_to_zmod_nondegenerate (F : Type*) [field F] [fintype F] {a : F}
(ha : a ≠ 0) : ∃ b : F, algebra.trace (zmod (ring_char F)) F (a * b) ≠ 0 :=
begin
haveI : fact (ring_char F).prime := ⟨char_p.char_is_prime F _⟩,
have htr := trace_form_nondegenerate (zmod (ring_char F)) F a,
simp_rw [algebra.trace_form_apply] at htr,
by_contra' hf,
exact ha (htr hf),
end
end finite_field
|
546f535f11f3ac60fcd8f73352cb0bda08dc6421
|
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
|
/src/analysis/calculus/deriv.lean
|
5a94667b590eafc87c20d7401409cbce3a546d14
|
[
"Apache-2.0"
] |
permissive
|
kmill/mathlib
|
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
|
1a419a9fea7b959317eddd556e1bb9639f4dcc05
|
refs/heads/master
| 1,668,578,197,719
| 1,593,629,163,000
| 1,593,629,163,000
| 276,482,939
| 0
| 0
| null | 1,593,637,960,000
| 1,593,637,959,000
| null |
UTF-8
|
Lean
| false
| false
| 69,536
|
lean
|
/-
Copyright (c) 2019 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Sébastien Gouëzel
-/
import analysis.calculus.fderiv
import data.polynomial
/-!
# One-dimensional derivatives
This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a
normed field and `F` is a normed space over this field. The derivative of
such a function `f` at a point `x` is given by an element `f' : F`.
The theory is developed analogously to the [Fréchet
derivatives](./fderiv.lean). We first introduce predicates defined in terms
of the corresponding predicates for Fréchet derivatives:
- `has_deriv_at_filter f f' x L` states that the function `f` has the
derivative `f'` at the point `x` as `x` goes along the filter `L`.
- `has_deriv_within_at f f' s x` states that the function `f` has the
derivative `f'` at the point `x` within the subset `s`.
- `has_deriv_at f f' x` states that the function `f` has the derivative `f'`
at the point `x`.
- `has_strict_deriv_at f f' x` states that the function `f` has the derivative `f'`
at the point `x` in the sense of strict differentiability, i.e.,
`f y - f z = (y - z) • f' + o (y - z)` as `y, z → x`.
For the last two notions we also define a functional version:
- `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the
derivative does not exist, then `deriv_within f s x` equals zero.
- `deriv f x` is a derivative of `f` at `x`. If the derivative does not
exist, then `deriv f x` equals zero.
The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the
one-dimensional derivatives coincide with the general Fréchet derivatives.
We also show the existence and compute the derivatives of:
- constants
- the identity function
- linear maps
- addition
- sum of finitely many functions
- negation
- subtraction
- multiplication
- inverse `x → x⁻¹`
- multiplication of two functions in `𝕜 → 𝕜`
- multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E`
- composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜`
- composition of a function in `F → E` with a function in `𝕜 → F`
- inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`)
- division
- polynomials
For most binary operations we also define `const_op` and `op_const` theorems for the cases when
the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier,
and they more frequently lead to the desired result.
We set up the simplifier so that it can compute the derivative of simple functions. For instance,
```lean
example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) :=
by { simp, ring }
```
## Implementation notes
Most of the theorems are direct restatements of the corresponding theorems
for Fréchet derivatives.
The strategy to construct simp lemmas that give the simplifier the possibility to compute
derivatives is the same as the one for differentiability statements, as explained in `fderiv.lean`.
See the explanations there.
-/
universes u v w
noncomputable theory
open_locale classical topological_space big_operators filter
open filter asymptotics set
open continuous_linear_map (smul_right smul_right_one_eq_iff)
variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜]
section
variables {F : Type v} [normed_group F] [normed_space 𝕜 F]
variables {E : Type w} [normed_group E] [normed_space 𝕜 E]
/--
`f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`.
That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`.
-/
def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) :=
has_fderiv_at_filter f (smul_right 1 f' : 𝕜 →L[𝕜] F) x L
/--
`f` has the derivative `f'` at the point `x` within the subset `s`.
That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`.
-/
def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) :=
has_deriv_at_filter f f' x (nhds_within x s)
/--
`f` has the derivative `f'` at the point `x`.
That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`.
-/
def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) :=
has_deriv_at_filter f f' x (𝓝 x)
/-- `f` has the derivative `f'` at the point `x` in the sense of strict differentiability.
That is, `f y - f z = (y - z) • f' + o(y - z)` as `y, z → x`. -/
def has_strict_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) :=
has_strict_fderiv_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) x
/--
Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise.
If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then
`f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`.
-/
def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) :=
(fderiv_within 𝕜 f s x : 𝕜 →L[𝕜] F) 1
/--
Derivative of `f` at the point `x`, if it exists. Zero otherwise.
If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then
`f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`.
-/
def deriv (f : 𝕜 → F) (x : 𝕜) :=
(fderiv 𝕜 f x : 𝕜 →L[𝕜] F) 1
variables {f f₀ f₁ g : 𝕜 → F}
variables {f' f₀' f₁' g' : F}
variables {x : 𝕜}
variables {s t : set 𝕜}
variables {L L₁ L₂ : filter 𝕜}
/-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/
lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L :=
by simp [has_deriv_at_filter]
lemma has_fderiv_at_filter.has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at_filter f f' x L → has_deriv_at_filter f (f' 1) x L :=
has_fderiv_at_filter_iff_has_deriv_at_filter.mp
/-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/
lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x :=
has_fderiv_at_filter_iff_has_deriv_at_filter
/-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/
lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} :
has_deriv_within_at f f' s x ↔
has_fderiv_within_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) s x :=
iff.rfl
lemma has_fderiv_within_at.has_deriv_within_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_within_at f f' s x → has_deriv_within_at f (f' 1) s x :=
has_fderiv_within_at_iff_has_deriv_within_at.mp
lemma has_deriv_within_at.has_fderiv_within_at {f' : F} :
has_deriv_within_at f f' s x → has_fderiv_within_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) s x :=
has_deriv_within_at_iff_has_fderiv_within_at.mp
/-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/
lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x :=
has_fderiv_at_filter_iff_has_deriv_at_filter
lemma has_fderiv_at.has_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at f f' x → has_deriv_at f (f' 1) x :=
has_fderiv_at_iff_has_deriv_at.mp
lemma has_strict_fderiv_at_iff_has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_strict_fderiv_at f f' x ↔ has_strict_deriv_at f (f' 1) x :=
by simp [has_strict_deriv_at, has_strict_fderiv_at]
protected lemma has_strict_fderiv_at.has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_strict_fderiv_at f f' x → has_strict_deriv_at f (f' 1) x :=
has_strict_fderiv_at_iff_has_strict_deriv_at.mp
/-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/
lemma has_deriv_at_iff_has_fderiv_at {f' : F} :
has_deriv_at f f' x ↔
has_fderiv_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) x :=
iff.rfl
lemma deriv_within_zero_of_not_differentiable_within_at
(h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 :=
by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption }
lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 :=
by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption }
theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x)
(h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' :=
smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁
theorem has_deriv_at_filter_iff_tendsto :
has_deriv_at_filter f f' x L ↔
tendsto (λ x' : 𝕜, ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) L (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (nhds_within x s) (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝 x) (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_strict_deriv_at.has_deriv_at (h : has_strict_deriv_at f f' x) :
has_deriv_at f f' x :=
h.has_fderiv_at
/-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical
definition with a limit. In this version we have to take the limit along the subset `-{x}`,
because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/
lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} :
has_deriv_at_filter f f' x L ↔
tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (L ⊓ 𝓟 {x}ᶜ) (𝓝 f') :=
begin
conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (normed_field.norm_inv _).symm,
(norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] },
conv_rhs { rw [← nhds_translation f', tendsto_comap_iff] },
refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _),
refine (eventually_principal.2 $ λ z hz, _).filter_mono inf_le_right,
simp only [(∘)],
rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 hz), one_smul]
end
lemma has_deriv_within_at_iff_tendsto_slope {x : 𝕜} {s : set 𝕜} :
has_deriv_within_at f f' s x ↔
tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x (s \ {x})) (𝓝 f') :=
begin
simp only [has_deriv_within_at, nhds_within, diff_eq, inf_assoc.symm, inf_principal.symm],
exact has_deriv_at_filter_iff_tendsto_slope
end
lemma has_deriv_within_at_iff_tendsto_slope' {x : 𝕜} {s : set 𝕜} (hs : x ∉ s) :
has_deriv_within_at f f' s x ↔
tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x s) (𝓝 f') :=
begin
convert ← has_deriv_within_at_iff_tendsto_slope,
exact diff_singleton_eq_self hs
end
lemma has_deriv_at_iff_tendsto_slope {x : 𝕜} :
has_deriv_at f f' x ↔
tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x {x}ᶜ) (𝓝 f') :=
has_deriv_at_filter_iff_tendsto_slope
theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔
is_o (λh, f (x + h) - f x - h • f') (λh, h) (𝓝 0) :=
has_fderiv_at_iff_is_o_nhds_zero
theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) :
has_deriv_at_filter f f' x L₁ :=
has_fderiv_at_filter.mono h hst
theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) :
has_deriv_within_at f f' s x :=
has_fderiv_within_at.mono h hst
theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) :
has_deriv_at_filter f f' x L :=
has_fderiv_at.has_fderiv_at_filter h hL
theorem has_deriv_at.has_deriv_within_at
(h : has_deriv_at f f' x) : has_deriv_within_at f f' s x :=
has_fderiv_at.has_fderiv_within_at h
lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) :
differentiable_within_at 𝕜 f s x :=
has_fderiv_within_at.differentiable_within_at h
lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x :=
has_fderiv_at.differentiable_at h
@[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x :=
has_fderiv_within_at_univ
theorem has_deriv_at_unique
(h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' :=
smul_right_one_eq_iff.mp $ has_fderiv_at_unique h₀ h₁
lemma has_deriv_within_at_inter' (h : t ∈ nhds_within x s) :
has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x :=
has_fderiv_within_at_inter' h
lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) :
has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x :=
has_fderiv_within_at_inter h
lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x) (ht : has_deriv_within_at f f' t x) :
has_deriv_within_at f f' (s ∪ t) x :=
begin
simp only [has_deriv_within_at, nhds_within_union],
exact hs.join ht,
end
lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x)
(ht : s ∈ nhds_within x t) : has_deriv_within_at f f' t x :=
(has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _))
lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) :
has_deriv_at f f' x :=
has_fderiv_within_at.has_fderiv_at h hs
lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) :
has_deriv_within_at f (deriv_within f s x) s x :=
show has_fderiv_within_at _ _ _ _, by { convert h.has_fderiv_within_at, simp [deriv_within] }
lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x :=
show has_fderiv_at _ _ _, by { convert h.has_fderiv_at, simp [deriv] }
lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' :=
has_deriv_at_unique h.differentiable_at.has_deriv_at h
lemma has_deriv_within_at.deriv_within
(h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within f s x = f' :=
hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h
lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x :=
rfl
lemma deriv_within_fderiv_within :
smul_right 1 (deriv_within f s x) = fderiv_within 𝕜 f s x :=
by simp [deriv_within]
lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x :=
rfl
lemma deriv_fderiv :
smul_right 1 (deriv f x) = fderiv 𝕜 f x :=
by simp [deriv]
lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x)
(hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x :=
by { unfold deriv_within deriv, rw h.fderiv_within hxs }
lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x)
(h : differentiable_within_at 𝕜 f t x) :
deriv_within f s x = deriv_within f t x :=
((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht
@[simp] lemma deriv_within_univ : deriv_within f univ = deriv f :=
by { ext, unfold deriv_within deriv, rw fderiv_within_univ }
lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) :
deriv_within f (s ∩ t) x = deriv_within f s x :=
by { unfold deriv_within, rw fderiv_within_inter ht hs }
section congr
/-! ### Congruence properties of derivatives -/
theorem has_deriv_at_filter_congr_of_mem_sets
(hx : f₀ x = f₁ x) (h₀ : ∀ᶠ x in L, f₀ x = f₁ x) (h₁ : f₀' = f₁') :
has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L :=
has_fderiv_at_filter_congr_of_mem_sets hx h₀ (by simp [h₁])
lemma has_deriv_at_filter.congr_of_mem_sets (h : has_deriv_at_filter f f' x L)
(hL : ∀ᶠ x in L, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L :=
by rwa has_deriv_at_filter_congr_of_mem_sets hx hL rfl
lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x)
(hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x :=
has_fderiv_within_at.congr_mono h ht hx h₁
lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x)
(hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x :=
h.congr_mono hs hx (subset.refl _)
lemma has_deriv_within_at.congr_of_mem_nhds_within (h : has_deriv_within_at f f' s x)
(h₁ : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x :=
has_deriv_at_filter.congr_of_mem_sets h h₁ hx
lemma has_deriv_at.congr_of_mem_nhds (h : has_deriv_at f f' x)
(h₁ : ∀ᶠ y in 𝓝 x, f₁ y = f y) : has_deriv_at f₁ f' x :=
has_deriv_at_filter.congr_of_mem_sets h h₁ (mem_of_nhds h₁ : _)
lemma deriv_within_congr_of_mem_nhds_within (hs : unique_diff_within_at 𝕜 s x)
(hL : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) :
deriv_within f₁ s x = deriv_within f s x :=
by { unfold deriv_within, rw fderiv_within_congr_of_mem_nhds_within hs hL hx }
lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x)
(hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) :
deriv_within f₁ s x = deriv_within f s x :=
by { unfold deriv_within, rw fderiv_within_congr hs hL hx }
lemma deriv_congr_of_mem_nhds (hL : ∀ᶠ y in 𝓝 x, f₁ y = f y) : deriv f₁ x = deriv f x :=
by { unfold deriv, rwa fderiv_congr_of_mem_nhds }
end congr
section id
/-! ### Derivative of the identity -/
variables (s x L)
theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L :=
(has_fderiv_at_filter_id x L).has_deriv_at_filter
theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x :=
has_deriv_at_filter_id _ _
theorem has_deriv_at_id : has_deriv_at id 1 x :=
has_deriv_at_filter_id _ _
theorem has_deriv_at_id' : has_deriv_at (λ (x : 𝕜), x) 1 x :=
has_deriv_at_filter_id _ _
theorem has_strict_deriv_at_id : has_strict_deriv_at id 1 x :=
(has_strict_fderiv_at_id x).has_strict_deriv_at
lemma deriv_id : deriv id x = 1 :=
has_deriv_at.deriv (has_deriv_at_id x)
@[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 :=
funext deriv_id
@[simp] lemma deriv_id'' : deriv (λ x : 𝕜, x) x = 1 :=
deriv_id x
lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 :=
(has_deriv_within_at_id x s).deriv_within hxs
end id
section const
/-! ### Derivative of constant functions -/
variables (c : F) (s x L)
theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L :=
(has_fderiv_at_filter_const c x L).has_deriv_at_filter
theorem has_strict_deriv_at_const : has_strict_deriv_at (λ x, c) 0 x :=
(has_strict_fderiv_at_const c x).has_strict_deriv_at
theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x :=
has_deriv_at_filter_const _ _ _
theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x :=
has_deriv_at_filter_const _ _ _
lemma deriv_const : deriv (λ x, c) x = 0 :=
has_deriv_at.deriv (has_deriv_at_const x c)
@[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 :=
funext (λ x, deriv_const x c)
lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 :=
(has_deriv_within_at_const _ _ _).deriv_within hxs
end const
section continuous_linear_map
/-! ### Derivative of continuous linear maps -/
variables (e : 𝕜 →L[𝕜] F)
lemma continuous_linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L :=
e.has_fderiv_at_filter.has_deriv_at_filter
lemma continuous_linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x :=
e.has_strict_fderiv_at.has_strict_deriv_at
lemma continuous_linear_map.has_deriv_at : has_deriv_at e (e 1) x :=
e.has_deriv_at_filter
lemma continuous_linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x :=
e.has_deriv_at_filter
@[simp] lemma continuous_linear_map.deriv : deriv e x = e 1 :=
e.has_deriv_at.deriv
lemma continuous_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within e s x = e 1 :=
e.has_deriv_within_at.deriv_within hxs
end continuous_linear_map
section linear_map
/-! ### Derivative of bundled linear maps -/
variables (e : 𝕜 →ₗ[𝕜] F)
lemma linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L :=
e.to_continuous_linear_map₁.has_deriv_at_filter
lemma linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x :=
e.to_continuous_linear_map₁.has_strict_deriv_at
lemma linear_map.has_deriv_at : has_deriv_at e (e 1) x :=
e.has_deriv_at_filter
lemma linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x :=
e.has_deriv_at_filter
@[simp] lemma linear_map.deriv : deriv e x = e 1 :=
e.has_deriv_at.deriv
lemma linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within e s x = e 1 :=
e.has_deriv_within_at.deriv_within hxs
end linear_map
section add
/-! ### Derivative of the sum of two functions -/
theorem has_deriv_at_filter.add
(hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) :
has_deriv_at_filter (λ y, f y + g y) (f' + g') x L :=
by simpa using (hf.add hg).has_deriv_at_filter
theorem has_strict_deriv_at.add
(hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) :
has_strict_deriv_at (λ y, f y + g y) (f' + g') x :=
by simpa using (hf.add hg).has_strict_deriv_at
theorem has_deriv_within_at.add
(hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) :
has_deriv_within_at (λ y, f y + g y) (f' + g') s x :=
hf.add hg
theorem has_deriv_at.add
(hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) :
has_deriv_at (λ x, f x + g x) (f' + g') x :=
hf.add hg
lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x :=
(hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs
@[simp] lemma deriv_add
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
deriv (λy, f y + g y) x = deriv f x + deriv g x :=
(hf.has_deriv_at.add hg.has_deriv_at).deriv
theorem has_deriv_at_filter.add_const
(hf : has_deriv_at_filter f f' x L) (c : F) :
has_deriv_at_filter (λ y, f y + c) f' x L :=
add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c)
theorem has_deriv_within_at.add_const
(hf : has_deriv_within_at f f' s x) (c : F) :
has_deriv_within_at (λ y, f y + c) f' s x :=
hf.add_const c
theorem has_deriv_at.add_const
(hf : has_deriv_at f f' x) (c : F) :
has_deriv_at (λ x, f x + c) f' x :=
hf.add_const c
lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (c : F) :
deriv_within (λy, f y + c) s x = deriv_within f s x :=
(hf.has_deriv_within_at.add_const c).deriv_within hxs
lemma deriv_add_const (hf : differentiable_at 𝕜 f x) (c : F) :
deriv (λy, f y + c) x = deriv f x :=
(hf.has_deriv_at.add_const c).deriv
theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ y, c + f y) f' x L :=
zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf
theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ y, c + f y) f' s x :=
hf.const_add c
theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, c + f x) f' x :=
hf.const_add c
lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x)
(c : F) (hf : differentiable_within_at 𝕜 f s x) :
deriv_within (λy, c + f y) s x = deriv_within f s x :=
(hf.has_deriv_within_at.const_add c).deriv_within hxs
lemma deriv_const_add (c : F) (hf : differentiable_at 𝕜 f x) :
deriv (λy, c + f y) x = deriv f x :=
(hf.has_deriv_at.const_add c).deriv
end add
section sum
/-! ### Derivative of a finite sum of functions -/
open_locale big_operators
variables {ι : Type*} {u : finset ι} {A : ι → (𝕜 → F)} {A' : ι → F}
theorem has_deriv_at_filter.sum (h : ∀ i ∈ u, has_deriv_at_filter (A i) (A' i) x L) :
has_deriv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L :=
by simpa [continuous_linear_map.sum_apply] using (has_fderiv_at_filter.sum h).has_deriv_at_filter
theorem has_strict_deriv_at.sum (h : ∀ i ∈ u, has_strict_deriv_at (A i) (A' i) x) :
has_strict_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x :=
by simpa [continuous_linear_map.sum_apply] using (has_strict_fderiv_at.sum h).has_strict_deriv_at
theorem has_deriv_within_at.sum (h : ∀ i ∈ u, has_deriv_within_at (A i) (A' i) s x) :
has_deriv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x :=
has_deriv_at_filter.sum h
theorem has_deriv_at.sum (h : ∀ i ∈ u, has_deriv_at (A i) (A' i) x) :
has_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x :=
has_deriv_at_filter.sum h
lemma deriv_within_sum (hxs : unique_diff_within_at 𝕜 s x)
(h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) :
deriv_within (λ y, ∑ i in u, A i y) s x = ∑ i in u, deriv_within (A i) s x :=
(has_deriv_within_at.sum (λ i hi, (h i hi).has_deriv_within_at)).deriv_within hxs
@[simp] lemma deriv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) :
deriv (λ y, ∑ i in u, A i y) x = ∑ i in u, deriv (A i) x :=
(has_deriv_at.sum (λ i hi, (h i hi).has_deriv_at)).deriv
end sum
section mul_vector
/-! ### Derivative of the multiplication of a scalar function and a vector function -/
variables {c : 𝕜 → 𝕜} {c' : 𝕜}
theorem has_deriv_within_at.smul
(hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x :=
by simpa using (has_fderiv_within_at.smul hc hf).has_deriv_within_at
theorem has_deriv_at.smul
(hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) :
has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.smul hf
end
theorem has_strict_deriv_at.smul
(hc : has_strict_deriv_at c c' x) (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x :=
by simpa using (hc.smul hf).has_strict_deriv_at
lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) :
deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x :=
(hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs
lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) :
deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x :=
(hc.has_deriv_at.smul hf.has_deriv_at).deriv
theorem has_deriv_within_at.smul_const
(hc : has_deriv_within_at c c' s x) (f : F) :
has_deriv_within_at (λ y, c y • f) (c' • f) s x :=
begin
have := hc.smul (has_deriv_within_at_const x s f),
rwa [smul_zero, zero_add] at this
end
theorem has_deriv_at.smul_const
(hc : has_deriv_at c c' x) (f : F) :
has_deriv_at (λ y, c y • f) (c' • f) x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.smul_const f
end
lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (f : F) :
deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f :=
(hc.has_deriv_within_at.smul_const f).deriv_within hxs
lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) :
deriv (λ y, c y • f) x = (deriv c x) • f :=
(hc.has_deriv_at.smul_const f).deriv
theorem has_deriv_within_at.const_smul
(c : 𝕜) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ y, c • f y) (c • f') s x :=
begin
convert (has_deriv_within_at_const x s c).smul hf,
rw [zero_smul, add_zero]
end
theorem has_deriv_at.const_smul (c : 𝕜) (hf : has_deriv_at f f' x) :
has_deriv_at (λ y, c • f y) (c • f') x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hf.const_smul c
end
lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x)
(c : 𝕜) (hf : differentiable_within_at 𝕜 f s x) :
deriv_within (λ y, c • f y) s x = c • deriv_within f s x :=
(hf.has_deriv_within_at.const_smul c).deriv_within hxs
lemma deriv_const_smul (c : 𝕜) (hf : differentiable_at 𝕜 f x) :
deriv (λ y, c • f y) x = c • deriv f x :=
(hf.has_deriv_at.const_smul c).deriv
end mul_vector
section neg
/-! ### Derivative of the negative of a function -/
theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ x, -f x) (-f') x L :=
by simpa using h.neg.has_deriv_at_filter
theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, -f x) (-f') s x :=
h.neg
theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x :=
h.neg
theorem has_strict_deriv_at.neg (h : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, -f x) (-f') x :=
by simpa using h.neg.has_strict_deriv_at
lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x)
(h : differentiable_within_at 𝕜 f s x) :
deriv_within (λy, -f y) s x = - deriv_within f s x :=
h.has_deriv_within_at.neg.deriv_within hxs
lemma deriv_neg : deriv (λy, -f y) x = - deriv f x :=
if h : differentiable_at 𝕜 f x then h.has_deriv_at.neg.deriv else
have ¬differentiable_at 𝕜 (λ y, -f y) x, from λ h', by simpa only [neg_neg] using h'.neg,
by simp only [deriv_zero_of_not_differentiable_at h,
deriv_zero_of_not_differentiable_at this, neg_zero]
@[simp] lemma deriv_neg' : deriv (λy, -f y) = (λ x, - deriv f x) :=
funext $ λ x, deriv_neg
end neg
section sub
/-! ### Derivative of the difference of two functions -/
theorem has_deriv_at_filter.sub
(hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) :
has_deriv_at_filter (λ x, f x - g x) (f' - g') x L :=
hf.add hg.neg
theorem has_deriv_within_at.sub
(hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) :
has_deriv_within_at (λ x, f x - g x) (f' - g') s x :=
hf.sub hg
theorem has_deriv_at.sub
(hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) :
has_deriv_at (λ x, f x - g x) (f' - g') x :=
hf.sub hg
theorem has_strict_deriv_at.sub
(hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) :
has_strict_deriv_at (λ x, f x - g x) (f' - g') x :=
hf.add hg.neg
lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x :=
(hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs
@[simp] lemma deriv_sub
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
deriv (λ y, f y - g y) x = deriv f x - deriv g x :=
(hf.has_deriv_at.sub hg.has_deriv_at).deriv
theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) :
is_O (λ x', f x' - f x) (λ x', x' - x) L :=
has_fderiv_at_filter.is_O_sub h
theorem has_deriv_at_filter.sub_const
(hf : has_deriv_at_filter f f' x L) (c : F) :
has_deriv_at_filter (λ x, f x - c) f' x L :=
hf.add_const (-c)
theorem has_deriv_within_at.sub_const
(hf : has_deriv_within_at f f' s x) (c : F) :
has_deriv_within_at (λ x, f x - c) f' s x :=
hf.sub_const c
theorem has_deriv_at.sub_const
(hf : has_deriv_at f f' x) (c : F) :
has_deriv_at (λ x, f x - c) f' x :=
hf.sub_const c
lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (c : F) :
deriv_within (λy, f y - c) s x = deriv_within f s x :=
(hf.has_deriv_within_at.sub_const c).deriv_within hxs
lemma deriv_sub_const (c : F) (hf : differentiable_at 𝕜 f x) :
deriv (λ y, f y - c) x = deriv f x :=
(hf.has_deriv_at.sub_const c).deriv
theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ x, c - f x) (-f') x L :=
hf.neg.const_add c
theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, c - f x) (-f') s x :=
hf.const_sub c
theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, c - f x) (-f') x :=
hf.const_sub c
lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x)
(c : F) (hf : differentiable_within_at 𝕜 f s x) :
deriv_within (λy, c - f y) s x = -deriv_within f s x :=
(hf.has_deriv_within_at.const_sub c).deriv_within hxs
lemma deriv_const_sub (c : F) (hf : differentiable_at 𝕜 f x) :
deriv (λ y, c - f y) x = -deriv f x :=
(hf.has_deriv_at.const_sub c).deriv
end sub
section continuous
/-! ### Continuity of a function admitting a derivative -/
theorem has_deriv_at_filter.tendsto_nhds
(hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) :
tendsto f L (𝓝 (f x)) :=
h.tendsto_nhds hL
theorem has_deriv_within_at.continuous_within_at
(h : has_deriv_within_at f f' s x) : continuous_within_at f s x :=
has_deriv_at_filter.tendsto_nhds inf_le_left h
theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x :=
has_deriv_at_filter.tendsto_nhds (le_refl _) h
end continuous
section cartesian_product
/-! ### Derivative of the cartesian product of two functions -/
variables {G : Type w} [normed_group G] [normed_space 𝕜 G]
variables {f₂ : 𝕜 → G} {f₂' : G}
lemma has_deriv_at_filter.prod
(hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) :
has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L :=
show has_fderiv_at_filter _ _ _ _,
by convert has_fderiv_at_filter.prod hf₁ hf₂
lemma has_deriv_within_at.prod
(hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) :
has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x :=
hf₁.prod hf₂
lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) :
has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x :=
hf₁.prod hf₂
end cartesian_product
section composition
/-!
### Derivative of the composition of a vector function and a scalar function
We use `scomp` in lemmas on composition of vector valued and scalar valued functions, and `comp`
in lemmas on composition of scalar valued functions, in analogy for `smul` and `mul` (and also
because the `comp` version with the shorter name will show up much more often in applications).
The formula for the derivative involves `smul` in `scomp` lemmas, which can be reduced to
usual multiplication in `comp` lemmas.
-/
variables {h h₁ h₂ : 𝕜 → 𝕜} {h' h₁' h₂' : 𝕜}
/- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to
get confused since there are too many possibilities for composition -/
variable (x)
theorem has_deriv_at_filter.scomp
(hg : has_deriv_at_filter g g' (h x) (L.map h))
(hh : has_deriv_at_filter h h' x L) :
has_deriv_at_filter (g ∘ h) (h' • g') x L :=
by simpa using (hg.comp x hh).has_deriv_at_filter
theorem has_deriv_within_at.scomp {t : set 𝕜}
(hg : has_deriv_within_at g g' t (h x))
(hh : has_deriv_within_at h h' s x) (hst : s ⊆ h ⁻¹' t) :
has_deriv_within_at (g ∘ h) (h' • g') s x :=
begin
apply has_deriv_at_filter.scomp _ (has_deriv_at_filter.mono hg _) hh,
calc map h (nhds_within x s)
≤ nhds_within (h x) (h '' s) : hh.continuous_within_at.tendsto_nhds_within_image
... ≤ nhds_within (h x) t : nhds_within_mono _ (image_subset_iff.mpr hst)
end
/-- The chain rule. -/
theorem has_deriv_at.scomp
(hg : has_deriv_at g g' (h x)) (hh : has_deriv_at h h' x) :
has_deriv_at (g ∘ h) (h' • g') x :=
(hg.mono hh.continuous_at).scomp x hh
theorem has_strict_deriv_at.scomp
(hg : has_strict_deriv_at g g' (h x)) (hh : has_strict_deriv_at h h' x) :
has_strict_deriv_at (g ∘ h) (h' • g') x :=
by simpa using (hg.comp x hh).has_strict_deriv_at
theorem has_deriv_at.scomp_has_deriv_within_at
(hg : has_deriv_at g g' (h x)) (hh : has_deriv_within_at h h' s x) :
has_deriv_within_at (g ∘ h) (h' • g') s x :=
begin
rw ← has_deriv_within_at_univ at hg,
exact has_deriv_within_at.scomp x hg hh subset_preimage_univ
end
lemma deriv_within.scomp
(hg : differentiable_within_at 𝕜 g t (h x)) (hh : differentiable_within_at 𝕜 h s x)
(hs : s ⊆ h ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (g ∘ h) s x = deriv_within h s x • deriv_within g t (h x) :=
begin
apply has_deriv_within_at.deriv_within _ hxs,
exact has_deriv_within_at.scomp x (hg.has_deriv_within_at) (hh.has_deriv_within_at) hs
end
lemma deriv.scomp
(hg : differentiable_at 𝕜 g (h x)) (hh : differentiable_at 𝕜 h x) :
deriv (g ∘ h) x = deriv h x • deriv g (h x) :=
begin
apply has_deriv_at.deriv,
exact has_deriv_at.scomp x hg.has_deriv_at hh.has_deriv_at
end
/-! ### Derivative of the composition of two scalar functions -/
theorem has_deriv_at_filter.comp
(hh₁ : has_deriv_at_filter h₁ h₁' (h₂ x) (L.map h₂))
(hh₂ : has_deriv_at_filter h₂ h₂' x L) :
has_deriv_at_filter (h₁ ∘ h₂) (h₁' * h₂') x L :=
by { rw mul_comm, exact hh₁.scomp x hh₂ }
theorem has_deriv_within_at.comp {t : set 𝕜}
(hh₁ : has_deriv_within_at h₁ h₁' t (h₂ x))
(hh₂ : has_deriv_within_at h₂ h₂' s x) (hst : s ⊆ h₂ ⁻¹' t) :
has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x :=
by { rw mul_comm, exact hh₁.scomp x hh₂ hst, }
/-- The chain rule. -/
theorem has_deriv_at.comp
(hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_at h₂ h₂' x) :
has_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x :=
(hh₁.mono hh₂.continuous_at).comp x hh₂
theorem has_strict_deriv_at.comp
(hh₁ : has_strict_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_strict_deriv_at h₂ h₂' x) :
has_strict_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x :=
by { rw mul_comm, exact hh₁.scomp x hh₂ }
theorem has_deriv_at.comp_has_deriv_within_at
(hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) :
has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x :=
begin
rw ← has_deriv_within_at_univ at hh₁,
exact has_deriv_within_at.comp x hh₁ hh₂ subset_preimage_univ
end
lemma deriv_within.comp
(hh₁ : differentiable_within_at 𝕜 h₁ t (h₂ x)) (hh₂ : differentiable_within_at 𝕜 h₂ s x)
(hs : s ⊆ h₂ ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (h₁ ∘ h₂) s x = deriv_within h₁ t (h₂ x) * deriv_within h₂ s x :=
begin
apply has_deriv_within_at.deriv_within _ hxs,
exact has_deriv_within_at.comp x (hh₁.has_deriv_within_at) (hh₂.has_deriv_within_at) hs
end
lemma deriv.comp
(hh₁ : differentiable_at 𝕜 h₁ (h₂ x)) (hh₂ : differentiable_at 𝕜 h₂ x) :
deriv (h₁ ∘ h₂) x = deriv h₁ (h₂ x) * deriv h₂ x :=
begin
apply has_deriv_at.deriv,
exact has_deriv_at.comp x hh₁.has_deriv_at hh₂.has_deriv_at
end
protected lemma has_deriv_at_filter.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_deriv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) :
has_deriv_at_filter (f^[n]) (f'^n) x L :=
begin
have := hf.iterate hL hx n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
protected lemma has_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_deriv_at f f' x) (hx : f x = x) (n : ℕ) :
has_deriv_at (f^[n]) (f'^n) x :=
begin
have := has_fderiv_at.iterate hf hx n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
protected lemma has_deriv_within_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_deriv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) :
has_deriv_within_at (f^[n]) (f'^n) s x :=
begin
have := has_fderiv_within_at.iterate hf hx hs n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
protected lemma has_strict_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_strict_deriv_at f f' x) (hx : f x = x) (n : ℕ) :
has_strict_deriv_at (f^[n]) (f'^n) x :=
begin
have := hf.iterate hx n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
end composition
section composition_vector
/-! ### Derivative of the composition of a function between vector spaces and of a function defined on `𝕜` -/
variables {l : F → E} {l' : F →L[𝕜] E}
variable (x)
/-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set
equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/
theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F}
(hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) :
has_deriv_within_at (l ∘ f) (l' (f')) s x :=
begin
rw has_deriv_within_at_iff_has_fderiv_within_at,
convert has_fderiv_within_at.comp x hl hf hst,
ext,
simp
end
/-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the
Fréchet derivative of `l` applied to the derivative of `f`. -/
theorem has_fderiv_at.comp_has_deriv_at
(hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) :
has_deriv_at (l ∘ f) (l' (f')) x :=
begin
rw has_deriv_at_iff_has_fderiv_at,
convert has_fderiv_at.comp x hl hf,
ext,
simp
end
theorem has_fderiv_at.comp_has_deriv_within_at
(hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (l ∘ f) (l' (f')) s x :=
begin
rw ← has_fderiv_within_at_univ at hl,
exact has_fderiv_within_at.comp_has_deriv_within_at x hl hf subset_preimage_univ
end
lemma fderiv_within.comp_deriv_within {t : set F}
(hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x)
(hs : s ⊆ f ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) :=
begin
apply has_deriv_within_at.deriv_within _ hxs,
exact (hl.has_fderiv_within_at).comp_has_deriv_within_at x (hf.has_deriv_within_at) hs
end
lemma fderiv.comp_deriv
(hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) :
deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) :=
begin
apply has_deriv_at.deriv _,
exact (hl.has_fderiv_at).comp_has_deriv_at x (hf.has_deriv_at)
end
end composition_vector
section mul
/-! ### Derivative of the multiplication of two scalar functions -/
variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜}
theorem has_deriv_within_at.mul
(hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) :
has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x :=
begin
convert hc.smul hd using 1,
rw [smul_eq_mul, smul_eq_mul, add_comm]
end
theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) :
has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.mul hd
end
theorem has_strict_deriv_at.mul
(hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) :
has_strict_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x :=
begin
convert hc.smul hd using 1,
rw [smul_eq_mul, smul_eq_mul, add_comm]
end
lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) :
deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x :=
(hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs
@[simp] lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) :
deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x :=
(hc.has_deriv_at.mul hd.has_deriv_at).deriv
theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝕜) :
has_deriv_within_at (λ y, c y * d) (c' * d) s x :=
begin
convert hc.mul (has_deriv_within_at_const x s d),
rw [mul_zero, add_zero]
end
theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝕜) :
has_deriv_at (λ y, c y * d) (c' * d) x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.mul_const d
end
lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) :
deriv_within (λ y, c y * d) s x = deriv_within c s x * d :=
(hc.has_deriv_within_at.mul_const d).deriv_within hxs
lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) :
deriv (λ y, c y * d) x = deriv c x * d :=
(hc.has_deriv_at.mul_const d).deriv
theorem has_deriv_within_at.const_mul (c : 𝕜) (hd : has_deriv_within_at d d' s x) :
has_deriv_within_at (λ y, c * d y) (c * d') s x :=
begin
convert (has_deriv_within_at_const x s c).mul hd,
rw [zero_mul, zero_add]
end
theorem has_deriv_at.const_mul (c : 𝕜) (hd : has_deriv_at d d' x) :
has_deriv_at (λ y, c * d y) (c * d') x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hd.const_mul c
end
lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x)
(c : 𝕜) (hd : differentiable_within_at 𝕜 d s x) :
deriv_within (λ y, c * d y) s x = c * deriv_within d s x :=
(hd.has_deriv_within_at.const_mul c).deriv_within hxs
lemma deriv_const_mul (c : 𝕜) (hd : differentiable_at 𝕜 d x) :
deriv (λ y, c * d y) x = c * deriv d x :=
(hd.has_deriv_at.const_mul c).deriv
end mul
section inverse
/-! ### Derivative of `x ↦ x⁻¹` -/
theorem has_strict_deriv_at_inv (hx : x ≠ 0) : has_strict_deriv_at has_inv.inv (-(x^2)⁻¹) x :=
begin
suffices : is_o (λ p : 𝕜 × 𝕜, (p.1 - p.2) * ((x * x)⁻¹ - (p.1 * p.2)⁻¹))
(λ (p : 𝕜 × 𝕜), (p.1 - p.2) * 1) (𝓝 (x, x)),
{ refine this.congr' _ (eventually_of_forall _ $ λ _, mul_one _),
refine eventually.mono (mem_nhds_sets (is_open_prod is_open_ne is_open_ne) ⟨hx, hx⟩) _,
rintro ⟨y, z⟩ ⟨hy, hz⟩,
simp only [mem_set_of_eq] at hy hz, -- hy : y ≠ 0, hz : z ≠ 0
field_simp [hx, hy, hz], ring, },
refine (is_O_refl (λ p : 𝕜 × 𝕜, p.1 - p.2) _).mul_is_o ((is_o_one_iff _).2 _),
rw [← sub_self (x * x)⁻¹],
exact tendsto_const_nhds.sub ((continuous_mul.tendsto (x, x)).inv' $ mul_ne_zero hx hx)
end
theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) :
has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x :=
(has_strict_deriv_at_inv x_ne_zero).has_deriv_at
theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) :
has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x :=
(has_deriv_at_inv x_ne_zero).has_deriv_within_at
lemma differentiable_at_inv (x_ne_zero : x ≠ 0) :
differentiable_at 𝕜 (λx, x⁻¹) x :=
(has_deriv_at_inv x_ne_zero).differentiable_at
lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) :
differentiable_within_at 𝕜 (λx, x⁻¹) s x :=
(differentiable_at_inv x_ne_zero).differentiable_within_at
lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} :=
λx hx, differentiable_within_at_inv hx
lemma deriv_inv (x_ne_zero : x ≠ 0) :
deriv (λx, x⁻¹) x = -(x^2)⁻¹ :=
(has_deriv_at_inv x_ne_zero).deriv
lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ :=
begin
rw differentiable_at.deriv_within (differentiable_at_inv x_ne_zero) hxs,
exact deriv_inv x_ne_zero
end
lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) :
has_fderiv_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x :=
has_deriv_at_inv x_ne_zero
lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) :
has_fderiv_within_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x :=
(has_fderiv_at_inv x_ne_zero).has_fderiv_within_at
lemma fderiv_inv (x_ne_zero : x ≠ 0) :
fderiv 𝕜 (λx, x⁻¹) x = smul_right 1 (-(x^2)⁻¹) :=
(has_fderiv_at_inv x_ne_zero).fderiv
lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right 1 (-(x^2)⁻¹) :=
begin
rw differentiable_at.fderiv_within (differentiable_at_inv x_ne_zero) hxs,
exact fderiv_inv x_ne_zero
end
variables {c : 𝕜 → 𝕜} {c' : 𝕜}
lemma has_deriv_within_at.inv
(hc : has_deriv_within_at c c' s x) (hx : c x ≠ 0) :
has_deriv_within_at (λ y, (c y)⁻¹) (- c' / (c x)^2) s x :=
begin
convert (has_deriv_at_inv hx).comp_has_deriv_within_at x hc,
field_simp
end
lemma has_deriv_at.inv (hc : has_deriv_at c c' x) (hx : c x ≠ 0) :
has_deriv_at (λ y, (c y)⁻¹) (- c' / (c x)^2) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hc.inv hx
end
lemma differentiable_within_at.inv (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) :
differentiable_within_at 𝕜 (λx, (c x)⁻¹) s x :=
(hc.has_deriv_within_at.inv hx).differentiable_within_at
@[simp] lemma differentiable_at.inv (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) :
differentiable_at 𝕜 (λx, (c x)⁻¹) x :=
(hc.has_deriv_at.inv hx).differentiable_at
lemma differentiable_on.inv (hc : differentiable_on 𝕜 c s) (hx : ∀ x ∈ s, c x ≠ 0) :
differentiable_on 𝕜 (λx, (c x)⁻¹) s :=
λx h, (hc x h).inv (hx x h)
@[simp] lemma differentiable.inv (hc : differentiable 𝕜 c) (hx : ∀ x, c x ≠ 0) :
differentiable 𝕜 (λx, (c x)⁻¹) :=
λx, (hc x).inv (hx x)
lemma deriv_within_inv' (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0)
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, (c x)⁻¹) s x = - (deriv_within c s x) / (c x)^2 :=
(hc.has_deriv_within_at.inv hx).deriv_within hxs
@[simp] lemma deriv_inv' (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) :
deriv (λx, (c x)⁻¹) x = - (deriv c x) / (c x)^2 :=
(hc.has_deriv_at.inv hx).deriv
end inverse
section division
/-! ### Derivative of `x ↦ c x / d x` -/
variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜}
lemma has_deriv_within_at.div
(hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) :
has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x :=
begin
have A : (d x)⁻¹ * (d x)⁻¹ * (c' * d x) = (d x)⁻¹ * c',
by rw [← mul_assoc, mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel hx, one_mul],
convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd),
simp [div_eq_inv_mul, pow_two, mul_inv', mul_add, A, sub_eq_add_neg],
ring
end
lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) :
has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hc.div hd hx
end
lemma differentiable_within_at.div
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) :
differentiable_within_at 𝕜 (λx, c x / d x) s x :=
((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at
@[simp] lemma differentiable_at.div
(hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) :
differentiable_at 𝕜 (λx, c x / d x) x :=
((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at
lemma differentiable_on.div
(hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) :
differentiable_on 𝕜 (λx, c x / d x) s :=
λx h, (hc x h).div (hd x h) (hx x h)
@[simp] lemma differentiable.div
(hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) :
differentiable 𝕜 (λx, c x / d x) :=
λx, (hc x).div (hd x) (hx x)
lemma deriv_within_div
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0)
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, c x / d x) s x
= ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 :=
((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs
@[simp] lemma deriv_div
(hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) :
deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 :=
((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv
lemma differentiable_within_at.div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜} :
differentiable_within_at 𝕜 (λx, c x / d) s x :=
by simp [div_eq_inv_mul, differentiable_within_at.const_mul, hc]
@[simp] lemma differentiable_at.div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜} :
differentiable_at 𝕜 (λ x, c x / d) x :=
by simp [div_eq_inv_mul, hc]
lemma differentiable_on.div_const (hc : differentiable_on 𝕜 c s) {d : 𝕜} :
differentiable_on 𝕜 (λx, c x / d) s :=
by simp [div_eq_inv_mul, differentiable_on.const_mul, hc]
@[simp] lemma differentiable.div_const (hc : differentiable 𝕜 c) {d : 𝕜} :
differentiable 𝕜 (λx, c x / d) :=
by simp [div_eq_inv_mul, differentiable.const_mul, hc]
lemma deriv_within_div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜}
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, c x / d) s x = (deriv_within c s x) / d :=
by simp [div_eq_inv_mul, deriv_within_const_mul, hc, hxs]
@[simp] lemma deriv_div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜} :
deriv (λx, c x / d) x = (deriv c x) / d :=
by simp [div_eq_inv_mul, deriv_const_mul, hc]
end division
theorem has_strict_deriv_at.has_strict_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜}
(hf : has_strict_deriv_at f f' x) (hf' : f' ≠ 0) :
has_strict_fderiv_at f
(continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x :=
hf
theorem has_deriv_at.has_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜}
(hf : has_deriv_at f f' x) (hf' : f' ≠ 0) :
has_fderiv_at f
(continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x :=
hf
/-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an
invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a`
in the strict sense.
This is one of the easy parts of the inverse function theorem: it assumes that we already have an
inverse function. -/
theorem has_strict_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜}
(hg : continuous_at g a) (hf : has_strict_deriv_at f f' (g a)) (hf' : f' ≠ 0)
(hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) :
has_strict_deriv_at g f'⁻¹ a :=
(hf.has_strict_fderiv_at_equiv hf').of_local_left_inverse hg hfg
/-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an
invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`.
This is one of the easy parts of the inverse function theorem: it assumes that we already have
an inverse function. -/
theorem has_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜}
(hg : continuous_at g a) (hf : has_deriv_at f f' (g a)) (hf' : f' ≠ 0)
(hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) :
has_deriv_at g f'⁻¹ a :=
(hf.has_fderiv_at_equiv hf').of_local_left_inverse hg hfg
end
namespace polynomial
/-! ### Derivative of a polynomial -/
variables {x : 𝕜} {s : set 𝕜}
variable (p : polynomial 𝕜)
/-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/
protected lemma has_strict_deriv_at (x : 𝕜) :
has_strict_deriv_at (λx, p.eval x) (p.derivative.eval x) x :=
begin
apply p.induction_on,
{ simp [has_strict_deriv_at_const] },
{ assume p q hp hq,
convert hp.add hq;
simp },
{ assume n a h,
convert h.mul (has_strict_deriv_at_id x),
{ ext y, simp [pow_add, mul_assoc] },
{ simp [pow_add], ring } }
end
/-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/
protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x :=
(p.has_strict_deriv_at x).has_deriv_at
protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) :
has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x :=
(p.has_deriv_at x).has_deriv_within_at
protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x :=
(p.has_deriv_at x).differentiable_at
protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x :=
p.differentiable_at.differentiable_within_at
protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) :=
λx, p.differentiable_at
protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s :=
p.differentiable.differentiable_on
@[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x :=
(p.has_deriv_at x).deriv
protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, p.eval x) s x = p.derivative.eval x :=
begin
rw differentiable_at.deriv_within p.differentiable_at hxs,
exact p.deriv
end
protected lemma continuous : continuous (λx, p.eval x) :=
p.differentiable.continuous
protected lemma continuous_on : continuous_on (λx, p.eval x) s :=
p.continuous.continuous_on
protected lemma continuous_at : continuous_at (λx, p.eval x) x :=
p.continuous.continuous_at
protected lemma continuous_within_at : continuous_within_at (λx, p.eval x) s x :=
p.continuous_at.continuous_within_at
protected lemma has_fderiv_at (x : 𝕜) :
has_fderiv_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) x :=
by simpa [has_deriv_at_iff_has_fderiv_at] using p.has_deriv_at x
protected lemma has_fderiv_within_at (x : 𝕜) :
has_fderiv_within_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) s x :=
(p.has_fderiv_at x).has_fderiv_within_at
@[simp] protected lemma fderiv : fderiv 𝕜 (λx, p.eval x) x = smul_right 1 (p.derivative.eval x) :=
(p.has_fderiv_at x).fderiv
protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λx, p.eval x) s x = smul_right 1 (p.derivative.eval x) :=
begin
rw differentiable_at.fderiv_within p.differentiable_at hxs,
exact p.fderiv
end
end polynomial
section pow
/-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/
variables {x : 𝕜} {s : set 𝕜} {c : 𝕜 → 𝕜} {c' : 𝕜}
variable {n : ℕ }
lemma has_strict_deriv_at_pow (n : ℕ) (x : 𝕜) :
has_strict_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x :=
begin
convert (polynomial.C (1 : 𝕜) * (polynomial.X)^n).has_strict_deriv_at x,
{ simp },
{ rw [polynomial.derivative_monomial], simp }
end
lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x :=
(has_strict_deriv_at_pow n x).has_deriv_at
theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) :
has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x :=
(has_deriv_at_pow n x).has_deriv_within_at
lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x :=
(has_deriv_at_pow n x).differentiable_at
lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x :=
differentiable_at_pow.differentiable_within_at
lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) :=
λx, differentiable_at_pow
lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s :=
differentiable_pow.differentiable_on
lemma deriv_pow : deriv (λx, x^n) x = (n : 𝕜) * x^(n-1) :=
(has_deriv_at_pow n x).deriv
@[simp] lemma deriv_pow' : deriv (λx, x^n) = λ x, (n : 𝕜) * x^(n-1) :=
funext $ λ x, deriv_pow
lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) :=
(has_deriv_within_at_pow n x s).deriv_within hxs
lemma iter_deriv_pow' {k : ℕ} :
deriv^[k] (λx:𝕜, x^n) = λ x, (∏ i in finset.range k, (n - i) : ℕ) * x^(n-k) :=
begin
induction k with k ihk,
{ simp only [one_mul, finset.prod_range_zero, function.iterate_zero_apply, nat.sub_zero,
nat.cast_one] },
{ simp only [function.iterate_succ_apply', ihk, finset.prod_range_succ],
ext x,
rw [((has_deriv_at_pow (n - k) x).const_mul _).deriv, nat.cast_mul, mul_left_comm, mul_assoc,
nat.succ_eq_add_one, nat.sub_sub] }
end
lemma iter_deriv_pow {k : ℕ} :
deriv^[k] (λx:𝕜, x^n) x = (∏ i in finset.range k, (n - i) : ℕ) * x^(n-k) :=
congr_fun iter_deriv_pow' x
lemma has_deriv_within_at.pow (hc : has_deriv_within_at c c' s x) :
has_deriv_within_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') s x :=
(has_deriv_at_pow n (c x)).comp_has_deriv_within_at x hc
lemma has_deriv_at.pow (hc : has_deriv_at c c' x) :
has_deriv_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') x :=
by { rw ← has_deriv_within_at_univ at *, exact hc.pow }
lemma differentiable_within_at.pow (hc : differentiable_within_at 𝕜 c s x) :
differentiable_within_at 𝕜 (λx, (c x)^n) s x :=
hc.has_deriv_within_at.pow.differentiable_within_at
@[simp] lemma differentiable_at.pow (hc : differentiable_at 𝕜 c x) :
differentiable_at 𝕜 (λx, (c x)^n) x :=
hc.has_deriv_at.pow.differentiable_at
lemma differentiable_on.pow (hc : differentiable_on 𝕜 c s) :
differentiable_on 𝕜 (λx, (c x)^n) s :=
λx h, (hc x h).pow
@[simp] lemma differentiable.pow (hc : differentiable 𝕜 c) :
differentiable 𝕜 (λx, (c x)^n) :=
λx, (hc x).pow
lemma deriv_within_pow' (hc : differentiable_within_at 𝕜 c s x)
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, (c x)^n) s x = (n : 𝕜) * (c x)^(n-1) * (deriv_within c s x) :=
hc.has_deriv_within_at.pow.deriv_within hxs
@[simp] lemma deriv_pow'' (hc : differentiable_at 𝕜 c x) :
deriv (λx, (c x)^n) x = (n : 𝕜) * (c x)^(n-1) * (deriv c x) :=
hc.has_deriv_at.pow.deriv
end pow
section fpow
/-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/
variables {x : 𝕜} {s : set 𝕜}
variable {m : ℤ}
lemma has_strict_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) :
has_strict_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x :=
begin
have : ∀ m : ℤ, 0 < m → has_strict_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x,
{ assume m hm,
lift m to ℕ using (le_of_lt hm),
simp only [fpow_of_nat, int.cast_coe_nat],
convert has_strict_deriv_at_pow _ _ using 2,
rw [← int.coe_nat_one, ← int.coe_nat_sub, fpow_coe_nat],
norm_cast at hm,
exact nat.succ_le_of_lt hm },
rcases lt_trichotomy m 0 with hm|hm|hm,
{ have := (has_strict_deriv_at_inv _).scomp _ (this (-m) (neg_pos.2 hm));
[skip, exact fpow_ne_zero_of_ne_zero hx _],
simp only [(∘), fpow_neg, one_div_eq_inv, inv_inv', smul_eq_mul] at this,
convert this using 1,
rw [pow_two, mul_inv', inv_inv', int.cast_neg, ← neg_mul_eq_neg_mul, neg_mul_neg,
← fpow_add hx, mul_assoc, ← fpow_add hx], congr, abel },
{ simp only [hm, fpow_zero, int.cast_zero, zero_mul, has_strict_deriv_at_const] },
{ exact this m hm }
end
lemma has_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) :
has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x :=
(has_strict_deriv_at_fpow m hx).has_deriv_at
theorem has_deriv_within_at_fpow (m : ℤ) (hx : x ≠ 0) (s : set 𝕜) :
has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x :=
(has_deriv_at_fpow m hx).has_deriv_within_at
lemma differentiable_at_fpow (hx : x ≠ 0) : differentiable_at 𝕜 (λx, x^m) x :=
(has_deriv_at_fpow m hx).differentiable_at
lemma differentiable_within_at_fpow (hx : x ≠ 0) :
differentiable_within_at 𝕜 (λx, x^m) s x :=
(differentiable_at_fpow hx).differentiable_within_at
lemma differentiable_on_fpow (hs : (0:𝕜) ∉ s) : differentiable_on 𝕜 (λx, x^m) s :=
λ x hxs, differentiable_within_at_fpow (λ hx, hs $ hx ▸ hxs)
-- TODO : this is true at `x=0` as well
lemma deriv_fpow (hx : x ≠ 0) : deriv (λx, x^m) x = (m : 𝕜) * x^(m-1) :=
(has_deriv_at_fpow m hx).deriv
lemma deriv_within_fpow (hxs : unique_diff_within_at 𝕜 s x) (hx : x ≠ 0) :
deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) :=
(has_deriv_within_at_fpow m hx s).deriv_within hxs
lemma iter_deriv_fpow {k : ℕ} (hx : x ≠ 0) :
deriv^[k] (λx:𝕜, x^m) x = (∏ i in finset.range k, (m - i) : ℤ) * x^(m-k) :=
begin
induction k with k ihk generalizing x hx,
{ simp only [one_mul, finset.prod_range_zero, function.iterate_zero_apply, int.coe_nat_zero,
sub_zero, int.cast_one] },
{ rw [function.iterate_succ', finset.prod_range_succ, int.cast_mul, mul_assoc, mul_left_comm,
int.coe_nat_succ, ← sub_sub, ← ((has_deriv_at_fpow _ hx).const_mul _).deriv],
exact deriv_congr_of_mem_nhds (eventually.mono (mem_nhds_sets is_open_ne hx) @ihk) }
end
end fpow
/-! ### Upper estimates on liminf and limsup -/
section real
variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ}
lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) :
∀ᶠ z in nhds_within x (s \ {x}), (z - x)⁻¹ * (f z - f x) < r :=
has_deriv_within_at_iff_tendsto_slope.1 hf (mem_nhds_sets is_open_Iio hr)
lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x)
(hs : x ∉ s) (hr : f' < r) :
∀ᶠ z in nhds_within x s, (z - x)⁻¹ * (f z - f x) < r :=
(has_deriv_within_at_iff_tendsto_slope' hs).1 hf (mem_nhds_sets is_open_Iio hr)
lemma has_deriv_within_at.liminf_right_slope_le
(hf : has_deriv_within_at f f' (Ioi x) x) (hr : f' < r) :
∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (f z - f x) < r :=
(hf.limsup_slope_le' (lt_irrefl x) hr).frequently (nhds_within_Ioi_self_ne_bot x)
end real
section real_space
open metric
variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ}
{x r : ℝ}
/-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio
`∥f z - f x∥ / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`.
In other words, the limit superior of this ratio as `z` tends to `x` along `s`
is less than or equal to `∥f'∥`. -/
lemma has_deriv_within_at.limsup_norm_slope_le
(hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) :
∀ᶠ z in nhds_within x s, ∥z - x∥⁻¹ * ∥f z - f x∥ < r :=
begin
have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr,
have A : ∀ᶠ z in nhds_within x (s \ {x}), ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r,
from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (mem_nhds_sets is_open_Iio hr),
have B : ∀ᶠ z in nhds_within x {x}, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r,
from mem_sets_of_superset self_mem_nhds_within
(singleton_subset_iff.2 $ by simp [hr₀]),
have C := mem_sup_sets.2 ⟨A, B⟩,
rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup_sets] at C,
filter_upwards [C.1],
simp only [mem_set_of_eq, norm_smul, mem_Iio, normed_field.norm_inv],
exact λ _, id
end
/-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio
`(∥f z∥ - ∥f x∥) / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`.
In other words, the limit superior of this ratio as `z` tends to `x` along `s`
is less than or equal to `∥f'∥`.
This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le`
where `∥f z∥ - ∥f x∥` is replaced by `∥f z - f x∥`. -/
lemma has_deriv_within_at.limsup_slope_norm_le
(hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) :
∀ᶠ z in nhds_within x s, ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) < r :=
begin
apply (hf.limsup_norm_slope_le hr).mono,
assume z hz,
refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz,
exact inv_nonneg.2 (norm_nonneg _)
end
/-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio
`∥f z - f x∥ / ∥z - x∥` is frequently less than `r` as `z → x+0`.
In other words, the limit inferior of this ratio as `z` tends to `x+0`
is less than or equal to `∥f'∥`. See also `has_deriv_within_at.limsup_norm_slope_le`
for a stronger version using limit superior and any set `s`. -/
lemma has_deriv_within_at.liminf_right_norm_slope_le
(hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) :
∃ᶠ z in nhds_within x (Ioi x), ∥z - x∥⁻¹ * ∥f z - f x∥ < r :=
(hf.limsup_norm_slope_le hr).frequently (nhds_within_Ioi_self_ne_bot x)
/-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio
`(∥f z∥ - ∥f x∥) / (z - x)` is frequently less than `r` as `z → x+0`.
In other words, the limit inferior of this ratio as `z` tends to `x+0`
is less than or equal to `∥f'∥`.
See also
* `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using
limit superior and any set `s`;
* `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using
`∥f z - f x∥` instead of `∥f z∥ - ∥f x∥`. -/
lemma has_deriv_within_at.liminf_right_slope_norm_le
(hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) :
∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r :=
begin
have := (hf.limsup_slope_norm_le hr).frequently (nhds_within_Ioi_self_ne_bot x),
refine this.mp (eventually.mono self_mem_nhds_within _),
assume z hxz hz,
rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz
end
end real_space
|
1247036728ee081628a0c42c0dc9e9360d9d7daa
|
d7189ea2ef694124821b033e533f18905b5e87ef
|
/galois/intmod.lean
|
a46e111ecdf3e7ef5da91236efe5a6eb9b7b20f0
|
[
"Apache-2.0"
] |
permissive
|
digama0/lean-protocol-support
|
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
|
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
|
refs/heads/master
| 1,625,421,450,627
| 1,506,035,462,000
| 1,506,035,462,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 6,203
|
lean
|
/-
This modules defines a type for representing integers modulo a natural number n,
along with the standard commutative ring operations.
The representation uses a canonical form of numbers between 0 and n-1. Operations
preserve the canonical form.
-/
import galois.nat.div_lemmas
def intmod (n:ℕ) := { x : ℕ // x < n }
namespace intmod
open nat
variable {n : nat}
def of_nat (x:ℕ) : intmod (succ n) :=
⟨ x % succ n, nat.mod_lt x (nat.zero_lt_succ _) ⟩
private lemma mlt {b : nat} : ∀ {a}, n > a → b % n < n
| 0 h := nat.mod_lt _ h
| (a+1) h :=
have n > 0, from lt.trans (nat.zero_lt_succ _) h,
nat.mod_lt _ this
def zero : intmod (succ n) := ⟨ 0, nat.succ_pos n ⟩
def one : intmod (succ n) := of_nat 1
def add : intmod n → intmod n → intmod n
| ⟨x,x_lt⟩ ⟨y,y_lt⟩ :=
if p:x+y < n then
⟨x+y, p⟩
else
let q : (x+y)-n < n :=
begin
simp [nat.sub_lt_iff'],
have xy_lt_nn : x + y < n + n := add_lt_add x_lt y_lt,
have n_le_xy : n ≤ x + y := le_of_not_gt p,
cc,
end in
⟨ (x+y)-n, q⟩
def neg : intmod n → intmod n
| ⟨x,p⟩ :=
let r := if x = 0 then 0 else n-x in
let q : (if x = 0 then 0 else n-x) < n :=
begin
by_cases x = 0,
{ simp [h],
simp [h] at p,
exact p,
},
{
-- Show x > 0
have x_pos := nat.eq_zero_or_pos x,
simp [h] at x_pos,
-- show n - x < n
simp [h, nat.sub_lt_iff'],
-- Decompose and
constructor,
-- n < n + x
exact lt_add_of_le_of_pos (le_refl n) x_pos,
-- show 0 < n
exact or.inr (lt_trans x_pos p),
}
end in
⟨r, q ⟩
def sub : intmod n → intmod n → intmod n
| ⟨x,h⟩ ⟨y,y_lt⟩ :=
if p : y ≤ x then
let q : x - y < n :=
begin
apply nat.lt_of_le_of_lt,
apply nat.sub_le,
exact h,
end in
⟨ x-y, q ⟩
else
let q : x + n - y < n :=
begin
--have p : x < y := sorry,
simp [nat.sub_lt_iff'],
constructor,
{ apply add_lt_add_left,
-- Enforce h := x < y
exact lt_of_not_ge p,
},
{ -- Pick right branch to prove y ≤ n + x
apply or.inr,
transitivity,
exact nat.le_of_lt y_lt,
apply nat.le_add_right,
}
end in
⟨ x+n-y, q ⟩
def mul : intmod n → intmod n → intmod n
| ⟨x,h⟩ ⟨y,_⟩ := ⟨(x*y)%n, mlt h ⟩
instance (n:ℕ) : has_zero (intmod (succ n)) := ⟨ zero ⟩
instance (n:ℕ) : has_one (intmod (succ n)) := ⟨ one ⟩
instance (n:ℕ) : has_add (intmod n) := ⟨ add ⟩
instance (n:ℕ) : has_neg (intmod n) := ⟨ neg ⟩
instance (n:ℕ) : has_sub (intmod n) := ⟨ sub ⟩
instance (n:ℕ) : has_mul (intmod n) := ⟨ mul ⟩
theorem zero_val (n : ℕ) : (0 : intmod (succ n)).val = 0 := rfl
theorem one_val (n : ℕ) : (1 : intmod (succ n)).val = 1 % succ n := rfl
theorem add_val (x y : intmod n) : (x + y).val = (x.val + y.val) % n :=
begin
cases x with xv x_lt,
cases y with yv y_lt,
transitivity,
unfold has_add.add,
by_cases (xv + yv < n) with p,
{
simp [add, p, nat.mod_eq_of_lt],
},
{
-- Show xv + yv ≥ n
have q : xv + yv ≥ n :=
or.resolve_left (nat.lt_or_ge (xv + yv) n) p,
have r : (xv + yv - n) < n,
{ simp [nat.sub_lt_iff'],
constructor,
{
transitivity,
exact nat.add_lt_add_left y_lt _,
exact nat.add_lt_add_right x_lt _,
},
-- Show n ≤ x + y
exact or.inr q,
},
simp [add, mod_eq_sub_mod, mod_eq_of_lt, *],
},
end
theorem mul_val (x y : intmod n) : (x * y).val = (x.val * y.val) % n :=
begin
cases x with xv xp,
cases y with yv yp,
refl,
end
theorem zero_add (x : intmod (succ n)) : 0 + x = x :=
begin
apply subtype.eq,
simp [add_val, zero_val],
exact nat.mod_eq_of_lt x.property,
end
theorem add_zero (x : intmod (succ n)) : x + 0 = x :=
begin
apply subtype.eq,
simp [add_val, zero_val],
exact nat.mod_eq_of_lt x.property,
end
theorem add_assoc (x y z : intmod n) : (x + y) + z = x + (y + z) :=
begin
apply subtype.eq,
simp [add_val, nat.mod_add_right_mod],
end
theorem add_comm (x y : intmod n) : x + y = y + x :=
begin
apply subtype.eq,
simp [add_val],
end
theorem add_left_neg (x : intmod (succ n)) : -x + x = 0 :=
begin
cases x with xv x_lt,
apply subtype.eq,
simp [add_val, has_neg.neg, neg],
by_cases (xv = 0) with h,
{
simp [h, zero_val],
},
{
have x_le : xv ≤ succ n := nat.le_of_lt x_lt,
simp only [h, if_false, nat.add_comm xv, ge, *, nat.sub_add_cancel],
simp [nat.mod_eq_sub_mod, zero_val],
}
end
theorem one_mul (x : intmod (succ n)) : 1 * x = x :=
begin
apply subtype.eq,
simp [mul_val, one_val, nat.mod_mul_left_mod, nat.mod_mul_right_mod],
exact nat.mod_eq_of_lt x.property,
end
theorem mul_one (x : intmod (succ n)) : x * 1 = x :=
begin
apply subtype.eq,
simp [mul_val, one_val, nat.mod_mul_left_mod, nat.mod_mul_right_mod],
exact nat.mod_eq_of_lt x.property,
end
theorem mul_assoc (x y z : intmod n) : (x * y) * z = x * (y * z) :=
begin
apply subtype.eq,
simp [mul_val, nat.mod_mul_right_mod],
end
theorem mul_comm (x y : intmod n) : x * y = y * x :=
begin
apply subtype.eq,
simp [mul_val],
end
theorem left_distrib (a b c : intmod n)
: a * (b + c) = a * b + a * c :=
begin
apply subtype.eq,
simp [add_val, mul_val],
simp [nat.mod_add_right_mod,
nat.mod_mul_right_mod,
nat.left_distrib],
end
theorem right_distrib (a b c : intmod n)
: (a + b) * c = a * c + b * c :=
begin
simp only [mul_comm _ c, left_distrib],
end
instance (n:ℕ) : comm_ring (intmod (succ n)) :=
{ zero := 0
, one := 1
, add := add
, neg := neg
, mul := mul
, zero_add := zero_add
, add_zero := add_zero
, add_assoc := add_assoc
, add_comm := add_comm
, add_left_neg := add_left_neg
, one_mul := one_mul
, mul_one := mul_one
, mul_assoc := mul_assoc
, mul_comm := mul_comm
, left_distrib := left_distrib
, right_distrib := right_distrib
}
end intmod
|
57fc1260e156165ada838aeb771b06e84633d4bf
|
592ee40978ac7604005a4e0d35bbc4b467389241
|
/Library/generated/mathscheme-lean/AssocPlusRingoid.lean
|
903e44c0ff7f68dfea551ea690350c00d358f834
|
[] |
no_license
|
ysharoda/Deriving-Definitions
|
3e149e6641fae440badd35ac110a0bd705a49ad2
|
dfecb27572022de3d4aa702cae8db19957523a59
|
refs/heads/master
| 1,679,127,857,700
| 1,615,939,007,000
| 1,615,939,007,000
| 229,785,731
| 4
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 9,137
|
lean
|
import init.data.nat.basic
import init.data.fin.basic
import data.vector
import .Prelude
open Staged
open nat
open fin
open vector
section AssocPlusRingoid
structure AssocPlusRingoid (A : Type) : Type :=
(plus : (A → (A → A)))
(times : (A → (A → A)))
(associative_plus : (∀ {x y z : A} , (plus (plus x y) z) = (plus x (plus y z))))
open AssocPlusRingoid
structure Sig (AS : Type) : Type :=
(plusS : (AS → (AS → AS)))
(timesS : (AS → (AS → AS)))
structure Product (A : Type) : Type :=
(plusP : ((Prod A A) → ((Prod A A) → (Prod A A))))
(timesP : ((Prod A A) → ((Prod A A) → (Prod A A))))
(associative_plusP : (∀ {xP yP zP : (Prod A A)} , (plusP (plusP xP yP) zP) = (plusP xP (plusP yP zP))))
structure Hom {A1 : Type} {A2 : Type} (As1 : (AssocPlusRingoid A1)) (As2 : (AssocPlusRingoid A2)) : Type :=
(hom : (A1 → A2))
(pres_plus : (∀ {x1 x2 : A1} , (hom ((plus As1) x1 x2)) = ((plus As2) (hom x1) (hom x2))))
(pres_times : (∀ {x1 x2 : A1} , (hom ((times As1) x1 x2)) = ((times As2) (hom x1) (hom x2))))
structure RelInterp {A1 : Type} {A2 : Type} (As1 : (AssocPlusRingoid A1)) (As2 : (AssocPlusRingoid A2)) : Type 1 :=
(interp : (A1 → (A2 → Type)))
(interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus As1) x1 x2) ((plus As2) y1 y2))))))
(interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times As1) x1 x2) ((times As2) y1 y2))))))
inductive AssocPlusRingoidTerm : Type
| plusL : (AssocPlusRingoidTerm → (AssocPlusRingoidTerm → AssocPlusRingoidTerm))
| timesL : (AssocPlusRingoidTerm → (AssocPlusRingoidTerm → AssocPlusRingoidTerm))
open AssocPlusRingoidTerm
inductive ClAssocPlusRingoidTerm (A : Type) : Type
| sing : (A → ClAssocPlusRingoidTerm)
| plusCl : (ClAssocPlusRingoidTerm → (ClAssocPlusRingoidTerm → ClAssocPlusRingoidTerm))
| timesCl : (ClAssocPlusRingoidTerm → (ClAssocPlusRingoidTerm → ClAssocPlusRingoidTerm))
open ClAssocPlusRingoidTerm
inductive OpAssocPlusRingoidTerm (n : ℕ) : Type
| v : ((fin n) → OpAssocPlusRingoidTerm)
| plusOL : (OpAssocPlusRingoidTerm → (OpAssocPlusRingoidTerm → OpAssocPlusRingoidTerm))
| timesOL : (OpAssocPlusRingoidTerm → (OpAssocPlusRingoidTerm → OpAssocPlusRingoidTerm))
open OpAssocPlusRingoidTerm
inductive OpAssocPlusRingoidTerm2 (n : ℕ) (A : Type) : Type
| v2 : ((fin n) → OpAssocPlusRingoidTerm2)
| sing2 : (A → OpAssocPlusRingoidTerm2)
| plusOL2 : (OpAssocPlusRingoidTerm2 → (OpAssocPlusRingoidTerm2 → OpAssocPlusRingoidTerm2))
| timesOL2 : (OpAssocPlusRingoidTerm2 → (OpAssocPlusRingoidTerm2 → OpAssocPlusRingoidTerm2))
open OpAssocPlusRingoidTerm2
def simplifyCl {A : Type} : ((ClAssocPlusRingoidTerm A) → (ClAssocPlusRingoidTerm A))
| (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2))
| (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2))
| (sing x1) := (sing x1)
def simplifyOpB {n : ℕ} : ((OpAssocPlusRingoidTerm n) → (OpAssocPlusRingoidTerm n))
| (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2))
| (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2))
| (v x1) := (v x1)
def simplifyOp {n : ℕ} {A : Type} : ((OpAssocPlusRingoidTerm2 n A) → (OpAssocPlusRingoidTerm2 n A))
| (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2))
| (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2))
| (v2 x1) := (v2 x1)
| (sing2 x1) := (sing2 x1)
def evalB {A : Type} : ((AssocPlusRingoid A) → (AssocPlusRingoidTerm → A))
| As (plusL x1 x2) := ((plus As) (evalB As x1) (evalB As x2))
| As (timesL x1 x2) := ((times As) (evalB As x1) (evalB As x2))
def evalCl {A : Type} : ((AssocPlusRingoid A) → ((ClAssocPlusRingoidTerm A) → A))
| As (sing x1) := x1
| As (plusCl x1 x2) := ((plus As) (evalCl As x1) (evalCl As x2))
| As (timesCl x1 x2) := ((times As) (evalCl As x1) (evalCl As x2))
def evalOpB {A : Type} {n : ℕ} : ((AssocPlusRingoid A) → ((vector A n) → ((OpAssocPlusRingoidTerm n) → A)))
| As vars (v x1) := (nth vars x1)
| As vars (plusOL x1 x2) := ((plus As) (evalOpB As vars x1) (evalOpB As vars x2))
| As vars (timesOL x1 x2) := ((times As) (evalOpB As vars x1) (evalOpB As vars x2))
def evalOp {A : Type} {n : ℕ} : ((AssocPlusRingoid A) → ((vector A n) → ((OpAssocPlusRingoidTerm2 n A) → A)))
| As vars (v2 x1) := (nth vars x1)
| As vars (sing2 x1) := x1
| As vars (plusOL2 x1 x2) := ((plus As) (evalOp As vars x1) (evalOp As vars x2))
| As vars (timesOL2 x1 x2) := ((times As) (evalOp As vars x1) (evalOp As vars x2))
def inductionB {P : (AssocPlusRingoidTerm → Type)} : ((∀ (x1 x2 : AssocPlusRingoidTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → ((∀ (x1 x2 : AssocPlusRingoidTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → (∀ (x : AssocPlusRingoidTerm) , (P x))))
| pplusl ptimesl (plusL x1 x2) := (pplusl _ _ (inductionB pplusl ptimesl x1) (inductionB pplusl ptimesl x2))
| pplusl ptimesl (timesL x1 x2) := (ptimesl _ _ (inductionB pplusl ptimesl x1) (inductionB pplusl ptimesl x2))
def inductionCl {A : Type} {P : ((ClAssocPlusRingoidTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClAssocPlusRingoidTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → ((∀ (x1 x2 : (ClAssocPlusRingoidTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → (∀ (x : (ClAssocPlusRingoidTerm A)) , (P x)))))
| psing ppluscl ptimescl (sing x1) := (psing x1)
| psing ppluscl ptimescl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ppluscl ptimescl x1) (inductionCl psing ppluscl ptimescl x2))
| psing ppluscl ptimescl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing ppluscl ptimescl x1) (inductionCl psing ppluscl ptimescl x2))
def inductionOpB {n : ℕ} {P : ((OpAssocPlusRingoidTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpAssocPlusRingoidTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → ((∀ (x1 x2 : (OpAssocPlusRingoidTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → (∀ (x : (OpAssocPlusRingoidTerm n)) , (P x)))))
| pv pplusol ptimesol (v x1) := (pv x1)
| pv pplusol ptimesol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv pplusol ptimesol x1) (inductionOpB pv pplusol ptimesol x2))
| pv pplusol ptimesol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv pplusol ptimesol x1) (inductionOpB pv pplusol ptimesol x2))
def inductionOp {n : ℕ} {A : Type} {P : ((OpAssocPlusRingoidTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpAssocPlusRingoidTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → ((∀ (x1 x2 : (OpAssocPlusRingoidTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → (∀ (x : (OpAssocPlusRingoidTerm2 n A)) , (P x))))))
| pv2 psing2 pplusol2 ptimesol2 (v2 x1) := (pv2 x1)
| pv2 psing2 pplusol2 ptimesol2 (sing2 x1) := (psing2 x1)
| pv2 psing2 pplusol2 ptimesol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 pplusol2 ptimesol2 x1) (inductionOp pv2 psing2 pplusol2 ptimesol2 x2))
| pv2 psing2 pplusol2 ptimesol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 pplusol2 ptimesol2 x1) (inductionOp pv2 psing2 pplusol2 ptimesol2 x2))
def stageB : (AssocPlusRingoidTerm → (Staged AssocPlusRingoidTerm))
| (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2))
| (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2))
def stageCl {A : Type} : ((ClAssocPlusRingoidTerm A) → (Staged (ClAssocPlusRingoidTerm A)))
| (sing x1) := (Now (sing x1))
| (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2))
| (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2))
def stageOpB {n : ℕ} : ((OpAssocPlusRingoidTerm n) → (Staged (OpAssocPlusRingoidTerm n)))
| (v x1) := (const (code (v x1)))
| (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2))
| (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2))
def stageOp {n : ℕ} {A : Type} : ((OpAssocPlusRingoidTerm2 n A) → (Staged (OpAssocPlusRingoidTerm2 n A)))
| (sing2 x1) := (Now (sing2 x1))
| (v2 x1) := (const (code (v2 x1)))
| (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2))
| (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2))
structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type :=
(plusT : ((Repr A) → ((Repr A) → (Repr A))))
(timesT : ((Repr A) → ((Repr A) → (Repr A))))
end AssocPlusRingoid
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.