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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
655c4088319b37ce51795a6890dfc5dd7c19f425 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/field_theory/minimal_polynomial.lean | d43ed50e5da79db4bfbfeefe5d4b679c4f9133ca | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 8,859 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johan Commelin
-/
import ring_theory.integral_closure
/-!
# Minimal polynomials
This file defines the minimal polynomial of an element x of an A-algebra B,
under the assumption that x is integral over A.
After stating the defining property we specialize to the setting of field extensions
and derive some well-known properties, amongst which the fact that minimal polynomials
are irreducible, and uniquely determined by their defining property.
-/
universes u v w
open_locale classical
open polynomial set function
variables {α : Type u} {β : Type v}
section min_poly_def
variables [comm_ring α] [comm_ring β] [algebra α β]
/-- Let B be an A-algebra, and x an element of B that is integral over A.
The minimal polynomial of x is a monic polynomial of smallest degree that has x as its root. -/
noncomputable def minimal_polynomial {x : β} (hx : is_integral α x) : polynomial α :=
well_founded.min polynomial.degree_lt_wf _ hx
end min_poly_def
namespace minimal_polynomial
section ring
variables [comm_ring α] [comm_ring β] [algebra α β]
variables {x : β} (hx : is_integral α x)
/--A minimal polynomial is monic.-/
lemma monic : monic (minimal_polynomial hx) :=
(well_founded.min_mem degree_lt_wf _ hx).1
/--An element is a root of its minimal polynomial.-/
@[simp] lemma aeval : aeval α β x (minimal_polynomial hx) = 0 :=
(well_founded.min_mem degree_lt_wf _ hx).2
/--The defining property of the minimal polynomial of an element x:
it is the monic polynomial with smallest degree that has x as its root.-/
lemma min {p : polynomial α} (pmonic : p.monic) (hp : polynomial.aeval α β x p = 0) :
degree (minimal_polynomial hx) ≤ degree p :=
le_of_not_lt $ well_founded.not_lt_min degree_lt_wf _ hx ⟨pmonic, hp⟩
end ring
section field
variables [field α] [field β] [algebra α β]
variables {x : β} (hx : is_integral α x)
/--A minimal polynomial is nonzero.-/
lemma ne_zero : (minimal_polynomial hx) ≠ 0 :=
ne_zero_of_monic (monic hx)
/--If an element x is a root of a nonzero polynomial p,
then the degree of p is at least the degree of the minimal polynomial of x.-/
lemma degree_le_of_ne_zero
{p : polynomial α} (pnz : p ≠ 0) (hp : polynomial.aeval α β x p = 0) :
degree (minimal_polynomial hx) ≤ degree p :=
calc degree (minimal_polynomial hx) ≤ degree (p * C (leading_coeff p)⁻¹) :
min _ (monic_mul_leading_coeff_inv pnz) (by simp [hp])
... = degree p : degree_mul_leading_coeff_inv p pnz
/--The minimal polynomial of an element x is uniquely characterized by its defining property:
if there is another monic polynomial of minimal degree that has x as a root,
then this polynomial is equal to the minimal polynomial of x.-/
lemma unique {p : polynomial α} (pmonic : p.monic) (hp : polynomial.aeval α β x p = 0)
(pmin : ∀ q : polynomial α, q.monic → polynomial.aeval α β x q = 0 → degree p ≤ degree q) :
p = minimal_polynomial hx :=
begin
symmetry, apply eq_of_sub_eq_zero,
by_contra hnz,
have := degree_le_of_ne_zero hx hnz (by simp [hp]),
contrapose! this,
apply degree_sub_lt _ (ne_zero hx),
{ rw [(monic hx).leading_coeff, pmonic.leading_coeff] },
{ exact le_antisymm (min hx pmonic hp)
(pmin (minimal_polynomial hx) (monic hx) (aeval hx)) },
end
/--If an element x is a root of a polynomial p, then the minimal polynomial of x divides p.-/
lemma dvd {p : polynomial α} (hp : polynomial.aeval α β x p = 0) :
minimal_polynomial hx ∣ p :=
begin
rw ← dvd_iff_mod_by_monic_eq_zero (monic hx),
by_contra hnz,
have := degree_le_of_ne_zero hx hnz _,
{ contrapose! this,
exact degree_mod_by_monic_lt _ (monic hx) (ne_zero hx) },
{ rw ← mod_by_monic_add_div p (monic hx) at hp,
simpa using hp }
end
/--The degree of a minimal polynomial is nonzero.-/
lemma degree_ne_zero : degree (minimal_polynomial hx) ≠ 0 :=
begin
assume deg_eq_zero,
have ndeg_eq_zero : nat_degree (minimal_polynomial hx) = 0,
{ simpa using congr_arg nat_degree (eq_C_of_degree_eq_zero deg_eq_zero) },
have eq_one : minimal_polynomial hx = 1,
{ rw eq_C_of_degree_eq_zero deg_eq_zero, congr,
simpa [ndeg_eq_zero.symm] using (monic hx).leading_coeff },
simpa [eq_one, aeval_def] using aeval hx
end
/--A minimal polynomial is not a unit.-/
lemma not_is_unit : ¬ is_unit (minimal_polynomial hx) :=
assume H, degree_ne_zero hx $ degree_eq_zero_of_is_unit H
/--The degree of a minimal polynomial is positive.-/
lemma degree_pos : 0 < degree (minimal_polynomial hx) :=
degree_pos_of_ne_zero_of_nonunit (ne_zero hx) (not_is_unit hx)
/--A minimal polynomial is prime.-/
lemma prime : prime (minimal_polynomial hx) :=
begin
refine ⟨ne_zero hx, not_is_unit hx, _⟩,
rintros p q ⟨d, h⟩,
have : polynomial.aeval α β x (p*q) = 0 := by simp [h, aeval hx],
replace : polynomial.aeval α β x p = 0 ∨ polynomial.aeval α β x q = 0 := by simpa,
cases this; [left, right]; apply dvd; assumption
end
/--A minimal polynomial is irreducible.-/
lemma irreducible : irreducible (minimal_polynomial hx) :=
irreducible_of_prime (prime hx)
/--If L/K is a field extension, and x is an element of L in the image of K,
then the minimal polynomial of x is X - C x.-/
@[simp] protected lemma algebra_map (a : α) (ha : is_integral α (algebra_map α β a)) :
minimal_polynomial ha = X - C a :=
begin
refine (unique ha (monic_X_sub_C a) (by simp [aeval_def]) _).symm,
intros q hq H,
rw degree_X_sub_C,
suffices : 0 < degree q,
{ -- This part is annoying and shouldn't be there.
have q_ne_zero : q ≠ 0,
{ apply polynomial.ne_zero_of_degree_gt this },
rw degree_eq_nat_degree q_ne_zero at this ⊢,
rw [← with_bot.coe_zero, with_bot.coe_lt_coe] at this,
rwa [← with_bot.coe_one, with_bot.coe_le_coe], },
apply degree_pos_of_root (ne_zero_of_monic hq),
show is_root q a,
apply (algebra_map α β).injective,
rw [(algebra_map α β).map_zero, ← H],
exact q.hom_eval₂ (ring_hom.id _) (algebra_map α β) _,
end
variable (β)
/--If L/K is a field extension, and x is an element of L in the image of K,
then the minimal polynomial of x is X - C x.-/
lemma algebra_map' (a : α) :
minimal_polynomial (@is_integral_algebra_map α β _ _ _ a) =
X - C a :=
minimal_polynomial.algebra_map _ _
variable {β}
/--The minimal polynomial of 0 is X.-/
@[simp] lemma zero {h₀ : is_integral α (0:β)} :
minimal_polynomial h₀ = X :=
by simpa only [add_zero, polynomial.C_0, sub_eq_add_neg, neg_zero, ring_hom.map_zero]
using algebra_map' β (0:α)
/--The minimal polynomial of 1 is X - 1.-/
@[simp] lemma one {h₁ : is_integral α (1:β)} :
minimal_polynomial h₁ = X - 1 :=
by simpa only [ring_hom.map_one, polynomial.C_1, sub_eq_add_neg]
using algebra_map' β (1:α)
/--If L/K is a field extension and an element y of K is a root of the minimal polynomial
of an element x ∈ L, then y maps to x under the field embedding.-/
lemma root {x : β} (hx : is_integral α x) {y : α}
(h : is_root (minimal_polynomial hx) y) : algebra_map α β y = x :=
begin
have ndeg_one : nat_degree (minimal_polynomial hx) = 1,
{ rw ← polynomial.degree_eq_iff_nat_degree_eq_of_pos (nat.zero_lt_one),
exact degree_eq_one_of_irreducible_of_root (irreducible hx) h },
have coeff_one : (minimal_polynomial hx).coeff 1 = 1,
{ simpa only [ndeg_one, leading_coeff] using (monic hx).leading_coeff },
have hy : y = - coeff (minimal_polynomial hx) 0,
{ rw (minimal_polynomial hx).as_sum at h,
apply eq_neg_of_add_eq_zero,
simpa only [ndeg_one, coeff_one, C_1, eval_C, eval_X, eval_add, mul_one, one_mul, pow_zero, pow_one,
is_root.def, finset.sum_range_succ, finset.insert_empty_eq_singleton, finset.sum_singleton, finset.range_one] using h, },
subst y,
rw [ring_hom.map_neg, neg_eq_iff_add_eq_zero],
have H := aeval hx,
rw (minimal_polynomial hx).as_sum at H,
simpa only [ndeg_one, coeff_one, aeval_def, C_1, eval₂_add, eval₂_C, eval₂_X,
mul_one, one_mul, pow_one, pow_zero, add_comm,
finset.sum_range_succ, finset.insert_empty_eq_singleton, finset.sum_singleton, finset.range_one] using H,
end
/--The constant coefficient of the minimal polynomial of x is 0
if and only if x = 0.-/
@[simp] lemma coeff_zero_eq_zero : coeff (minimal_polynomial hx) 0 = 0 ↔ x = 0 :=
begin
split,
{ intro h,
have zero_root := polynomial.zero_is_root_of_coeff_zero_eq_zero h,
rw ← root hx zero_root,
exact is_ring_hom.map_zero _ },
{ rintro rfl, simp }
end
/--The minimal polynomial of a nonzero element has nonzero constant coefficient.-/
lemma coeff_zero_ne_zero (h : x ≠ 0) : coeff (minimal_polynomial hx) 0 ≠ 0 :=
by { contrapose! h, simpa using h }
end field
end minimal_polynomial
|
1616ea2cb642eee9523e61ff0532276f51f39640 | b7fc5b86b12212bea5542eb2c9d9f0988fd78697 | /src/solutions/thursday/groups_rings_fields.lean | 5b63efd91076f1cede8620bdabf0686da564a32c | [] | no_license | stjordanis/lftcm2020 | 3b16591aec853c8546d9c8b69c0bf3f5f3956fee | 1f3485e4dafdc587b451ec5144a1d8d3ec9b411e | refs/heads/master | 1,675,958,865,413 | 1,609,901,722,000 | 1,609,901,722,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,927 | lean | import linear_algebra.finite_dimensional
import ring_theory.algebraic
import data.zmod.basic
import data.real.basic
import tactic
/-!
```
____
/ ___|_ __ ___ _ _ _ __ ___
| | _| '__/ _ \| | | | '_ \/ __|
| |_| | | | (_) | |_| | |_) \__ \_
\____|_| \___/ \__,_| .__/|___( )
|_| |/
_ __ (_) _ __ __ _ ___
| '__| | | | '_ \ / _` | / __|
| | | | | | | | | (_| | \__ \ _
|_| |_| |_| |_| \__, | |___/ ( )
|___/ |/
_ __ _ _ _
__ _ _ __ __| | / _| (_) ___ | | __| | ___
/ _` | | '_ \ / _` | | |_ | | / _ \ | | / _` | / __|
| (_| | | | | | | (_| | | _| | | | __/ | | | (_| | \__ \
\__,_| |_| |_| \__,_| |_| |_| \___| |_| \__,_| |___/
```
-/
/-! ## Reminder on updating the exercises
These instructions are now available at:
https://leanprover-community.github.io/lftcm2020/exercises.html
To get a new copy of the exercises,
run the following commands in your terminal:
```
leanproject get lftcm2020
cp -r lftcm2020/src/exercises_sources/ lftcm2020/src/my_exercises
code lftcm2020
```
To update your exercise files, run the following commands:
```
cd /path/to/lftcm2020
git pull
leanproject get-mathlib-cache
```
Don’t forget to copy the updated files to `src/my_exercises`.
-/
/-! ## What do we have?
Too much to cover in detail in 10 minutes.
Take a look at the “General algebra” section on
https://leanprover-community.github.io/mathlib-overview.html
All the basic concepts are there:
`group`, `ring`, `field`, `module`, etc...
Also versions that are compatible with an ordering, like `ordered_ring`
And versions that express compatibility with a topology: `topological_group`
Finally constructions, like `polynomial R`, or `mv_polynomial σ R`,
or `monoid_algebra K G`, or `ℤ_[p]`, or `zmod n`, or `localization R S`.
-/
/-! ## Morphisms
We are in the middle of a transition to “bundled” morphisms.
(Why? Long story... but they work better with `simp`)
* `X → Y` -- ordinary function
* `X →+ Y` -- function respects `0` and `+`
* `X →* Y` -- function respects `1` and `*`
* `X →+* Y` -- function respects `0`, `1`, `+`, `*` (surprise!)
-/
section
variables {R S : Type*} [ring R] [ring S]
-- We used to write
example (f : R → S) [is_ring_hom f] : true := trivial
-- But now we write
example (f : R →+* S) : true := trivial
/-
This heavily relies on the “coercion to function”
that we have seen a couple of times this week.
-/
end
/-! ## Where are these things in the library?
`algebra/` for basic definitions and properties; “algebraic hierarchy”
`group_theory/` ⎫
`ring_theory/` ⎬ “advanced” and “specialised” material
`field_theory/` ⎭
`data/` definitions and examples
To give an idea:
* `algebra/ordered_ring.lean`
* `ring_theory/noetherian.lean`
* `field_theory/chevalley_warning.lean`
* `data/nat/*.lean`, `data/real/*.lean`, `data/padics/*.lean`
-/
/-! ## How to find things (search tools)
* `library_search` -- it often helps to carve out
the exact lemma statement that you are looking for
* online documentation: https://leanprover-community.github.io/mathlib_docs/
new search bar under construction
* Old-skool: `grep`
* Search in VS Code:
- `Ctrl - Shift - F`
-- don't forget to change settings, to search everywhere
-- click the three dots (`…`) below the search bar
-- disable the blue cogwheel
- `Ctrl - P` -- search for filenames
- `Ctrl - P`, `#` -- search for lemmas and definitions
-/
/-! ## How to find things (autocomplete)
Mathlib follows pretty strict naming conventions:
```
/-- The binomial theorem-/
theorem add_pow [comm_semiring α] (x y : α) (n : ℕ) :
(x + y) ^ n = ∑ m in range (n + 1), x ^ m * y ^ (n - m) * choose n m :=
(commute.all x y).add_pow n
```
After a while, you get the hang of this,
and you can start guessing names.
-/
open_locale big_operators -- nice notation ∑, ∏
open finset -- `finset.range n` is the finite set `{0,1,..., n-1}`
-- Demonstrate autocompletion
example (f : ℕ → ℝ) (n : ℕ) :
57 + ∑ i in range (n+1), f i = 57 + f n + ∑ i in range n, f i :=
begin
sorry
end
/-! ## How to find things (jump to definition)
Another good strategy for finding useful results about `X`,
is to “jump to the definition” and scroll through the next 3 screens of lemmas.
If you are looking for a basic fact about `X`, you will usually find it there.
-/
-- demonstrate “jump to definition”
#check polynomial.coeff
/-! ## Exercise 1
We will warm up with a well-known result:
“Subgroups of abelian groups are normal.”
Hints for proving this result:
* Notice that `normal` is a structure,
which you can see by going to the definition.
The `constructor` tactic will help you to get started.
-/
namespace add_subgroup
variables {A : Type*} [add_comm_group A]
lemma normal_of_add_comm_group (H : add_subgroup A) : normal H :=
begin
-- sorry
constructor,
intros x hx y,
simpa,
-- sorry
end
end add_subgroup
/-! ## Exercise 2
The following exercise will show the classical fact:
“Finite field extensions are algebraic.”
Hints for proving this result:
* Look up the definition of `finite_dimensional`.
* Search the library for useful lemmas about `is_algebraic` and `is_integral`.
-/
namespace algebra
variables {K L : Type*} [field K] [field L] [algebra K L] [finite_dimensional K L]
lemma is_algebraic_of_finite_dimensional : is_algebraic K L :=
begin
-- sorry
intro x,
rw is_algebraic_iff_is_integral,
apply is_integral_of_noetherian,
assumption,
-- sorry
end
end algebra
/-! ## Exercise 3
In this exercise we will define the Frobenius morphism.
-/
section
variables (p : ℕ) [fact p.prime]
variables (K : Type*) [field K] [char_p K p]
/-! ### Subchallenge -/
lemma add_pow_char' (x y : K) : (x + y) ^ p = x ^ p + y ^ p :=
begin
-- Hint: `add_pow_char` already exists.
-- You can use it if you don't want to spend time on this.
/- Hints if you do want to attempt this:
* `finset.sum_range_succ`
* `finset.sum_eq_single`
* `nat.prime.ne_zero`
* `char_p.cast_eq_zero_iff`
* `nat.prime.dvd_choose_self`
-/
-- sorry
rw add_pow,
rw sum_range_succ,
simp only [nat.choose_self, mul_one, nat.sub_self, nat.cast_one, add_right_inj, pow_zero],
rw sum_eq_single 0,
{ simp only [mul_one, one_mul, nat.choose_zero_right, nat.sub_zero, nat.cast_one, pow_zero], },
{ intros i hi hi0,
convert mul_zero _,
rw char_p.cast_eq_zero_iff K p,
apply nat.prime.dvd_choose_self _ _ (by assumption),
{ rwa nat.pos_iff_ne_zero, },
{ simpa using hi } },
{ intro h,
simp only [le_zero_iff_eq, mem_range, not_lt] at h,
exfalso,
apply nat.prime.ne_zero _ h, assumption },
-- sorry
end
def frobenius_hom : K →+* K :=
{ to_fun := λ x, x^p,
map_zero' :=
begin
-- Hint: `zero_pow`, search for lemmas near `nat.prime`
-- sorry
rw zero_pow,
apply nat.prime.pos,
assumption,
-- sorry
end,
map_one' :=
begin
-- sorry
simp,
-- sorry
end,
map_mul' :=
begin
-- sorry
intros x y,
rw mul_pow,
-- sorry
end,
map_add' :=
begin
-- Hint: `add_pow_char` -- can you prove that one yourself?
-- sorry
intros x y,
rw add_pow_char',
-- sorry
end }
end
/-! ## Exercise 4 [challenging]
The next exercise asks to show that a monic polynomial `f ∈ ℤ[X]` is irreducible
if it is irreducible modulo a prime `p`.
This fact is also not in mathlib.
Hint: prove the helper lemma that is stated first.
Follow-up question:
Can you generalise `irreducible_of_irreducible_mod_prime`?
-/
namespace polynomial
variables {R S : Type*} [semiring R] [integral_domain S] (φ : R →+* S)
/-
Useful library lemmas (in no particular order):
- `degree_eq_zero_of_is_unit`
- `eq_C_of_degree_eq_zero`
- `is_unit.map'`
- `leading_coeff_C`
- `degree_map_eq_of_leading_coeff_ne_zero`
- `is_unit.map'`
- `is_unit.ne_zero`
-/
lemma is_unit_of_is_unit_leading_coeff_of_is_unit_map'
(f : polynomial R) (hf : is_unit (leading_coeff f)) (H : is_unit (map φ f)) :
is_unit f :=
begin
-- sorry
have key := degree_eq_zero_of_is_unit H,
have hφ_lcf : φ (leading_coeff f) ≠ 0,
{ apply is_unit.ne_zero,
apply is_unit.map',
assumption, },
rw degree_map_eq_of_leading_coeff_ne_zero _ hφ_lcf at key,
rw eq_C_of_degree_eq_zero key,
apply is_unit.map',
rw [eq_C_of_degree_eq_zero key, leading_coeff_C] at hf,
exact hf,
-- sorry
end
/-
Useful library lemmas (in no particular order):
- `is_unit.map'`
- `is_unit_of_mul_is_unit_left` (also `_right`)
- `leading_coeff_mul`
- `is_unit_of_is_unit_leading_coeff_of_is_unit_map` (the helper lemma we just proved)
- `is_unit_one`
-/
lemma irreducible_of_irreducible_mod_prime (f : polynomial ℤ) (p : ℕ) [fact p.prime]
(h_mon : monic f) (h_irr : irreducible (map (int.cast_ring_hom (zmod p)) f)) :
irreducible f :=
begin
-- sorry
split,
{ intro hf,
apply h_irr.1,
apply is_unit.map',
exact hf, },
{ intros g h Hf,
have aux : is_unit (leading_coeff g * leading_coeff h),
{ rw [← leading_coeff_mul, ← Hf, h_mon.leading_coeff], exact is_unit_one, },
have lc_g_unit : is_unit (leading_coeff g),
{ apply is_unit_of_mul_is_unit_left aux, },
have lc_h_unit : is_unit (leading_coeff h),
{ apply is_unit_of_mul_is_unit_right aux, },
rw Hf at h_irr,
simp at h_irr,
have key_fact := h_irr.2 _ _ rfl,
cases key_fact with Hg Hh,
{ left,
apply is_unit_of_is_unit_leading_coeff_of_is_unit_map _ g lc_g_unit Hg, },
{ right,
apply is_unit_of_is_unit_leading_coeff_of_is_unit_map _ h lc_h_unit Hh, } }
-- sorry
end
end polynomial
-- SCROLL DOWN FOR THE BONUS EXERCISE
section
/-! ## Bonus exercise (wicked hard) -/
noncomputable theory -- because `polynomial` is noncomputable (implementation detail)
open polynomial -- we want to write `X`, instead of `polynomial.X`
/-
First we make some definitions
Scroll to the end for the actual exercise
-/
def partial_ramanujan_tau_polynomial (n : ℕ) : polynomial ℤ :=
X * ∏ k in finset.Ico 1 n, (1 - X^k)^24
def ramanujan_tau (n : ℕ) : ℤ :=
coeff (partial_ramanujan_tau_polynomial n) n
-- Some nice suggestive notation
prefix `τ`:300 := ramanujan_tau
/-
Some lemmas to warm up
Hint: unfold definitions, `simp`
-/
example : τ 0 = 0 :=
begin
-- sorry
simp [ramanujan_tau, partial_ramanujan_tau_polynomial],
-- sorry
end
example : τ 1 = 1 :=
begin
-- sorry
simp [ramanujan_tau, partial_ramanujan_tau_polynomial],
-- sorry
end
-- This one is nontrivial
-- Use `have : subresult,` or state helper lemmas and prove them first!
example : τ 2 = -24 :=
begin
-- Really, we ought to have a tactic that makes this easy
delta ramanujan_tau partial_ramanujan_tau_polynomial,
rw [mul_comm, coeff_mul_X],
suffices : ((1 - X) ^ 24 : polynomial ℤ).coeff 1 = -(24 : ℕ), by simpa,
generalize : (24 : ℕ) = n,
-- sorry
induction n with n ih, { apply coeff_one },
rw [pow_succ, sub_mul, one_mul, mul_comm X, coeff_sub, coeff_mul_X],
rw ih,
suffices : ((1 - X) ^ n : polynomial ℤ).coeff 0 = 1,
{ rw [this, sub_eq_add_neg, add_comm], simp, },
clear ih,
induction n with n ih, { simp, },
rw [pow_succ, sub_mul, one_mul, coeff_sub],
rw ih,
rw coeff_mul,
simp,
-- sorry
end
/-
The actual exercise. Good luck (-;
-/
theorem deligne (p : ℕ) (hp : p.prime) : (abs (τ p) : ℝ) ≤ 2 * p^(11/2) :=
begin
-- sorry
-- I did not even start this proof
sorry
-- sorry
end
end
|
d10dcde0151116bfb275aef89854c266695e9565 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/category_theory/isomorphism.lean | 70978f47d7a571de07a5b07dd959aa01b879d54c | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 7,873 | 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
import category_theory.functor
universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation
namespace category_theory
structure iso {C : Sort u} [category.{v} C] (X Y : C) :=
(hom : X ⟶ Y)
(inv : Y ⟶ X)
(hom_inv_id' : hom ≫ inv = 𝟙 X . obviously)
(inv_hom_id' : inv ≫ hom = 𝟙 Y . obviously)
restate_axiom iso.hom_inv_id'
restate_axiom iso.inv_hom_id'
attribute [simp] iso.hom_inv_id iso.inv_hom_id
infixr ` ≅ `:10 := iso -- type as \cong or \iso
variables {C : Sort u} [𝒞 : category.{v} C]
include 𝒞
variables {X Y Z : C}
namespace iso
@[simp] lemma hom_inv_id_assoc (α : X ≅ Y) (f : X ⟶ Z) : α.hom ≫ α.inv ≫ f = f :=
by rw [←category.assoc, α.hom_inv_id, category.id_comp]
@[simp] lemma inv_hom_id_assoc (α : X ≅ Y) (f : Y ⟶ Z) : α.inv ≫ α.hom ≫ f = f :=
by rw [←category.assoc, α.inv_hom_id, category.id_comp]
@[extensionality] lemma ext (α β : X ≅ Y) (w : α.hom = β.hom) : α = β :=
suffices α.inv = β.inv, by cases α; cases β; cc,
calc α.inv
= α.inv ≫ (β.hom ≫ β.inv) : by rw [iso.hom_inv_id, category.comp_id]
... = (α.inv ≫ α.hom) ≫ β.inv : by rw [category.assoc, ←w]
... = β.inv : by rw [iso.inv_hom_id, category.id_comp]
@[symm] def symm (I : X ≅ Y) : Y ≅ X :=
{ hom := I.inv,
inv := I.hom,
hom_inv_id' := I.inv_hom_id',
inv_hom_id' := I.hom_inv_id' }
@[simp] lemma symm_hom (α : X ≅ Y) : α.symm.hom = α.inv := rfl
@[simp] lemma symm_inv (α : X ≅ Y) : α.symm.inv = α.hom := rfl
@[simp] lemma symm_mk {X Y : C} (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id) (inv_hom_id) :
iso.symm {hom := hom, inv := inv, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id} =
{hom := inv, inv := hom, hom_inv_id' := inv_hom_id, inv_hom_id' := hom_inv_id} := rfl
@[refl] def refl (X : C) : X ≅ X :=
{ hom := 𝟙 X,
inv := 𝟙 X }
@[simp] lemma refl_hom (X : C) : (iso.refl X).hom = 𝟙 X := rfl
@[simp] lemma refl_inv (X : C) : (iso.refl X).inv = 𝟙 X := rfl
@[trans] def trans (α : X ≅ Y) (β : Y ≅ Z) : X ≅ Z :=
{ hom := α.hom ≫ β.hom,
inv := β.inv ≫ α.inv }
infixr ` ≪≫ `:80 := iso.trans -- type as `\ll \gg`.
@[simp] lemma trans_hom (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).hom = α.hom ≫ β.hom := rfl
@[simp] lemma trans_inv (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).inv = β.inv ≫ α.inv := rfl
@[simp] lemma trans_mk {X Y Z : C}
(hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id) (inv_hom_id)
(hom' : Y ⟶ Z) (inv' : Z ⟶ Y) (hom_inv_id') (inv_hom_id') (hom_inv_id'') (inv_hom_id'') :
iso.trans
{hom := hom, inv := inv, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id}
{hom := hom', inv := inv', hom_inv_id' := hom_inv_id', inv_hom_id' := inv_hom_id'} =
{hom := hom ≫ hom', inv := inv' ≫ inv, hom_inv_id' := hom_inv_id'', inv_hom_id' := inv_hom_id''} :=
rfl
@[simp] lemma refl_symm (X : C) : (iso.refl X).hom = 𝟙 X := rfl
@[simp] lemma trans_symm (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).inv = β.inv ≫ α.inv := rfl
lemma inv_comp_eq (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : α.inv ≫ f = g ↔ f = α.hom ≫ g :=
⟨λ H, by simp [H.symm], λ H, by simp [H]⟩
lemma eq_inv_comp (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : g = α.inv ≫ f ↔ α.hom ≫ g = f :=
(inv_comp_eq α.symm).symm
lemma comp_inv_eq (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : f ≫ α.inv = g ↔ f = g ≫ α.hom :=
⟨λ H, by simp [H.symm], λ H, by simp [H]⟩
lemma eq_comp_inv (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : g = f ≫ α.inv ↔ g ≫ α.hom = f :=
(comp_inv_eq α.symm).symm
end iso
/-- `is_iso` typeclass expressing that a morphism is invertible.
This contains the data of the inverse, but is a subsingleton type. -/
class is_iso (f : X ⟶ Y) :=
(inv : Y ⟶ X)
(hom_inv_id' : f ≫ inv = 𝟙 X . obviously)
(inv_hom_id' : inv ≫ f = 𝟙 Y . obviously)
def inv (f : X ⟶ Y) [is_iso f] := is_iso.inv f
namespace is_iso
@[simp] lemma hom_inv_id (f : X ⟶ Y) [is_iso f] : f ≫ category_theory.inv f = 𝟙 X :=
is_iso.hom_inv_id' f
@[simp] lemma inv_hom_id (f : X ⟶ Y) [is_iso f] : category_theory.inv f ≫ f = 𝟙 Y :=
is_iso.inv_hom_id' f
@[simp] lemma hom_inv_id_assoc {Z} (f : X ⟶ Y) [is_iso f] (g : X ⟶ Z) : f ≫ category_theory.inv f ≫ g = g :=
by rw [←category.assoc, hom_inv_id, category.id_comp]
@[simp] lemma inv_hom_id_assoc {Z} (f : X ⟶ Y) [is_iso f] (g : Y ⟶ Z) : category_theory.inv f ≫ f ≫ g = g :=
by rw [←category.assoc, inv_hom_id, category.id_comp]
instance (X : C) : is_iso (𝟙 X) :=
{ inv := 𝟙 X }
instance of_iso (f : X ≅ Y) : is_iso f.hom :=
{ inv := f.inv }
instance of_iso_inverse (f : X ≅ Y) : is_iso f.inv :=
{ inv := f.hom }
end is_iso
def as_iso (f : X ⟶ Y) [is_iso f] : X ≅ Y :=
{ hom := f, inv := inv f }
@[simp] lemma as_iso_hom (f : X ⟶ Y) [is_iso f] : (as_iso f).hom = f := rfl
@[simp] lemma as_iso_inv (f : X ⟶ Y) [is_iso f] : (as_iso f).inv = inv f := rfl
instance (f : X ⟶ Y) : subsingleton (is_iso f) :=
⟨λ a b,
suffices a.inv = b.inv, by cases a; cases b; congr; exact this,
show (@as_iso C _ _ _ f a).inv = (@as_iso C _ _ _ f b).inv,
by congr' 1; ext; refl⟩
namespace functor
universes u₁ v₁ u₂ v₂
variables {D : Sort u₂}
variables [𝒟 : category.{v₂} D]
include 𝒟
def map_iso (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : F.obj X ≅ F.obj Y :=
{ hom := F.map i.hom,
inv := F.map i.inv,
hom_inv_id' := by rw [←map_comp, iso.hom_inv_id, ←map_id],
inv_hom_id' := by rw [←map_comp, iso.inv_hom_id, ←map_id] }
@[simp] lemma map_iso_hom (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : (F.map_iso i).hom = F.map i.hom := rfl
@[simp] lemma map_iso_inv (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : (F.map_iso i).inv = F.map i.inv := rfl
instance (F : C ⥤ D) (f : X ⟶ Y) [is_iso f] : is_iso (F.map f) :=
{ inv := F.map (inv f),
hom_inv_id' := by rw [← F.map_comp, is_iso.hom_inv_id, map_id],
inv_hom_id' := by rw [← F.map_comp, is_iso.inv_hom_id, map_id] }
@[simp] lemma map_hom_inv (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] :
F.map f ≫ F.map (inv f) = 𝟙 (F.obj X) :=
begin
rw [←map_comp, is_iso.hom_inv_id, map_id],
end
@[simp] lemma map_inv_hom (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] :
F.map (inv f) ≫ F.map f = 𝟙 (F.obj Y) :=
begin
rw [←map_comp, is_iso.inv_hom_id, map_id],
end
end functor
instance epi_of_iso (f : X ⟶ Y) [is_iso f] : epi f :=
{ left_cancellation := begin
-- This is an interesting test case for better rewrite automation.
intros,
rw [←category.id_comp C g, ←category.id_comp C h],
rw [← is_iso.inv_hom_id f],
rw [category.assoc, w, category.assoc],
end }
instance mono_of_iso (f : X ⟶ Y) [is_iso f] : mono f :=
{ right_cancellation := begin
intros,
rw [←category.comp_id C g, ←category.comp_id C h],
rw [← is_iso.hom_inv_id f],
rw [←category.assoc, w, ←category.assoc]
end }
end category_theory
namespace category_theory
-- We need to get the morphism universe level up into `Type`, in order to have group structures.
variables {C : Sort u} [𝒞 : category.{v+1} C]
include 𝒞
def Aut (X : C) := X ≅ X
attribute [extensionality Aut] iso.ext
instance {X : C} : group (Aut X) :=
by refine { one := iso.refl X,
inv := iso.symm,
mul := iso.trans, .. } ; obviously
end category_theory
|
9cdfae842f1173cc28c83f96ab204b63d07e12b2 | 315b4184091c669ce8e5e07f9b24473c4bcfbaaf | /tests/lean/run/check_constants.lean | 6badec575b3856c6db7c2c5da05897ce561f168c | [
"Apache-2.0"
] | permissive | haraldschilly/lean | 78404910ad4c258cdf84e0509e4348c1525e57a9 | d01e2d7ae8250e8f69139d8cb37950079e76ca9d | refs/heads/master | 1,619,977,395,095 | 1,517,501,044,000 | 1,517,940,670,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,474 | lean | -- DO NOT EDIT, automatically generated file, generator scripts/gen_constants_cpp.py
import smt system.io
open tactic
meta def script_check_id (n : name) : tactic unit :=
do env ← get_env, (env^.get n >> return ()) <|> (guard $ env^.is_namespace n) <|> (attribute.get_instances n >> return ()) <|> fail ("identifier '" ++ to_string n ++ "' is not a constant, namespace nor attribute")
run_cmd script_check_id `abs
run_cmd script_check_id `absurd
run_cmd script_check_id `acc.cases_on
run_cmd script_check_id `acc.rec
run_cmd script_check_id `add_comm_group
run_cmd script_check_id `add_comm_semigroup
run_cmd script_check_id `add_group
run_cmd script_check_id `add_monoid
run_cmd script_check_id `and
run_cmd script_check_id `and.elim_left
run_cmd script_check_id `and.elim_right
run_cmd script_check_id `and.intro
run_cmd script_check_id `and.rec
run_cmd script_check_id `and.cases_on
run_cmd script_check_id `auto_param
run_cmd script_check_id `bit0
run_cmd script_check_id `bit1
run_cmd script_check_id `bin_tree.empty
run_cmd script_check_id `bin_tree.leaf
run_cmd script_check_id `bin_tree.node
run_cmd script_check_id `bool
run_cmd script_check_id `bool.ff
run_cmd script_check_id `bool.tt
run_cmd script_check_id `combinator.K
run_cmd script_check_id `cast
run_cmd script_check_id `cast_heq
run_cmd script_check_id `char
run_cmd script_check_id `char.mk
run_cmd script_check_id `char.ne_of_vne
run_cmd script_check_id `char.of_nat
run_cmd script_check_id `char.of_nat_ne_of_ne
run_cmd script_check_id `is_valid_char_range_1
run_cmd script_check_id `is_valid_char_range_2
run_cmd script_check_id `classical.prop_decidable
run_cmd script_check_id `classical.type_decidable_eq
run_cmd script_check_id `coe
run_cmd script_check_id `coe_fn
run_cmd script_check_id `coe_sort
run_cmd script_check_id `coe_to_lift
run_cmd script_check_id `congr
run_cmd script_check_id `congr_arg
run_cmd script_check_id `congr_fun
run_cmd script_check_id `decidable
run_cmd script_check_id `decidable.to_bool
run_cmd script_check_id `distrib
run_cmd script_check_id `dite
run_cmd script_check_id `empty
run_cmd script_check_id `Exists
run_cmd script_check_id `eq
run_cmd script_check_id `eq.cases_on
run_cmd script_check_id `eq.drec
run_cmd script_check_id `eq.mp
run_cmd script_check_id `eq.mpr
run_cmd script_check_id `eq.rec
run_cmd script_check_id `eq.refl
run_cmd script_check_id `eq.subst
run_cmd script_check_id `eq.symm
run_cmd script_check_id `eq.trans
run_cmd script_check_id `eq_of_heq
run_cmd script_check_id `eq_rec_heq
run_cmd script_check_id `eq_true_intro
run_cmd script_check_id `eq_false_intro
run_cmd script_check_id `eq_self_iff_true
run_cmd script_check_id `expr
run_cmd script_check_id `expr.subst
run_cmd script_check_id `format
run_cmd script_check_id `false
run_cmd script_check_id `false_of_true_iff_false
run_cmd script_check_id `false_of_true_eq_false
run_cmd script_check_id `true_eq_false_of_false
run_cmd script_check_id `false.rec
run_cmd script_check_id `field
run_cmd script_check_id `fin.mk
run_cmd script_check_id `fin.ne_of_vne
run_cmd script_check_id `forall_congr
run_cmd script_check_id `forall_congr_eq
run_cmd script_check_id `forall_not_of_not_exists
run_cmd script_check_id `funext
run_cmd script_check_id `ge
run_cmd script_check_id `gt
run_cmd script_check_id `has_add
run_cmd script_check_id `has_add.add
run_cmd script_check_id `has_andthen.andthen
run_cmd script_check_id `has_bind.and_then
run_cmd script_check_id `has_bind.bind
run_cmd script_check_id `has_bind.seq
run_cmd script_check_id `has_div
run_cmd script_check_id `has_div.div
run_cmd script_check_id `has_emptyc.emptyc
run_cmd script_check_id `has_mod.mod
run_cmd script_check_id `has_mul
run_cmd script_check_id `has_mul.mul
run_cmd script_check_id `has_insert.insert
run_cmd script_check_id `has_inv
run_cmd script_check_id `has_inv.inv
run_cmd script_check_id `has_le
run_cmd script_check_id `has_le.le
run_cmd script_check_id `has_lt
run_cmd script_check_id `has_lt.lt
run_cmd script_check_id `has_neg
run_cmd script_check_id `has_neg.neg
run_cmd script_check_id `has_one
run_cmd script_check_id `has_one.one
run_cmd script_check_id `has_orelse.orelse
run_cmd script_check_id `has_sep.sep
run_cmd script_check_id `has_sizeof
run_cmd script_check_id `has_sizeof.mk
run_cmd script_check_id `has_sub
run_cmd script_check_id `has_sub.sub
run_cmd script_check_id `has_to_format
run_cmd script_check_id `has_repr
run_cmd script_check_id `has_well_founded
run_cmd script_check_id `has_well_founded.r
run_cmd script_check_id `has_well_founded.wf
run_cmd script_check_id `has_zero
run_cmd script_check_id `has_zero.zero
run_cmd script_check_id `has_coe_t
run_cmd script_check_id `heq
run_cmd script_check_id `heq.refl
run_cmd script_check_id `heq.symm
run_cmd script_check_id `heq.trans
run_cmd script_check_id `heq_of_eq
run_cmd script_check_id `hole_command
run_cmd script_check_id `id
run_cmd script_check_id `id_rhs
run_cmd script_check_id `id_delta
run_cmd script_check_id `if_neg
run_cmd script_check_id `if_pos
run_cmd script_check_id `iff
run_cmd script_check_id `iff_false_intro
run_cmd script_check_id `iff.intro
run_cmd script_check_id `iff.mp
run_cmd script_check_id `iff.mpr
run_cmd script_check_id `iff.refl
run_cmd script_check_id `iff.symm
run_cmd script_check_id `iff.trans
run_cmd script_check_id `iff_true_intro
run_cmd script_check_id `imp_congr
run_cmd script_check_id `imp_congr_eq
run_cmd script_check_id `imp_congr_ctx
run_cmd script_check_id `imp_congr_ctx_eq
run_cmd script_check_id `implies
run_cmd script_check_id `implies_of_if_neg
run_cmd script_check_id `implies_of_if_pos
run_cmd script_check_id `int
run_cmd script_check_id `int.has_add
run_cmd script_check_id `int.has_mul
run_cmd script_check_id `int.has_sub
run_cmd script_check_id `int.has_div
run_cmd script_check_id `int.has_le
run_cmd script_check_id `int.has_lt
run_cmd script_check_id `int.has_neg
run_cmd script_check_id `int.has_mod
run_cmd script_check_id `int.bit0_nonneg
run_cmd script_check_id `int.bit1_nonneg
run_cmd script_check_id `int.one_nonneg
run_cmd script_check_id `int.zero_nonneg
run_cmd script_check_id `int.bit0_pos
run_cmd script_check_id `int.bit1_pos
run_cmd script_check_id `int.one_pos
run_cmd script_check_id `int.nat_abs_zero
run_cmd script_check_id `int.nat_abs_one
run_cmd script_check_id `int.nat_abs_bit0_step
run_cmd script_check_id `int.nat_abs_bit1_nonneg_step
run_cmd script_check_id `int.ne_of_nat_ne_nonneg_case
run_cmd script_check_id `int.ne_neg_of_ne
run_cmd script_check_id `int.neg_ne_of_pos
run_cmd script_check_id `int.ne_neg_of_pos
run_cmd script_check_id `int.neg_ne_zero_of_ne
run_cmd script_check_id `int.zero_ne_neg_of_ne
run_cmd script_check_id `int.decidable_linear_ordered_comm_group
run_cmd script_check_id `interactive.param_desc
run_cmd script_check_id `interactive.parse
run_cmd script_check_id `io_core
run_cmd script_check_id `monad_io_impl
run_cmd script_check_id `monad_io_terminal_impl
run_cmd script_check_id `monad_io_file_system_impl
run_cmd script_check_id `monad_io_environment_impl
run_cmd script_check_id `monad_io_process_impl
run_cmd script_check_id `io
run_cmd script_check_id `is_associative
run_cmd script_check_id `is_associative.assoc
run_cmd script_check_id `is_commutative
run_cmd script_check_id `is_commutative.comm
run_cmd script_check_id `ite
run_cmd script_check_id `lean.parser
run_cmd script_check_id `lean.parser.pexpr
run_cmd script_check_id `lean.parser.tk
run_cmd script_check_id `left_distrib
run_cmd script_check_id `left_comm
run_cmd script_check_id `le_refl
run_cmd script_check_id `linear_ordered_ring
run_cmd script_check_id `linear_ordered_semiring
run_cmd script_check_id `list
run_cmd script_check_id `list.nil
run_cmd script_check_id `list.cons
run_cmd script_check_id `match_failed
run_cmd script_check_id `monad
run_cmd script_check_id `monad_fail
run_cmd script_check_id `monoid
run_cmd script_check_id `mul_one
run_cmd script_check_id `mul_zero
run_cmd script_check_id `mul_zero_class
run_cmd script_check_id `name.anonymous
run_cmd script_check_id `name.mk_numeral
run_cmd script_check_id `name.mk_string
run_cmd script_check_id `nat
run_cmd script_check_id `nat.succ
run_cmd script_check_id `nat.zero
run_cmd script_check_id `nat.has_zero
run_cmd script_check_id `nat.has_one
run_cmd script_check_id `nat.has_add
run_cmd script_check_id `nat.add
run_cmd script_check_id `nat.cases_on
run_cmd script_check_id `nat.bit0_ne
run_cmd script_check_id `nat.bit0_ne_bit1
run_cmd script_check_id `nat.bit0_ne_zero
run_cmd script_check_id `nat.bit0_ne_one
run_cmd script_check_id `nat.bit1_ne
run_cmd script_check_id `nat.bit1_ne_bit0
run_cmd script_check_id `nat.bit1_ne_zero
run_cmd script_check_id `nat.bit1_ne_one
run_cmd script_check_id `nat.zero_ne_one
run_cmd script_check_id `nat.zero_ne_bit0
run_cmd script_check_id `nat.zero_ne_bit1
run_cmd script_check_id `nat.one_ne_zero
run_cmd script_check_id `nat.one_ne_bit0
run_cmd script_check_id `nat.one_ne_bit1
run_cmd script_check_id `nat.bit0_lt
run_cmd script_check_id `nat.bit1_lt
run_cmd script_check_id `nat.bit0_lt_bit1
run_cmd script_check_id `nat.bit1_lt_bit0
run_cmd script_check_id `nat.zero_lt_one
run_cmd script_check_id `nat.zero_lt_bit1
run_cmd script_check_id `nat.zero_lt_bit0
run_cmd script_check_id `nat.one_lt_bit0
run_cmd script_check_id `nat.one_lt_bit1
run_cmd script_check_id `nat.le_of_lt
run_cmd script_check_id `nat.le_refl
run_cmd script_check_id `ne
run_cmd script_check_id `neq_of_not_iff
run_cmd script_check_id `norm_num.add1
run_cmd script_check_id `norm_num.add1_bit0
run_cmd script_check_id `norm_num.add1_bit1_helper
run_cmd script_check_id `norm_num.add1_one
run_cmd script_check_id `norm_num.add1_zero
run_cmd script_check_id `norm_num.add_div_helper
run_cmd script_check_id `norm_num.bin_add_zero
run_cmd script_check_id `norm_num.bin_zero_add
run_cmd script_check_id `norm_num.bit0_add_bit0_helper
run_cmd script_check_id `norm_num.bit0_add_bit1_helper
run_cmd script_check_id `norm_num.bit0_add_one
run_cmd script_check_id `norm_num.bit1_add_bit0_helper
run_cmd script_check_id `norm_num.bit1_add_bit1_helper
run_cmd script_check_id `norm_num.bit1_add_one_helper
run_cmd script_check_id `norm_num.div_add_helper
run_cmd script_check_id `norm_num.div_eq_div_helper
run_cmd script_check_id `norm_num.div_helper
run_cmd script_check_id `norm_num.div_mul_helper
run_cmd script_check_id `norm_num.mk_cong
run_cmd script_check_id `norm_num.mul_bit0_helper
run_cmd script_check_id `norm_num.mul_bit1_helper
run_cmd script_check_id `norm_num.mul_div_helper
run_cmd script_check_id `norm_num.neg_add_neg_helper
run_cmd script_check_id `norm_num.neg_add_pos_helper1
run_cmd script_check_id `norm_num.neg_add_pos_helper2
run_cmd script_check_id `norm_num.neg_mul_neg_helper
run_cmd script_check_id `norm_num.neg_mul_pos_helper
run_cmd script_check_id `norm_num.neg_neg_helper
run_cmd script_check_id `norm_num.neg_zero_helper
run_cmd script_check_id `norm_num.nonneg_bit0_helper
run_cmd script_check_id `norm_num.nonneg_bit1_helper
run_cmd script_check_id `norm_num.nonzero_of_div_helper
run_cmd script_check_id `norm_num.nonzero_of_neg_helper
run_cmd script_check_id `norm_num.nonzero_of_pos_helper
run_cmd script_check_id `norm_num.one_add_bit0
run_cmd script_check_id `norm_num.one_add_bit1_helper
run_cmd script_check_id `norm_num.one_add_one
run_cmd script_check_id `norm_num.pos_add_neg_helper
run_cmd script_check_id `norm_num.pos_bit0_helper
run_cmd script_check_id `norm_num.pos_bit1_helper
run_cmd script_check_id `norm_num.pos_mul_neg_helper
run_cmd script_check_id `norm_num.sub_nat_zero_helper
run_cmd script_check_id `norm_num.sub_nat_pos_helper
run_cmd script_check_id `norm_num.subst_into_div
run_cmd script_check_id `norm_num.subst_into_prod
run_cmd script_check_id `norm_num.subst_into_subtr
run_cmd script_check_id `norm_num.subst_into_sum
run_cmd script_check_id `not
run_cmd script_check_id `not_of_iff_false
run_cmd script_check_id `not_of_eq_false
run_cmd script_check_id `of_eq_true
run_cmd script_check_id `of_iff_true
run_cmd script_check_id `opt_param
run_cmd script_check_id `or
run_cmd script_check_id `out_param
run_cmd script_check_id `punit
run_cmd script_check_id `punit.star
run_cmd script_check_id `prod.mk
run_cmd script_check_id `pprod
run_cmd script_check_id `pprod.mk
run_cmd script_check_id `pprod.fst
run_cmd script_check_id `pprod.snd
run_cmd script_check_id `propext
run_cmd script_check_id `to_pexpr
run_cmd script_check_id `quot.mk
run_cmd script_check_id `quot.lift
run_cmd script_check_id `real
run_cmd script_check_id `real.of_int
run_cmd script_check_id `real.to_int
run_cmd script_check_id `real.is_int
run_cmd script_check_id `real.has_neg
run_cmd script_check_id `real.has_div
run_cmd script_check_id `real.has_add
run_cmd script_check_id `real.has_mul
run_cmd script_check_id `real.has_sub
run_cmd script_check_id `real.has_lt
run_cmd script_check_id `real.has_le
run_cmd script_check_id `reflected
run_cmd script_check_id `reflected.subst
run_cmd script_check_id `repr
run_cmd script_check_id `rfl
run_cmd script_check_id `right_distrib
run_cmd script_check_id `ring
run_cmd script_check_id `scope_trace
run_cmd script_check_id `set_of
run_cmd script_check_id `semiring
run_cmd script_check_id `psigma
run_cmd script_check_id `psigma.cases_on
run_cmd script_check_id `psigma.mk
run_cmd script_check_id `psigma.fst
run_cmd script_check_id `psigma.snd
run_cmd script_check_id `singleton
run_cmd script_check_id `sizeof
run_cmd script_check_id `smt.array
run_cmd script_check_id `smt.select
run_cmd script_check_id `smt.store
run_cmd script_check_id `smt.prove
run_cmd script_check_id `string
run_cmd script_check_id `string.empty
run_cmd script_check_id `string.str
run_cmd script_check_id `string.empty_ne_str
run_cmd script_check_id `string.str_ne_empty
run_cmd script_check_id `string.str_ne_str_left
run_cmd script_check_id `string.str_ne_str_right
run_cmd script_check_id `subsingleton
run_cmd script_check_id `subsingleton.elim
run_cmd script_check_id `subsingleton.helim
run_cmd script_check_id `subtype
run_cmd script_check_id `subtype.mk
run_cmd script_check_id `subtype.val
run_cmd script_check_id `subtype.rec
run_cmd script_check_id `psum
run_cmd script_check_id `psum.cases_on
run_cmd script_check_id `psum.inl
run_cmd script_check_id `psum.inr
run_cmd script_check_id `tactic
run_cmd script_check_id `tactic.try
run_cmd script_check_id `tactic.triv
run_cmd script_check_id `tactic.mk_inj_eq
run_cmd script_check_id `thunk
run_cmd script_check_id `to_fmt
run_cmd script_check_id `trans_rel_left
run_cmd script_check_id `trans_rel_right
run_cmd script_check_id `true
run_cmd script_check_id `true.intro
run_cmd script_check_id `unification_hint
run_cmd script_check_id `unification_hint.mk
run_cmd script_check_id `unit
run_cmd script_check_id `unit.cases_on
run_cmd script_check_id `unit.star
run_cmd script_check_id `unsafe_monad_from_pure_bind
run_cmd script_check_id `user_attribute
run_cmd script_check_id `user_attribute.parse_reflect
run_cmd script_check_id `vm_monitor
run_cmd script_check_id `partial_order
run_cmd script_check_id `well_founded.fix
run_cmd script_check_id `well_founded.fix_eq
run_cmd script_check_id `well_founded_tactics
run_cmd script_check_id `well_founded_tactics.default
run_cmd script_check_id `well_founded_tactics.rel_tac
run_cmd script_check_id `well_founded_tactics.dec_tac
run_cmd script_check_id `xor
run_cmd script_check_id `zero_le_one
run_cmd script_check_id `zero_lt_one
run_cmd script_check_id `zero_mul
|
c167099dd96919887deb6e156e46fd129f4773ad | 453dcd7c0d1ef170b0843a81d7d8caedc9741dce | /tactic/replacer.lean | aa3004a0a65d89b3f4094a289c70ed706e1f8fd6 | [
"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 | 2,754 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
A mechanism for defining tactics for use in auto params, whose
meaning is defined incrementally through attributes.
-/
namespace tactic
meta def replacer_attr (ntac : name) : user_attribute :=
{ name := ntac,
descr :=
"Replaces the definition of `" ++ to_string ntac ++ "`. This should be " ++
"applied to a definition with the type `tactic unit`, which will be " ++
"called whenever `" ++ to_string ntac ++ "` is called. The definition " ++
"can optionally have an argument of type `tactic unit` or " ++
"`option (tactic unit)` which refers to the previous definition, if any.",
after_set := some $ λ n _ _, do d ← get_decl n,
monad.unlessb (d.type =ₐ `(tactic unit) ∨
d.type =ₐ `(tactic unit → tactic unit) ∨
d.type =ₐ `(option (tactic unit) → tactic unit)) $
fail format!"incorrect type for @[{ntac}]" }
meta def replacer_core (ntac : name) : list name → tactic unit
| [] := fail ("no implementation defined for " ++ to_string ntac)
| (n::ns) := do d ← get_decl n, let t := d.type,
if t =ₐ `(tactic unit) then
monad.join (mk_const n >>= eval_expr (tactic unit))
else if t =ₐ `(tactic unit → tactic unit) then
do tac ← mk_const n >>= eval_expr (tactic unit → tactic unit),
tac (replacer_core ns)
else if t =ₐ `(option (tactic unit) → tactic unit) then
do tac ← mk_const n >>= eval_expr (option (tactic unit) → tactic unit),
tac (guard (ns ≠ []) >> some (replacer_core ns))
else failed
meta def replacer (ntac : name) : tactic unit :=
attribute.get_instances ntac >>= replacer_core ntac
/-- Define a new replaceable tactic. -/
meta def def_replacer (ntac : name) : tactic unit :=
let nattr := ntac <.> "attr" in do
add_decl $ declaration.defn nattr []
`(user_attribute) `(replacer_attr %%(reflect ntac))
(reducibility_hints.regular 1 tt) ff,
set_basic_attribute `user_attribute nattr tt,
add_decl $ declaration.defn ntac []
`(tactic unit) `(replacer %%(reflect ntac))
(reducibility_hints.regular 1 tt) ff,
add_doc_string ntac $
"The `" ++ to_string ntac ++ "` tactic is a \"replaceable\" " ++
"tactic, which means that its meaning is defined by tactics that " ++
"are defined later with the `@[" ++ to_string ntac ++ "]` attribute. " ++
"It is intended for use with `auto_param`s for structure fields."
open interactive lean.parser
/-- Define a new replaceable tactic. -/
@[user_command] meta def def_replacer_cmd (meta_info : decl_meta_info)
(_ : parse $ tk "def_replacer") : lean.parser unit :=
do ntac ← ident, def_replacer ntac
end tactic
|
9da0dca37fb84d337782bc6c80170b22d54296d2 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/2006.lean | 84340a0b6196e45f7a4146fadc117a3e1d00c993 | [
"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 | lean | /-
|
773438c469ef5b03c9f716d4bfbe0e5a19a414f9 | 32da3d0f92cab08875472ef6cacc1931c2b3eafa | /src/topology/instances/ennreal.lean | 6897853c2a8fec23bf21b8b2de803f54a58ea37c | [
"Apache-2.0"
] | permissive | karthiknadig/mathlib | b6073c3748860bfc9a3e55da86afcddba62dc913 | 33a86cfff12d7f200d0010cd03b95e9b69a6c1a5 | refs/heads/master | 1,676,389,371,851 | 1,610,061,127,000 | 1,610,061,127,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 43,959 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
-/
import topology.instances.nnreal
/-!
# Extended non-negative reals
-/
noncomputable theory
open classical set filter metric
open_locale classical topological_space ennreal nnreal big_operators filter
variables {α : Type*} {β : Type*} {γ : Type*}
namespace ennreal
variables {a b c d : ennreal} {r p q : ℝ≥0}
variables {x y z : ennreal} {ε ε₁ ε₂ : ennreal} {s : set ennreal}
section topological_space
open topological_space
/-- Topology on `ennreal`.
Note: this is different from the `emetric_space` topology. The `emetric_space` topology has
`is_open {⊤}`, while this topology doesn't have singleton elements. -/
instance : topological_space ennreal := preorder.topology ennreal
instance : order_topology ennreal := ⟨rfl⟩
instance : t2_space ennreal := by apply_instance -- short-circuit type class inference
instance : second_countable_topology ennreal :=
⟨⟨⋃q ≥ (0:ℚ), {{a : ennreal | a < nnreal.of_real q}, {a : ennreal | ↑(nnreal.of_real q) < a}},
(countable_encodable _).bUnion $ assume a ha, (countable_singleton _).insert _,
le_antisymm
(le_generate_from $ by simp [or_imp_distrib, is_open_lt', is_open_gt'] {contextual := tt})
(le_generate_from $ λ s h, begin
rcases h with ⟨a, hs | hs⟩;
[ rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ a < nnreal.of_real q}, {b | ↑(nnreal.of_real q) < b},
from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn a b, and_assoc]),
rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ ↑(nnreal.of_real q) < a}, {b | b < ↑(nnreal.of_real q)},
from set.ext (assume b,
by simp [hs, @ennreal.lt_iff_exists_rat_btwn b a, and_comm, and_assoc])];
{ apply is_open_Union, intro q,
apply is_open_Union, intro hq,
exact generate_open.basic _ (mem_bUnion hq.1 $ by simp) }
end)⟩⟩
lemma embedding_coe : embedding (coe : ℝ≥0 → ennreal) :=
⟨⟨begin
refine le_antisymm _ _,
{ rw [@order_topology.topology_eq_generate_intervals ennreal _,
← coinduced_le_iff_le_induced],
refine le_generate_from (assume s ha, _),
rcases ha with ⟨a, rfl | rfl⟩,
show is_open {b : ℝ≥0 | a < ↑b},
{ cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] },
show is_open {b : ℝ≥0 | ↑b < a},
{ cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } },
{ rw [@order_topology.topology_eq_generate_intervals ℝ≥0 _],
refine le_generate_from (assume s ha, _),
rcases ha with ⟨a, rfl | rfl⟩,
exact ⟨Ioi a, is_open_Ioi, by simp [Ioi]⟩,
exact ⟨Iio a, is_open_Iio, by simp [Iio]⟩ }
end⟩,
assume a b, coe_eq_coe.1⟩
lemma is_open_ne_top : is_open {a : ennreal | a ≠ ⊤} := is_open_ne
lemma is_open_Ico_zero : is_open (Ico 0 b) := by { rw ennreal.Ico_eq_Iio, exact is_open_Iio}
lemma coe_range_mem_nhds : range (coe : ℝ≥0 → ennreal) ∈ 𝓝 (r : ennreal) :=
have {a : ennreal | a ≠ ⊤} = range (coe : ℝ≥0 → ennreal),
from set.ext $ assume a, by cases a; simp [none_eq_top, some_eq_coe],
this ▸ mem_nhds_sets is_open_ne_top coe_ne_top
@[norm_cast] lemma tendsto_coe {f : filter α} {m : α → ℝ≥0} {a : ℝ≥0} :
tendsto (λa, (m a : ennreal)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) :=
embedding_coe.tendsto_nhds_iff.symm
lemma continuous_coe : continuous (coe : ℝ≥0 → ennreal) :=
embedding_coe.continuous
lemma continuous_coe_iff {α} [topological_space α] {f : α → ℝ≥0} :
continuous (λa, (f a : ennreal)) ↔ continuous f :=
embedding_coe.continuous_iff.symm
lemma nhds_coe {r : ℝ≥0} : 𝓝 (r : ennreal) = (𝓝 r).map coe :=
by rw [embedding_coe.induced, map_nhds_induced_eq coe_range_mem_nhds]
lemma nhds_coe_coe {r p : ℝ≥0} : 𝓝 ((r : ennreal), (p : ennreal)) =
(𝓝 (r, p)).map (λp:ℝ≥0×ℝ≥0, (p.1, p.2)) :=
begin
rw [(embedding_coe.prod_mk embedding_coe).map_nhds_eq],
rw [← prod_range_range_eq],
exact prod_mem_nhds_sets coe_range_mem_nhds coe_range_mem_nhds
end
lemma continuous_of_real : continuous ennreal.of_real :=
(continuous_coe_iff.2 continuous_id).comp nnreal.continuous_of_real
lemma tendsto_of_real {f : filter α} {m : α → ℝ} {a : ℝ} (h : tendsto m f (𝓝 a)) :
tendsto (λa, ennreal.of_real (m a)) f (𝓝 (ennreal.of_real a)) :=
tendsto.comp (continuous.tendsto continuous_of_real _) h
lemma tendsto_to_nnreal {a : ennreal} : a ≠ ⊤ →
tendsto (ennreal.to_nnreal) (𝓝 a) (𝓝 a.to_nnreal) :=
begin
cases a; simp [some_eq_coe, none_eq_top, nhds_coe, tendsto_map'_iff, (∘)],
exact tendsto_id
end
lemma continuous_on_to_nnreal : continuous_on ennreal.to_nnreal {a | a ≠ ∞} :=
continuous_on_iff_continuous_restrict.2 $ continuous_iff_continuous_at.2 $ λ x,
(tendsto_to_nnreal x.2).comp continuous_at_subtype_coe
lemma tendsto_to_real {a : ennreal} : a ≠ ⊤ → tendsto (ennreal.to_real) (𝓝 a) (𝓝 a.to_real) :=
λ ha, tendsto.comp ((@nnreal.tendsto_coe _ (𝓝 a.to_nnreal) id (a.to_nnreal)).2 tendsto_id)
(tendsto_to_nnreal ha)
/-- The set of finite `ennreal` numbers is homeomorphic to `ℝ≥0`. -/
def ne_top_homeomorph_nnreal : {a | a ≠ ∞} ≃ₜ ℝ≥0 :=
{ continuous_to_fun := continuous_on_iff_continuous_restrict.1 continuous_on_to_nnreal,
continuous_inv_fun := continuous_subtype_mk _ continuous_coe,
.. ne_top_equiv_nnreal }
/-- The set of finite `ennreal` numbers is homeomorphic to `ℝ≥0`. -/
def lt_top_homeomorph_nnreal : {a | a < ∞} ≃ₜ ℝ≥0 :=
by refine (homeomorph.set_congr $ set.ext $ λ x, _).trans ne_top_homeomorph_nnreal;
simp only [mem_set_of_eq, lt_top_iff_ne_top]
lemma nhds_top : 𝓝 ∞ = ⨅ a ≠ ∞, 𝓟 (Ioi a) :=
nhds_top_order.trans $ by simp [lt_top_iff_ne_top, Ioi]
lemma nhds_top' : 𝓝 ∞ = ⨅ r : ℝ≥0, 𝓟 (Ioi r) :=
nhds_top.trans $ infi_ne_top _
lemma tendsto_nhds_top_iff_nnreal {m : α → ennreal} {f : filter α} :
tendsto m f (𝓝 ⊤) ↔ ∀ x : ℝ≥0, ∀ᶠ a in f, ↑x < m a :=
by simp only [nhds_top', tendsto_infi, tendsto_principal, mem_Ioi]
lemma tendsto_nhds_top_iff_nat {m : α → ennreal} {f : filter α} :
tendsto m f (𝓝 ⊤) ↔ ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a :=
tendsto_nhds_top_iff_nnreal.trans ⟨λ h n, by simpa only [ennreal.coe_nat] using h n,
λ h x, let ⟨n, hn⟩ := exists_nat_gt x in
(h n).mono (λ y, lt_trans $ by rwa [← ennreal.coe_nat, coe_lt_coe])⟩
lemma tendsto_nhds_top {m : α → ennreal} {f : filter α}
(h : ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a) : tendsto m f (𝓝 ⊤) :=
tendsto_nhds_top_iff_nat.2 h
lemma tendsto_nat_nhds_top : tendsto (λ n : ℕ, ↑n) at_top (𝓝 ∞) :=
tendsto_nhds_top $ λ n, mem_at_top_sets.2
⟨n+1, λ m hm, ennreal.coe_nat_lt_coe_nat.2 $ nat.lt_of_succ_le hm⟩
@[simp, norm_cast] lemma tendsto_coe_nhds_top {f : α → ℝ≥0} {l : filter α} :
tendsto (λ x, (f x : ennreal)) l (𝓝 ∞) ↔ tendsto f l at_top :=
by rw [tendsto_nhds_top_iff_nnreal, at_top_basis_Ioi.tendsto_right_iff];
[simp, apply_instance, apply_instance]
lemma nhds_zero : 𝓝 (0 : ennreal) = ⨅a ≠ 0, 𝓟 (Iio a) :=
nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot, Iio]
-- using Icc because
-- • don't have 'Ioo (x - ε) (x + ε) ∈ 𝓝 x' unless x > 0
-- • (x - y ≤ ε ↔ x ≤ ε + y) is true, while (x - y < ε ↔ x < ε + y) is not
lemma Icc_mem_nhds : x ≠ ⊤ → 0 < ε → Icc (x - ε) (x + ε) ∈ 𝓝 x :=
begin
assume xt ε0, rw mem_nhds_sets_iff,
by_cases x0 : x = 0,
{ use Iio (x + ε),
have : Iio (x + ε) ⊆ Icc (x - ε) (x + ε), assume a, rw x0, simpa using le_of_lt,
use this, exact ⟨is_open_Iio, mem_Iio_self_add xt ε0⟩ },
{ use Ioo (x - ε) (x + ε), use Ioo_subset_Icc_self,
exact ⟨is_open_Ioo, mem_Ioo_self_sub_add xt x0 ε0 ε0 ⟩ }
end
lemma nhds_of_ne_top : x ≠ ⊤ → 𝓝 x = ⨅ε > 0, 𝓟 (Icc (x - ε) (x + ε)) :=
begin
assume xt, refine le_antisymm _ _,
-- first direction
simp only [le_infi_iff, le_principal_iff], assume ε ε0, exact Icc_mem_nhds xt ε0,
-- second direction
rw nhds_generate_from, refine le_infi (assume s, le_infi $ assume hs, _),
simp only [mem_set_of_eq] at hs, rcases hs with ⟨xs, ⟨a, ha⟩⟩,
cases ha,
{ rw ha at *,
rcases exists_between xs with ⟨b, ⟨ab, bx⟩⟩,
have xb_pos : x - b > 0 := zero_lt_sub_iff_lt.2 bx,
have xxb : x - (x - b) = b := sub_sub_cancel (by rwa lt_top_iff_ne_top) (le_of_lt bx),
refine infi_le_of_le (x - b) (infi_le_of_le xb_pos _),
simp only [mem_principal_sets, le_principal_iff],
assume y, rintros ⟨h₁, h₂⟩, rw xxb at h₁, calc a < b : ab ... ≤ y : h₁ },
{ rw ha at *,
rcases exists_between xs with ⟨b, ⟨xb, ba⟩⟩,
have bx_pos : b - x > 0 := zero_lt_sub_iff_lt.2 xb,
have xbx : x + (b - x) = b := add_sub_cancel_of_le (le_of_lt xb),
refine infi_le_of_le (b - x) (infi_le_of_le bx_pos _),
simp only [mem_principal_sets, le_principal_iff],
assume y, rintros ⟨h₁, h₂⟩, rw xbx at h₂, calc y ≤ b : h₂ ... < a : ba },
end
/-- Characterization of neighborhoods for `ennreal` numbers. See also `tendsto_order`
for a version with strict inequalities. -/
protected theorem tendsto_nhds {f : filter α} {u : α → ennreal} {a : ennreal} (ha : a ≠ ⊤) :
tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, (u x) ∈ Icc (a - ε) (a + ε) :=
by simp only [nhds_of_ne_top ha, tendsto_infi, tendsto_principal, mem_Icc]
protected lemma tendsto_at_top [nonempty β] [semilattice_sup β] {f : β → ennreal} {a : ennreal}
(ha : a ≠ ⊤) : tendsto f at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, (f n) ∈ Icc (a - ε) (a + ε) :=
by simp only [ennreal.tendsto_nhds ha, mem_at_top_sets, mem_set_of_eq, filter.eventually]
instance : has_continuous_add ennreal :=
begin
refine ⟨continuous_iff_continuous_at.2 _⟩,
rintro ⟨(_|a), b⟩,
{ exact tendsto_nhds_top_mono' continuous_at_fst (λ p, le_add_right le_rfl) },
rcases b with (_|b),
{ exact tendsto_nhds_top_mono' continuous_at_snd (λ p, le_add_left le_rfl) },
simp only [continuous_at, some_eq_coe, nhds_coe_coe, ← coe_add, tendsto_map'_iff, (∘),
tendsto_coe, tendsto_add]
end
protected lemma tendsto_mul (ha : a ≠ 0 ∨ b ≠ ⊤) (hb : b ≠ 0 ∨ a ≠ ⊤) :
tendsto (λp:ennreal×ennreal, p.1 * p.2) (𝓝 (a, b)) (𝓝 (a * b)) :=
have ht : ∀b:ennreal, b ≠ 0 → tendsto (λp:ennreal×ennreal, p.1 * p.2) (𝓝 ((⊤:ennreal), b)) (𝓝 ⊤),
begin
refine assume b hb, tendsto_nhds_top_iff_nnreal.2 $ assume n, _,
rcases lt_iff_exists_nnreal_btwn.1 (zero_lt_iff_ne_zero.2 hb) with ⟨ε, hε, hεb⟩,
replace hε : 0 < ε, from coe_pos.1 hε,
filter_upwards [prod_mem_nhds_sets (lt_mem_nhds $ @coe_lt_top (n / ε)) (lt_mem_nhds hεb)],
rintros ⟨a₁, a₂⟩ ⟨h₁, h₂⟩,
dsimp at h₁ h₂ ⊢,
rw [← div_mul_cancel n hε.ne', coe_mul],
exact mul_lt_mul h₁ h₂
end,
begin
cases a, {simp [none_eq_top] at hb, simp [none_eq_top, ht b hb, top_mul, hb] },
cases b, {
simp [none_eq_top] at ha,
simp [*, nhds_swap (a : ennreal) ⊤, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘),
mul_comm] },
simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)],
simp only [coe_mul.symm, tendsto_coe, tendsto_mul]
end
protected lemma tendsto.mul {f : filter α} {ma : α → ennreal} {mb : α → ennreal} {a b : ennreal}
(hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) :
tendsto (λa, ma a * mb a) f (𝓝 (a * b)) :=
show tendsto ((λp:ennreal×ennreal, p.1 * p.2) ∘ (λa, (ma a, mb a))) f (𝓝 (a * b)), from
tendsto.comp (ennreal.tendsto_mul ha hb) (hma.prod_mk_nhds hmb)
protected lemma tendsto.const_mul {f : filter α} {m : α → ennreal} {a b : ennreal}
(hm : tendsto m f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λb, a * m b) f (𝓝 (a * b)) :=
by_cases
(assume : a = 0, by simp [this, tendsto_const_nhds])
(assume ha : a ≠ 0, ennreal.tendsto.mul tendsto_const_nhds (or.inl ha) hm hb)
protected lemma tendsto.mul_const {f : filter α} {m : α → ennreal} {a b : ennreal}
(hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) : tendsto (λx, m x * b) f (𝓝 (a * b)) :=
by simpa only [mul_comm] using ennreal.tendsto.const_mul hm ha
protected lemma continuous_at_const_mul {a b : ennreal} (h : a ≠ ⊤ ∨ b ≠ 0) :
continuous_at ((*) a) b :=
tendsto.const_mul tendsto_id h.symm
protected lemma continuous_at_mul_const {a b : ennreal} (h : a ≠ ⊤ ∨ b ≠ 0) :
continuous_at (λ x, x * a) b :=
tendsto.mul_const tendsto_id h.symm
protected lemma continuous_const_mul {a : ennreal} (ha : a ≠ ⊤) : continuous ((*) a) :=
continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_const_mul (or.inl ha)
protected lemma continuous_mul_const {a : ennreal} (ha : a ≠ ⊤) : continuous (λ x, x * a) :=
continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_mul_const (or.inl ha)
lemma le_of_forall_lt_one_mul_le {x y : ennreal} (h : ∀ a < 1, a * x ≤ y) : x ≤ y :=
begin
have : tendsto (* x) (𝓝[Iio 1] 1) (𝓝 (1 * x)) :=
(ennreal.continuous_at_mul_const (or.inr one_ne_zero)).mono_left inf_le_left,
rw one_mul at this,
haveI : (𝓝[Iio 1] (1 : ennreal)).ne_bot := nhds_within_Iio_self_ne_bot' ennreal.zero_lt_one,
exact le_of_tendsto this (eventually_nhds_within_iff.2 $ eventually_of_forall h)
end
lemma infi_mul_left {ι} [nonempty ι] {f : ι → ennreal} {a : ennreal}
(h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) :
(⨅ i, a * f i) = a * ⨅ i, f i :=
begin
by_cases H : a = ⊤ ∧ (⨅ i, f i) = 0,
{ rcases h H.1 H.2 with ⟨i, hi⟩,
rw [H.2, mul_zero, ← bot_eq_zero, infi_eq_bot],
exact λ b hb, ⟨i, by rwa [hi, mul_zero, ← bot_eq_zero]⟩ },
{ rw not_and_distrib at H,
exact (map_infi_of_continuous_at_of_monotone' (ennreal.continuous_at_const_mul H)
ennreal.mul_left_mono).symm }
end
lemma infi_mul_right {ι} [nonempty ι] {f : ι → ennreal} {a : ennreal}
(h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) :
(⨅ i, f i * a) = (⨅ i, f i) * a :=
by simpa only [mul_comm a] using infi_mul_left h
protected lemma continuous_inv : continuous (has_inv.inv : ennreal → ennreal) :=
continuous_iff_continuous_at.2 $ λ a, tendsto_order.2
⟨begin
assume b hb,
simp only [@ennreal.lt_inv_iff_lt_inv b],
exact gt_mem_nhds (ennreal.lt_inv_iff_lt_inv.1 hb),
end,
begin
assume b hb,
simp only [gt_iff_lt, @ennreal.inv_lt_iff_inv_lt _ b],
exact lt_mem_nhds (ennreal.inv_lt_iff_inv_lt.1 hb)
end⟩
@[simp] protected lemma tendsto_inv_iff {f : filter α} {m : α → ennreal} {a : ennreal} :
tendsto (λ x, (m x)⁻¹) f (𝓝 a⁻¹) ↔ tendsto m f (𝓝 a) :=
⟨λ h, by simpa only [function.comp, ennreal.inv_inv]
using (ennreal.continuous_inv.tendsto a⁻¹).comp h,
(ennreal.continuous_inv.tendsto a).comp⟩
protected lemma tendsto.div {f : filter α} {ma : α → ennreal} {mb : α → ennreal} {a b : ennreal}
(hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) :
tendsto (λa, ma a / mb a) f (𝓝 (a / b)) :=
by { apply tendsto.mul hma _ (ennreal.tendsto_inv_iff.2 hmb) _; simp [ha, hb] }
protected lemma tendsto.const_div {f : filter α} {m : α → ennreal} {a b : ennreal}
(hm : tendsto m f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λb, a / m b) f (𝓝 (a / b)) :=
by { apply tendsto.const_mul (ennreal.tendsto_inv_iff.2 hm), simp [hb] }
protected lemma tendsto.div_const {f : filter α} {m : α → ennreal} {a b : ennreal}
(hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) : tendsto (λx, m x / b) f (𝓝 (a / b)) :=
by { apply tendsto.mul_const hm, simp [ha] }
protected lemma tendsto_inv_nat_nhds_zero : tendsto (λ n : ℕ, (n : ennreal)⁻¹) at_top (𝓝 0) :=
ennreal.inv_top ▸ ennreal.tendsto_inv_iff.2 tendsto_nat_nhds_top
lemma Sup_add {s : set ennreal} (hs : s.nonempty) : Sup s + a = ⨆b∈s, b + a :=
have Sup ((λb, b + a) '' s) = Sup s + a,
from is_lub.Sup_eq (is_lub_of_is_lub_of_tendsto
(assume x _ y _ h, add_le_add h (le_refl _))
(is_lub_Sup s)
hs
(tendsto.add (tendsto_id' inf_le_left) tendsto_const_nhds)),
by simp [Sup_image, -add_comm] at this; exact this.symm
lemma supr_add {ι : Sort*} {s : ι → ennreal} [h : nonempty ι] : supr s + a = ⨆b, s b + a :=
let ⟨x⟩ := h in
calc supr s + a = Sup (range s) + a : by simp [Sup_range]
... = (⨆b∈range s, b + a) : Sup_add ⟨s x, x, rfl⟩
... = _ : supr_range
lemma add_supr {ι : Sort*} {s : ι → ennreal} [h : nonempty ι] : a + supr s = ⨆b, a + s b :=
by rw [add_comm, supr_add]; simp [add_comm]
lemma supr_add_supr {ι : Sort*} {f g : ι → ennreal} (h : ∀i j, ∃k, f i + g j ≤ f k + g k) :
supr f + supr g = (⨆ a, f a + g a) :=
begin
by_cases hι : nonempty ι,
{ letI := hι,
refine le_antisymm _ (supr_le $ λ a, add_le_add (le_supr _ _) (le_supr _ _)),
simpa [add_supr, supr_add] using
λ i j:ι, show f i + g j ≤ ⨆ a, f a + g a, from
let ⟨k, hk⟩ := h i j in le_supr_of_le k hk },
{ have : ∀f:ι → ennreal, (⨆i, f i) = 0 := λ f, bot_unique (supr_le $ assume i, (hι ⟨i⟩).elim),
rw [this, this, this, zero_add] }
end
lemma supr_add_supr_of_monotone {ι : Sort*} [semilattice_sup ι]
{f g : ι → ennreal} (hf : monotone f) (hg : monotone g) :
supr f + supr g = (⨆ a, f a + g a) :=
supr_add_supr $ assume i j, ⟨i ⊔ j, add_le_add (hf $ le_sup_left) (hg $ le_sup_right)⟩
lemma finset_sum_supr_nat {α} {ι} [semilattice_sup ι] {s : finset α} {f : α → ι → ennreal}
(hf : ∀a, monotone (f a)) :
∑ a in s, supr (f a) = (⨆ n, ∑ a in s, f a n) :=
begin
refine finset.induction_on s _ _,
{ simp,
exact (bot_unique $ supr_le $ assume i, le_refl ⊥).symm },
{ assume a s has ih,
simp only [finset.sum_insert has],
rw [ih, supr_add_supr_of_monotone (hf a)],
assume i j h,
exact (finset.sum_le_sum $ assume a ha, hf a h) }
end
section priority
-- for some reason the next proof fails without changing the priority of this instance
local attribute [instance, priority 1000] classical.prop_decidable
lemma mul_Sup {s : set ennreal} {a : ennreal} : a * Sup s = ⨆i∈s, a * i :=
begin
by_cases hs : ∀x∈s, x = (0:ennreal),
{ have h₁ : Sup s = 0 := (bot_unique $ Sup_le $ assume a ha, (hs a ha).symm ▸ le_refl 0),
have h₂ : (⨆i ∈ s, a * i) = 0 :=
(bot_unique $ supr_le $ assume a, supr_le $ assume ha, by simp [hs a ha]),
rw [h₁, h₂, mul_zero] },
{ simp only [not_forall] at hs,
rcases hs with ⟨x, hx, hx0⟩,
have s₁ : Sup s ≠ 0 :=
zero_lt_iff_ne_zero.1 (lt_of_lt_of_le (zero_lt_iff_ne_zero.2 hx0) (le_Sup hx)),
have : Sup ((λb, a * b) '' s) = a * Sup s :=
is_lub.Sup_eq (is_lub_of_is_lub_of_tendsto
(assume x _ y _ h, canonically_ordered_semiring.mul_le_mul (le_refl _) h)
(is_lub_Sup _)
⟨x, hx⟩
(ennreal.tendsto.const_mul (tendsto_id' inf_le_left) (or.inl s₁))),
rw [this.symm, Sup_image] }
end
end priority
lemma mul_supr {ι : Sort*} {f : ι → ennreal} {a : ennreal} : a * supr f = ⨆i, a * f i :=
by rw [← Sup_range, mul_Sup, supr_range]
lemma supr_mul {ι : Sort*} {f : ι → ennreal} {a : ennreal} : supr f * a = ⨆i, f i * a :=
by rw [mul_comm, mul_supr]; congr; funext; rw [mul_comm]
protected lemma tendsto_coe_sub : ∀{b:ennreal}, tendsto (λb:ennreal, ↑r - b) (𝓝 b) (𝓝 (↑r - b)) :=
begin
refine (forall_ennreal.2 $ and.intro (assume a, _) _),
{ simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, coe_sub.symm],
exact tendsto_const_nhds.sub tendsto_id },
simp,
exact (tendsto.congr' (mem_sets_of_superset (lt_mem_nhds $ @coe_lt_top r) $
by simp [le_of_lt] {contextual := tt})) tendsto_const_nhds
end
lemma sub_supr {ι : Sort*} [hι : nonempty ι] {b : ι → ennreal} (hr : a < ⊤) :
a - (⨆i, b i) = (⨅i, a - b i) :=
let ⟨i⟩ := hι in
let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in
have Inf ((λb, ↑r - b) '' range b) = ↑r - (⨆i, b i),
from is_glb.Inf_eq $ is_glb_of_is_lub_of_tendsto
(assume x _ y _, sub_le_sub (le_refl _))
is_lub_supr
⟨_, i, rfl⟩
(tendsto.comp ennreal.tendsto_coe_sub (tendsto_id' inf_le_left)),
by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_refl _
end topological_space
section tsum
variables {f g : α → ennreal}
@[norm_cast] protected lemma has_sum_coe {f : α → ℝ≥0} {r : ℝ≥0} :
has_sum (λa, (f a : ennreal)) ↑r ↔ has_sum f r :=
have (λs:finset α, ∑ a in s, ↑(f a)) = (coe : ℝ≥0 → ennreal) ∘ (λs:finset α, ∑ a in s, f a),
from funext $ assume s, ennreal.coe_finset_sum.symm,
by unfold has_sum; rw [this, tendsto_coe]
protected lemma tsum_coe_eq {f : α → ℝ≥0} (h : has_sum f r) : (∑'a, (f a : ennreal)) = r :=
(ennreal.has_sum_coe.2 h).tsum_eq
protected lemma coe_tsum {f : α → ℝ≥0} : summable f → ↑(tsum f) = (∑'a, (f a : ennreal))
| ⟨r, hr⟩ := by rw [hr.tsum_eq, ennreal.tsum_coe_eq hr]
protected lemma has_sum : has_sum f (⨆s:finset α, ∑ a in s, f a) :=
tendsto_order.2
⟨assume a' ha',
let ⟨s, hs⟩ := lt_supr_iff.mp ha' in
mem_at_top_sets.mpr ⟨s, assume t ht, lt_of_lt_of_le hs $ finset.sum_le_sum_of_subset ht⟩,
assume a' ha',
univ_mem_sets' $ assume s,
have ∑ a in s, f a ≤ ⨆(s : finset α), ∑ a in s, f a,
from le_supr (λ(s : finset α), ∑ a in s, f a) s,
lt_of_le_of_lt this ha'⟩
@[simp] protected lemma summable : summable f := ⟨_, ennreal.has_sum⟩
lemma tsum_coe_ne_top_iff_summable {f : β → ℝ≥0} :
(∑' b, (f b:ennreal)) ≠ ∞ ↔ summable f :=
begin
refine ⟨λ h, _, λ h, ennreal.coe_tsum h ▸ ennreal.coe_ne_top⟩,
lift (∑' b, (f b:ennreal)) to ℝ≥0 using h with a ha,
refine ⟨a, ennreal.has_sum_coe.1 _⟩,
rw ha,
exact ennreal.summable.has_sum
end
protected lemma tsum_eq_supr_sum : (∑'a, f a) = (⨆s:finset α, ∑ a in s, f a) :=
ennreal.has_sum.tsum_eq
protected lemma tsum_eq_supr_sum' {ι : Type*} (s : ι → finset α) (hs : ∀ t, ∃ i, t ⊆ s i) :
(∑' a, f a) = ⨆ i, ∑ a in s i, f a :=
begin
rw [ennreal.tsum_eq_supr_sum],
symmetry,
change (⨆i:ι, (λ t : finset α, ∑ a in t, f a) (s i)) = ⨆s:finset α, ∑ a in s, f a,
exact (finset.sum_mono_set f).supr_comp_eq hs
end
protected lemma tsum_sigma {β : α → Type*} (f : Πa, β a → ennreal) :
(∑'p:Σa, β a, f p.1 p.2) = (∑'a b, f a b) :=
tsum_sigma' (assume b, ennreal.summable) ennreal.summable
protected lemma tsum_sigma' {β : α → Type*} (f : (Σ a, β a) → ennreal) :
(∑'p:(Σa, β a), f p) = (∑'a b, f ⟨a, b⟩) :=
tsum_sigma' (assume b, ennreal.summable) ennreal.summable
protected lemma tsum_prod {f : α → β → ennreal} : (∑'p:α×β, f p.1 p.2) = (∑'a, ∑'b, f a b) :=
tsum_prod' ennreal.summable $ λ _, ennreal.summable
protected lemma tsum_comm {f : α → β → ennreal} : (∑'a, ∑'b, f a b) = (∑'b, ∑'a, f a b) :=
tsum_comm' ennreal.summable (λ _, ennreal.summable) (λ _, ennreal.summable)
protected lemma tsum_add : (∑'a, f a + g a) = (∑'a, f a) + (∑'a, g a) :=
tsum_add ennreal.summable ennreal.summable
protected lemma tsum_le_tsum (h : ∀a, f a ≤ g a) : (∑'a, f a) ≤ (∑'a, g a) :=
tsum_le_tsum h ennreal.summable ennreal.summable
protected lemma sum_le_tsum {f : α → ennreal} (s : finset α) : ∑ x in s, f x ≤ ∑' x, f x :=
sum_le_tsum s (λ x hx, zero_le _) ennreal.summable
protected lemma tsum_eq_supr_nat' {f : ℕ → ennreal} {N : ℕ → ℕ} (hN : tendsto N at_top at_top) :
(∑'i:ℕ, f i) = (⨆i:ℕ, ∑ a in finset.range (N i), f a) :=
ennreal.tsum_eq_supr_sum' _ $ λ t,
let ⟨n, hn⟩ := t.exists_nat_subset_range,
⟨k, _, hk⟩ := exists_le_of_tendsto_at_top hN 0 n in
⟨k, finset.subset.trans hn (finset.range_mono hk)⟩
protected lemma tsum_eq_supr_nat {f : ℕ → ennreal} :
(∑'i:ℕ, f i) = (⨆i:ℕ, ∑ a in finset.range i, f a) :=
ennreal.tsum_eq_supr_sum' _ finset.exists_nat_subset_range
protected lemma le_tsum (a : α) : f a ≤ (∑'a, f a) :=
le_tsum' ennreal.summable a
protected lemma tsum_eq_top_of_eq_top : (∃ a, f a = ∞) → (∑' a, f a) = ∞
| ⟨a, ha⟩ := top_unique $ ha ▸ ennreal.le_tsum a
protected lemma ne_top_of_tsum_ne_top (h : (∑' a, f a) ≠ ∞) (a : α) : f a ≠ ∞ :=
λ ha, h $ ennreal.tsum_eq_top_of_eq_top ⟨a, ha⟩
protected lemma tsum_mul_left : (∑'i, a * f i) = a * (∑'i, f i) :=
if h : ∀i, f i = 0 then by simp [h] else
let ⟨i, (hi : f i ≠ 0)⟩ := not_forall.mp h in
have sum_ne_0 : (∑'i, f i) ≠ 0, from ne_of_gt $
calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm
... ≤ (∑'i, f i) : ennreal.le_tsum _,
have tendsto (λs:finset α, ∑ j in s, a * f j) at_top (𝓝 (a * (∑'i, f i))),
by rw [← show (*) a ∘ (λs:finset α, ∑ j in s, f j) = λs, ∑ j in s, a * f j,
from funext $ λ s, finset.mul_sum];
exact ennreal.tendsto.const_mul ennreal.summable.has_sum (or.inl sum_ne_0),
has_sum.tsum_eq this
protected lemma tsum_mul_right : (∑'i, f i * a) = (∑'i, f i) * a :=
by simp [mul_comm, ennreal.tsum_mul_left]
@[simp] lemma tsum_supr_eq {α : Type*} (a : α) {f : α → ennreal} :
(∑'b:α, ⨆ (h : a = b), f b) = f a :=
le_antisymm
(by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s,
calc (∑ b in s, ⨆ (h : a = b), f b) ≤ ∑ b in {a}, ⨆ (h : a = b), f b :
finset.sum_le_sum_of_ne_zero $ assume b _ hb,
suffices a = b, by simpa using this.symm,
classical.by_contradiction $ assume h,
by simpa [h] using hb
... = f a : by simp))
(calc f a ≤ (⨆ (h : a = a), f a) : le_supr (λh:a=a, f a) rfl
... ≤ (∑'b:α, ⨆ (h : a = b), f b) : ennreal.le_tsum _)
lemma has_sum_iff_tendsto_nat {f : ℕ → ennreal} (r : ennreal) :
has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) :=
begin
refine ⟨has_sum.tendsto_sum_nat, assume h, _⟩,
rw [← supr_eq_of_tendsto _ h, ← ennreal.tsum_eq_supr_nat],
{ exact ennreal.summable.has_sum },
{ exact assume s t hst, finset.sum_le_sum_of_subset (finset.range_subset.2 hst) }
end
lemma to_nnreal_apply_of_tsum_ne_top {α : Type*} {f : α → ennreal} (hf : (∑' i, f i) ≠ ∞) (x : α) :
(((ennreal.to_nnreal ∘ f) x : ℝ≥0) : ennreal) = f x :=
coe_to_nnreal $ ennreal.ne_top_of_tsum_ne_top hf _
lemma summable_to_nnreal_of_tsum_ne_top {α : Type*} {f : α → ennreal} (hf : (∑' i, f i) ≠ ∞) :
summable (ennreal.to_nnreal ∘ f) :=
by simpa only [←tsum_coe_ne_top_iff_summable, to_nnreal_apply_of_tsum_ne_top hf] using hf
protected lemma tsum_apply {ι α : Type*} {f : ι → α → ennreal} {x : α} :
(∑' i, f i) x = ∑' i, f i x :=
tsum_apply $ pi.summable.mpr $ λ _, ennreal.summable
lemma tsum_sub {f : ℕ → ennreal} {g : ℕ → ennreal} (h₁ : (∑' i, g i) < ∞) (h₂ : g ≤ f) :
(∑' i, (f i - g i)) = (∑' i, f i) - (∑' i, g i) :=
begin
have h₃:(∑' i, (f i - g i)) = (∑' i, (f i - g i) + (g i))-(∑' i, g i),
{ rw [ennreal.tsum_add, add_sub_self h₁]},
have h₄:(λ i, (f i - g i) + (g i)) = f,
{ ext n, rw ennreal.sub_add_cancel_of_le (h₂ n)},
rw h₄ at h₃, apply h₃,
end
end tsum
end ennreal
namespace nnreal
open_locale nnreal
/-- Comparison test of convergence of `ℝ≥0`-valued series. -/
lemma exists_le_has_sum_of_le {f g : β → ℝ≥0} {r : ℝ≥0}
(hgf : ∀b, g b ≤ f b) (hfr : has_sum f r) : ∃p≤r, has_sum g p :=
have (∑'b, (g b : ennreal)) ≤ r,
begin
refine has_sum_le (assume b, _) ennreal.summable.has_sum (ennreal.has_sum_coe.2 hfr),
exact ennreal.coe_le_coe.2 (hgf _)
end,
let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in
⟨p, hpr, ennreal.has_sum_coe.1 $ eq ▸ ennreal.summable.has_sum⟩
/-- Comparison test of convergence of `ℝ≥0`-valued series. -/
lemma summable_of_le {f g : β → ℝ≥0} (hgf : ∀b, g b ≤ f b) : summable f → summable g
| ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_has_sum_of_le hgf hfr in hp.summable
/-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if
the sequence of partial sum converges to `r`. -/
lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0} {r : ℝ≥0} :
has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) :=
begin
rw [← ennreal.has_sum_coe, ennreal.has_sum_iff_tendsto_nat],
simp only [ennreal.coe_finset_sum.symm],
exact ennreal.tendsto_coe
end
lemma not_summable_iff_tendsto_nat_at_top {f : ℕ → ℝ≥0} :
¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top :=
begin
split,
{ intros h,
refine ((tendsto_of_monotone _).resolve_right h).comp _,
exacts [finset.sum_mono_set _, tendsto_finset_range] },
{ rintros hnat ⟨r, hr⟩,
exact not_tendsto_nhds_of_tendsto_at_top hnat _ (has_sum_iff_tendsto_nat.1 hr) }
end
lemma summable_iff_not_tendsto_nat_at_top {f : ℕ → ℝ≥0} :
summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top :=
by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top]
lemma summable_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0}
(h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f :=
begin
apply summable_iff_not_tendsto_nat_at_top.2 (λ H, _),
rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩,
exact lt_irrefl _ (hn.trans_le (h n)),
end
lemma tsum_le_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0}
(h : ∀ n, ∑ i in finset.range n, f i ≤ c) : (∑' n, f n) ≤ c :=
le_of_tendsto' (has_sum_iff_tendsto_nat.1 (summable_of_sum_range_le h).has_sum) h
lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ≥0} (hf : summable f)
{i : β → α} (hi : function.injective i) : (∑' x, f (i x)) ≤ ∑' x, f x :=
tsum_le_tsum_of_inj i hi (λ c hc, zero_le _) (λ b, le_refl _) (summable_comp_injective hf hi) hf
lemma summable_sigma {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ≥0} :
summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) :=
begin
split,
{ simp only [← nnreal.summable_coe, nnreal.coe_tsum],
exact λ h, ⟨h.sigma_factor, h.sigma⟩ },
{ rintro ⟨h₁, h₂⟩,
simpa only [← ennreal.tsum_coe_ne_top_iff_summable, ennreal.tsum_sigma', ennreal.coe_tsum, h₁]
using h₂ }
end
open finset
/-- For `f : ℕ → ℝ≥0`, then `∑' k, f (k + i)` tends to zero. This does not require a summability
assumption on `f`, as otherwise all sums are zero. -/
lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) :=
begin
rw ← tendsto_coe,
convert tendsto_sum_nat_add (λ i, (f i : ℝ)),
norm_cast,
end
end nnreal
namespace ennreal
lemma tendsto_sum_nat_add (f : ℕ → ennreal) (hf : (∑' i, f i) ≠ ∞) :
tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) :=
begin
have : ∀ i, (∑' k, (((ennreal.to_nnreal ∘ f) (k + i) : ℝ≥0) : ennreal)) =
(∑' k, (ennreal.to_nnreal ∘ f) (k + i) : ℝ≥0) :=
λ i, (ennreal.coe_tsum
(nnreal.summable_nat_add _ (summable_to_nnreal_of_tsum_ne_top hf) _)).symm,
simp only [λ x, (to_nnreal_apply_of_tsum_ne_top hf x).symm, ←ennreal.coe_zero,
this, ennreal.tendsto_coe] { single_pass := tt },
exact nnreal.tendsto_sum_nat_add _
end
end ennreal
lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ} (hf : summable f) (hn : ∀ a, 0 ≤ f a)
{i : β → α} (hi : function.injective i) : tsum (f ∘ i) ≤ tsum f :=
begin
let g : α → ℝ≥0 := λ a, ⟨f a, hn a⟩,
have hg : summable g, by rwa ← nnreal.summable_coe,
convert nnreal.coe_le_coe.2 (nnreal.tsum_comp_le_tsum_of_inj hg hi);
{ rw nnreal.coe_tsum, congr }
end
/-- Comparison test of convergence of series of non-negative real numbers. -/
lemma summable_of_nonneg_of_le {f g : β → ℝ}
(hg : ∀b, 0 ≤ g b) (hgf : ∀b, g b ≤ f b) (hf : summable f) : summable g :=
let f' (b : β) : ℝ≥0 := ⟨f b, le_trans (hg b) (hgf b)⟩ in
let g' (b : β) : ℝ≥0 := ⟨g b, hg b⟩ in
have summable f', from nnreal.summable_coe.1 hf,
have summable g', from
nnreal.summable_of_le (assume b, (@nnreal.coe_le_coe (g' b) (f' b)).2 $ hgf b) this,
show summable (λb, g' b : β → ℝ), from nnreal.summable_coe.2 this
/-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if
the sequence of partial sum converges to `r`. -/
lemma has_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} (hf : ∀i, 0 ≤ f i) (r : ℝ) :
has_sum f r ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) :=
begin
lift f to ℕ → ℝ≥0 using hf,
simp only [has_sum, ← nnreal.coe_sum, nnreal.tendsto_coe'],
exact exists_congr (λ hr, nnreal.has_sum_iff_tendsto_nat)
end
lemma not_summable_iff_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) :
¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top :=
begin
lift f to ℕ → ℝ≥0 using hf,
exact_mod_cast nnreal.not_summable_iff_tendsto_nat_at_top
end
lemma summable_iff_not_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) :
summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top :=
by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top_of_nonneg hf]
lemma summable_sigma_of_nonneg {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ} (hf : ∀ x, 0 ≤ f x) :
summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) :=
by { lift f to (Σ x, β x) → ℝ≥0 using hf, exact_mod_cast nnreal.summable_sigma }
lemma summable_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n)
(h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f :=
begin
apply (summable_iff_not_tendsto_nat_at_top_of_nonneg hf).2 (λ H, _),
rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩,
exact lt_irrefl _ (hn.trans_le (h n)),
end
lemma tsum_le_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n)
(h : ∀ n, ∑ i in finset.range n, f i ≤ c) : (∑' n, f n) ≤ c :=
le_of_tendsto' ((has_sum_iff_tendsto_nat_of_nonneg hf _).1
(summable_of_sum_range_le hf h).has_sum) h
section
variables [emetric_space β]
open ennreal filter emetric
/-- In an emetric ball, the distance between points is everywhere finite -/
lemma edist_ne_top_of_mem_ball {a : β} {r : ennreal} (x y : ball a r) : edist x.1 y.1 ≠ ⊤ :=
lt_top_iff_ne_top.1 $
calc edist x y ≤ edist a x + edist a y : edist_triangle_left x.1 y.1 a
... < r + r : by rw [edist_comm a x, edist_comm a y]; exact add_lt_add x.2 y.2
... ≤ ⊤ : le_top
/-- Each ball in an extended metric space gives us a metric space, as the edist
is everywhere finite. -/
def metric_space_emetric_ball (a : β) (r : ennreal) : metric_space (ball a r) :=
emetric_space.to_metric_space edist_ne_top_of_mem_ball
local attribute [instance] metric_space_emetric_ball
lemma nhds_eq_nhds_emetric_ball (a x : β) (r : ennreal) (h : x ∈ ball a r) :
𝓝 x = map (coe : ball a r → β) (𝓝 ⟨x, h⟩) :=
(map_nhds_subtype_coe_eq _ $ mem_nhds_sets emetric.is_open_ball h).symm
end
section
variable [emetric_space α]
open emetric
lemma tendsto_iff_edist_tendsto_0 {l : filter β} {f : β → α} {y : α} :
tendsto f l (𝓝 y) ↔ tendsto (λ x, edist (f x) y) l (𝓝 0) :=
by simp only [emetric.nhds_basis_eball.tendsto_right_iff, emetric.mem_ball,
@tendsto_order ennreal β _ _, forall_prop_of_false ennreal.not_lt_zero, forall_const, true_and]
/-- Yet another metric characterization of Cauchy sequences on integers. This one is often the
most efficient. -/
lemma emetric.cauchy_seq_iff_le_tendsto_0 [nonempty β] [semilattice_sup β] {s : β → α} :
cauchy_seq s ↔ (∃ (b: β → ennreal), (∀ n m N : β, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N)
∧ (tendsto b at_top (𝓝 0))) :=
⟨begin
assume hs,
rw emetric.cauchy_seq_iff at hs,
/- `s` is Cauchy sequence. The sequence `b` will be constructed by taking
the supremum of the distances between `s n` and `s m` for `n m ≥ N`-/
let b := λN, Sup ((λ(p : β × β), edist (s p.1) (s p.2))''{p | p.1 ≥ N ∧ p.2 ≥ N}),
--Prove that it bounds the distances of points in the Cauchy sequence
have C : ∀ n m N, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N,
{ refine λm n N hm hn, le_Sup _,
use (prod.mk m n),
simp only [and_true, eq_self_iff_true, set.mem_set_of_eq],
exact ⟨hm, hn⟩ },
--Prove that it tends to `0`, by using the Cauchy property of `s`
have D : tendsto b at_top (𝓝 0),
{ refine tendsto_order.2 ⟨λa ha, absurd ha (ennreal.not_lt_zero), λε εpos, _⟩,
rcases exists_between εpos with ⟨δ, δpos, δlt⟩,
rcases hs δ δpos with ⟨N, hN⟩,
refine filter.mem_at_top_sets.2 ⟨N, λn hn, _⟩,
have : b n ≤ δ := Sup_le begin
simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib, prod.exists],
intros d p q hp hq hd,
rw ← hd,
exact le_of_lt (hN p q (le_trans hn hp) (le_trans hn hq))
end,
simpa using lt_of_le_of_lt this δlt },
-- Conclude
exact ⟨b, ⟨C, D⟩⟩
end,
begin
rintros ⟨b, ⟨b_bound, b_lim⟩⟩,
/-b : ℕ → ℝ, b_bound : ∀ (n m N : ℕ), N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N,
b_lim : tendsto b at_top (𝓝 0)-/
refine emetric.cauchy_seq_iff.2 (λε εpos, _),
have : ∀ᶠ n in at_top, b n < ε := (tendsto_order.1 b_lim ).2 _ εpos,
rcases filter.mem_at_top_sets.1 this with ⟨N, hN⟩,
exact ⟨N, λm n hm hn, calc
edist (s m) (s n) ≤ b N : b_bound m n N hm hn
... < ε : (hN _ (le_refl N)) ⟩
end⟩
lemma continuous_of_le_add_edist {f : α → ennreal} (C : ennreal)
(hC : C ≠ ⊤) (h : ∀x y, f x ≤ f y + C * edist x y) : continuous f :=
begin
refine continuous_iff_continuous_at.2 (λx, tendsto_order.2 ⟨_, _⟩),
show ∀e, e < f x → ∀ᶠ y in 𝓝 x, e < f y,
{ assume e he,
let ε := min (f x - e) 1,
have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]),
have : 0 < ε := by simp [ε, hC, he, ennreal.zero_lt_one],
have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, mul_eq_zero]),
have I : C * (C⁻¹ * (ε/2)) < ε,
{ by_cases C_zero : C = 0,
{ simp [C_zero, ‹0 < ε›] },
{ calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc]
... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC]
... < ε : ennreal.half_lt_self (‹0 < ε›.ne') (‹ε < ⊤›.ne) }},
have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | e < f y},
{ rintros y hy,
by_cases htop : f y = ⊤,
{ simp [htop, lt_top_iff_ne_top, ne_top_of_lt he] },
{ simp at hy,
have : e + ε < f y + ε := calc
e + ε ≤ e + (f x - e) : add_le_add_left (min_le_left _ _) _
... = f x : by simp [le_of_lt he]
... ≤ f y + C * edist x y : h x y
... = f y + C * edist y x : by simp [edist_comm]
... ≤ f y + C * (C⁻¹ * (ε/2)) :
add_le_add_left (canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy)) _
... < f y + ε : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I,
show e < f y, from
(ennreal.add_lt_add_iff_right ‹ε < ⊤›).1 this }},
apply filter.mem_sets_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this },
show ∀e, f x < e → ∀ᶠ y in 𝓝 x, f y < e,
{ assume e he,
let ε := min (e - f x) 1,
have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]),
have : 0 < ε := by simp [ε, he, ennreal.zero_lt_one],
have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, mul_eq_zero]),
have I : C * (C⁻¹ * (ε/2)) < ε,
{ by_cases C_zero : C = 0,
simp [C_zero, ‹0 < ε›],
calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc]
... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC]
... < ε : ennreal.half_lt_self (‹0 < ε›.ne') (‹ε < ⊤›.ne) },
have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | f y < e},
{ rintros y hy,
have htop : f x ≠ ⊤ := ne_top_of_lt he,
show f y < e, from calc
f y ≤ f x + C * edist y x : h y x
... ≤ f x + C * (C⁻¹ * (ε/2)) :
add_le_add_left (canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy)) _
... < f x + ε : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I
... ≤ f x + (e - f x) : add_le_add_left (min_le_left _ _) _
... = e : by simp [le_of_lt he] },
apply filter.mem_sets_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this },
end
theorem continuous_edist : continuous (λp:α×α, edist p.1 p.2) :=
begin
apply continuous_of_le_add_edist 2 (by norm_num),
rintros ⟨x, y⟩ ⟨x', y'⟩,
calc edist x y ≤ edist x x' + edist x' y' + edist y' y : edist_triangle4 _ _ _ _
... = edist x' y' + (edist x x' + edist y y') : by simp [edist_comm]; cc
... ≤ edist x' y' + (edist (x, y) (x', y') + edist (x, y) (x', y')) :
add_le_add_left (add_le_add (le_max_left _ _) (le_max_right _ _)) _
... = edist x' y' + 2 * edist (x, y) (x', y') : by rw [← mul_two, mul_comm]
end
theorem continuous.edist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, edist (f b) (g b)) :=
continuous_edist.comp (hf.prod_mk hg : _)
theorem filter.tendsto.edist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, edist (f x) (g x)) x (𝓝 (edist a b)) :=
(continuous_edist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
lemma cauchy_seq_of_edist_le_of_tsum_ne_top {f : ℕ → α} (d : ℕ → ennreal)
(hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : tsum d ≠ ∞) :
cauchy_seq f :=
begin
lift d to (ℕ → nnreal) using (λ i, ennreal.ne_top_of_tsum_ne_top hd i),
rw ennreal.tsum_coe_ne_top_iff_summable at hd,
exact cauchy_seq_of_edist_le_of_summable d hf hd
end
lemma emetric.is_closed_ball {a : α} {r : ennreal} : is_closed (closed_ball a r) :=
is_closed_le (continuous_id.edist continuous_const) continuous_const
/-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ennreal`,
then the distance from `f n` to the limit is bounded by `∑'_{k=n}^∞ d k`. -/
lemma edist_le_tsum_of_edist_le_of_tendsto {f : ℕ → α} (d : ℕ → ennreal)
(hf : ∀ n, edist (f n) (f n.succ) ≤ d n)
{a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
edist (f n) a ≤ ∑' m, d (n + m) :=
begin
refine le_of_tendsto (tendsto_const_nhds.edist ha)
(mem_at_top_sets.2 ⟨n, λ m hnm, _⟩),
refine le_trans (edist_le_Ico_sum_of_edist_le hnm (λ k _ _, hf k)) _,
rw [finset.sum_Ico_eq_sum_range],
exact sum_le_tsum _ (λ _ _, zero_le _) ennreal.summable
end
/-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ennreal`,
then the distance from `f 0` to the limit is bounded by `∑'_{k=0}^∞ d k`. -/
lemma edist_le_tsum_of_edist_le_of_tendsto₀ {f : ℕ → α} (d : ℕ → ennreal)
(hf : ∀ n, edist (f n) (f n.succ) ≤ d n)
{a : α} (ha : tendsto f at_top (𝓝 a)) :
edist (f 0) a ≤ ∑' m, d m :=
by simpa using edist_le_tsum_of_edist_le_of_tendsto d hf ha 0
end --section
|
2f1563e1eedfcddad875f8faad2e6e5721862a0f | 618003631150032a5676f229d13a079ac875ff77 | /src/ring_theory/localization.lean | 31665d6d058a46ef2c6381b23b75c89904f7e8f6 | [
"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 | 23,761 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston
-/
import data.equiv.ring
import tactic.ring_exp
import ring_theory.ideal_operations
import group_theory.monoid_localization
/-!
# Localizations of commutative rings
We characterize the localization of a commutative ring `R` at a submonoid `M` up to
isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a
ring homomorphism `f : R →+* S` satisfying 3 properties:
1. For all `y ∈ M`, `f y` is a unit;
2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`;
3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`.
Given such a localization map `f : R →+* S`, we can define the surjection
`localization.mk'` sending `(x, y) : R × M` to `f x * (f y)⁻¹`, and
`localization.lift`, the homomorphism from `S` induced by a homomorphism from `R` which maps
elements of `M` to invertible elements of the codomain. Similarly, given commutative rings
`P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism
`g : R →+* P` such that `g(M) ⊆ T` induces a homomorphism of localizations,
`localization.map`, from `S` to `Q`.
We prove some lemmas about the `R`-algebra structure of `S`.
When `R` is an integral domain, we define `fraction_map R K` as an abbreviation for
`localization (non_zero_divisors R) K`, the natural map to `R`'s field of fractions.
We show that a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}`
is a field.
## Implementation notes
In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one
structure with an isomorphic one; one way around this is to isolate a predicate characterizing
a structure up to isomorphism, and reason about things that satisfy the predicate.
A ring localization map is defined to be a localization map of the underlying `comm_monoid` (a
`submonoid.localization_map`) which is also a ring hom. To prove most lemmas about a
`localization` `f` in this file we invoke the corresponding proof for the underlying
`comm_monoid` localization map `f.to_localization_map`, which can be found in
`group_theory.monoid_localization` and the namespace `submonoid.localization_map`.
To apply a localization map `f` as a function, we use `f.to_map`, as coercions don't work well for
this structure.
We use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the
`R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure.
## Tags
localization, ring localization, commutative ring localization, characteristic predicate,
commutative ring, field of fractions
-/
variables {R : Type*} [comm_ring R] (M : submonoid R) (S : Type*) [comm_ring S]
{P : Type*} [comm_ring P]
open function
set_option old_structure_cmd true
/-- The type of ring homomorphisms satisfying the characteristic predicate: if `f : R →+* S`
satisfies this predicate, then `S` is isomorphic to the localization of `R` at `M`.
We later define an instance coercing a localization map `f` to its codomain `S` so
that the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra
structure. -/
@[nolint has_inhabited_instance] structure localization
extends ring_hom R S, submonoid.localization_map M S
/-- The ring hom underlying a `localization`. -/
add_decl_doc localization.to_ring_hom
/-- The `comm_monoid` `localization_map` underlying a `comm_ring` `localization`.
See `group_theory.monoid_localization` for its definition. -/
add_decl_doc localization.to_localization_map
variables {M S}
namespace ring_hom
/-- Makes a localization map from a `comm_ring` hom satisfying the characteristic predicate. -/
def to_localization (f : R →+* S) (H1 : ∀ y : M, is_unit (f y))
(H2 : ∀ z, ∃ x : R × M, z * f x.2 = f x.1) (H3 : ∀ x y, f x = f y ↔ ∃ c : M, x * c = y * c) :
localization M S :=
{ map_units' := H1,
surj' := H2,
eq_iff_exists' := H3,
.. f }
end ring_hom
namespace localization
variables (f : localization M S)
/-- Short for `to_ring_hom`; used for applying a localization map as a function. -/
abbreviation to_map := f.to_ring_hom
lemma map_units (y : M) : is_unit (f.to_map y) := f.6 y
lemma surj (z) : ∃ x : R × M, z * f.to_map x.2 = f.to_map x.1 := f.7 z
lemma eq_iff_exists {x y} : f.to_map x = f.to_map y ↔ ∃ c : M, x * c = y * c := f.8 x y
@[ext] lemma ext {f g : localization M S}
(h : ∀ x, f.to_map x = g.to_map x) : f = g :=
begin
cases f, cases g,
simp only [] at *,
exact funext h
end
lemma ext_iff {f g : localization M S} : f = g ↔ ∀ x, f.to_map x = g.to_map x :=
⟨λ h x, h ▸ rfl, ext⟩
lemma to_map_injective : injective (@localization.to_map _ _ M S _) :=
λ _ _ h, ext $ ring_hom.ext_iff.1 h
/-- Given `a : S`, `S` a localization of `R`, `is_integer a` iff `a` is in the image of
the localization map from `R` to `S`. -/
def is_integer (a : S) : Prop := a ∈ set.range f.to_map
variables {f}
lemma is_integer_add {a b} (ha : f.is_integer a) (hb : f.is_integer b) :
f.is_integer (a + b) :=
begin
rcases ha with ⟨a', ha⟩,
rcases hb with ⟨b', hb⟩,
use a' + b',
rw [f.to_map.map_add, ha, hb]
end
lemma is_integer_mul {a b} (ha : f.is_integer a) (hb : f.is_integer b) :
f.is_integer (a * b) :=
begin
rcases ha with ⟨a', ha⟩,
rcases hb with ⟨b', hb⟩,
use a' * b',
rw [f.to_map.map_mul, ha, hb]
end
lemma is_integer_smul {a : R} {b} (hb : f.is_integer b) :
f.is_integer (f.to_map a * b) :=
begin
rcases hb with ⟨b', hb⟩,
use a * b',
rw [←hb, f.to_map.map_mul]
end
variables (f)
/-- Each element `a : S` has an `M`-multiple which is an integer.
This version multiplies `a` on the right, matching the argument order in `localization.surj`.
-/
lemma exists_integer_multiple' (a : S) :
∃ (b : M), is_integer f (a * f.to_map b) :=
let ⟨⟨num, denom⟩, h⟩ := f.surj a in ⟨denom, set.mem_range.mpr ⟨num, h.symm⟩⟩
/-- Each element `a : S` has an `M`-multiple which is an integer.
This version multiplies `a` on the left, matching the argument order in the `has_scalar` instance.
-/
lemma exists_integer_multiple (a : S) :
∃ (b : M), is_integer f (f.to_map b * a) :=
by { simp_rw mul_comm _ a, apply exists_integer_multiple' }
/-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such
that `z * f y = f x` (so this lemma is true by definition). -/
lemma sec_spec {f : localization M S} (z : S) :
z * f.to_map (f.to_localization_map.sec z).2 = f.to_map (f.to_localization_map.sec z).1 :=
classical.some_spec $ f.surj z
/-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such
that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/
lemma sec_spec' {f : localization M S} (z : S) :
f.to_map (f.to_localization_map.sec z).1 = f.to_map (f.to_localization_map.sec z).2 * z :=
by rw [mul_comm, sec_spec]
lemma map_right_cancel {x y} {c : M} (h : f.to_map (c * x) = f.to_map (c * y)) :
f.to_map x = f.to_map y :=
f.to_localization_map.map_right_cancel h
lemma map_left_cancel {x y} {c : M} (h : f.to_map (x * c) = f.to_map (y * c)) :
f.to_map x = f.to_map y :=
f.to_localization_map.map_left_cancel h
lemma eq_zero_of_fst_eq_zero {z x} {y : M}
(h : z * f.to_map y = f.to_map x) (hx : x = 0) : z = 0 :=
by rw [hx, f.to_map.map_zero] at h;
exact (is_unit.mul_left_eq_zero_iff_eq_zero (f.map_units y)).1 h
/-- Given a localization map `f : R →+* S`, the surjection sending `(x, y) : R × M` to
`f x * (f y)⁻¹`. -/
noncomputable def mk' (f : localization M S) (x : R) (y : M) : S :=
f.to_localization_map.mk' x y
@[simp] lemma mk'_sec (z : S) :
f.mk' (f.to_localization_map.sec z).1 (f.to_localization_map.sec z).2 = z :=
f.to_localization_map.mk'_sec _
lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) :
f.mk' (x₁ * x₂) (y₁ * y₂) = f.mk' x₁ y₁ * f.mk' x₂ y₂ :=
f.to_localization_map.mk'_mul _ _ _ _
lemma mk'_one (x) : f.mk' x (1 : M) = f.to_map x :=
f.to_localization_map.mk'_one _
lemma mk'_spec (x) (y : M) :
f.mk' x y * f.to_map y = f.to_map x :=
f.to_localization_map.mk'_spec _ _
lemma mk'_spec' (x) (y : M) :
f.to_map y * f.mk' x y = f.to_map x :=
f.to_localization_map.mk'_spec' _ _
theorem eq_mk'_iff_mul_eq {x} {y : M} {z} :
z = f.mk' x y ↔ z * f.to_map y = f.to_map x :=
f.to_localization_map.eq_mk'_iff_mul_eq
theorem mk'_eq_iff_eq_mul {x} {y : M} {z} :
f.mk' x y = z ↔ f.to_map x = z * f.to_map y :=
f.to_localization_map.mk'_eq_iff_eq_mul
lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} :
f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ f.to_map (x₁ * y₂) = f.to_map (x₂ * y₁) :=
f.to_localization_map.mk'_eq_iff_eq
protected lemma eq {a₁ b₁} {a₂ b₂ : M} :
f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ ∃ c : M, a₁ * b₂ * c = b₁ * a₂ * c :=
f.to_localization_map.eq
lemma eq_iff_eq (g : localization M P) {x y} :
f.to_map x = f.to_map y ↔ g.to_map x = g.to_map y :=
f.to_localization_map.eq_iff_eq g.to_localization_map
lemma mk'_eq_iff_mk'_eq (g : localization M P) {x₁ x₂}
{y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ g.mk' x₁ y₁ = g.mk' x₂ y₂ :=
f.to_localization_map.mk'_eq_iff_mk'_eq g.to_localization_map
lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * a₂ = a₁ * b₂) :
f.mk' a₁ a₂ = f.mk' b₁ b₂ :=
f.to_localization_map.mk'_eq_of_eq H
@[simp] lemma mk'_self {x : R} {hx : x ∈ M} : f.mk' x ⟨x, hx⟩ = 1 :=
f.to_localization_map.mk'_self' _ hx
@[simp] lemma mk'_self' {x : M} : f.mk' x x = 1 :=
f.to_localization_map.mk'_self _
@[simp] lemma mk'_self'' {x : M} : f.mk' x.1 x = 1 :=
f.mk'_self'
lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) :
f.to_map x * f.mk' y z = f.mk' (x * y) z :=
f.to_localization_map.mul_mk'_eq_mk'_of_mul _ _ _
lemma mk'_eq_mul_mk'_one (x : R) (y : M) :
f.mk' x y = f.to_map x * f.mk' 1 y :=
(f.to_localization_map.mul_mk'_one_eq_mk' _ _).symm
@[simp] lemma mk'_mul_cancel_left (x : R) (y : M) :
f.mk' (y * x) y = f.to_map x :=
f.to_localization_map.mk'_mul_cancel_left _ _
lemma mk'_mul_cancel_right (x : R) (y : M) :
f.mk' (x * y) y = f.to_map x :=
f.to_localization_map.mk'_mul_cancel_right _ _
lemma is_unit_comp (j : S →+* P) (y : M) :
is_unit (j.comp f.to_map y) :=
f.to_localization_map.is_unit_comp j.to_monoid_hom _
/-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s
`g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/
lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y} (h : f.to_map x = f.to_map y) :
g x = g y :=
@submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _
f.to_localization_map g.to_monoid_hom hg _ _ h
lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) :
f.mk' (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = f.mk' x₁ y₁ + f.mk' x₂ y₂ :=
f.mk'_eq_iff_eq_mul.2 $ eq.symm
begin
rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, ←eq_sub_iff_add_eq, mk'_eq_iff_eq_mul,
mul_comm _ (f.to_map _), mul_sub, eq_sub_iff_add_eq, ←eq_sub_iff_add_eq', ←mul_assoc,
←f.to_map.map_mul, mul_mk'_eq_mk'_of_mul, mk'_eq_iff_eq_mul],
simp only [f.to_map.map_add, submonoid.coe_mul, f.to_map.map_mul],
ring_exp,
end
/-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s
`g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from
`S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that
`z = f x * (f y)⁻¹`. -/
noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P :=
ring_hom.mk' (@submonoid.localization_map.lift _ _ _ _ _ _ _
f.to_localization_map g.to_monoid_hom hg) $
begin
intros x y,
rw [f.to_localization_map.lift_spec, mul_comm, add_mul, ←sub_eq_iff_eq_add, eq_comm,
f.to_localization_map.lift_spec_mul, mul_comm _ (_ - _), sub_mul, eq_sub_iff_add_eq',
←eq_sub_iff_add_eq, mul_assoc, f.to_localization_map.lift_spec_mul],
show g _ * (g _ * g _) = g _ * (g _ * g _ - g _ * g _),
repeat {rw ←g.map_mul},
rw [←g.map_sub, ←g.map_mul],
apply f.eq_of_eq hg,
erw [f.to_map.map_mul, sec_spec', mul_sub, f.to_map.map_sub],
simp only [f.to_map.map_mul, sec_spec'],
ring_exp,
end
variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y))
/-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s
`g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from
`S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/
lemma lift_mk' (x y) :
f.lift hg (f.mk' x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.mrestrict M) hg y)⁻¹ :=
f.to_localization_map.lift_mk' _ _ _
lemma lift_mk'_spec (x v) (y : M) :
f.lift hg (f.mk' x y) = v ↔ g x = g y * v :=
f.to_localization_map.lift_mk'_spec _ _ _ _
@[simp] lemma lift_eq (x : R) :
f.lift hg (f.to_map x) = g x :=
f.to_localization_map.lift_eq _ _
lemma lift_eq_iff {x y : R × M} :
f.lift hg (f.mk' x.1 x.2) = f.lift hg (f.mk' y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) :=
f.to_localization_map.lift_eq_iff _
@[simp] lemma lift_comp : (f.lift hg).comp f.to_map = g :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_comp _
@[simp] lemma lift_of_comp (j : S →+* P) :
f.lift (f.is_unit_comp j) = j :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_of_comp j.to_monoid_hom
lemma epic_of_localization_map {j k : S →+* P}
(h : ∀ a, j.comp f.to_map a = k.comp f.to_map a) : j = k :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.epic_of_localization_map
_ _ _ _ _ _ _ f.to_localization_map j.to_monoid_hom k.to_monoid_hom h
lemma lift_unique {j : S →+* P}
(hj : ∀ x, j (f.to_map x) = g x) : f.lift hg = j :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique
_ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg j.to_monoid_hom hj
@[simp] lemma lift_id (x) : f.lift f.map_units x = x :=
f.to_localization_map.lift_id _
/-- Given two localization maps `f : R →+* S, k : R →+* P` for a submonoid `M ⊆ R`,
the hom from `P` to `S` induced by `f` is left inverse to the hom from `S` to `P`
induced by `k`. -/
@[simp] lemma lift_left_inverse {k : localization M S} (z : S) :
k.lift f.map_units (f.lift k.map_units z) = z :=
f.to_localization_map.lift_left_inverse _
lemma lift_surjective_iff :
surjective (f.lift hg) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 :=
f.to_localization_map.lift_surjective_iff hg
lemma lift_injective_iff :
injective (f.lift hg) ↔ ∀ x y, f.to_map x = f.to_map y ↔ g x = g y :=
f.to_localization_map.lift_injective_iff hg
variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q]
(k : localization T Q)
/-- Given a `comm_ring` homomorphism `g : R →+* P` where for submonoids `M ⊆ R, T ⊆ P` we have
`g(M) ⊆ T`, the induced ring homomorphism from the localization of `R` at `M` to the
localization of `P` at `T`: if `f : R →+* S` and `k : P →+* Q` are localization maps for `M`
and `T` respectively, we send `z : S` to `k (g x) * (k (g y))⁻¹`, where `(x, y) : R × M` are
such that `z = f x * (f y)⁻¹`. -/
noncomputable def map : S →+* Q :=
@lift _ _ _ _ _ _ _ f (k.to_map.comp g) $ λ y, k.map_units ⟨g y, hy y⟩
variables {k}
lemma map_eq (x) :
f.map hy k (f.to_map x) = k.to_map (g x) :=
f.lift_eq (λ y, k.map_units ⟨g y, hy y⟩) x
@[simp] lemma map_comp :
(f.map hy k).comp f.to_map = k.to_map.comp g :=
f.lift_comp $ λ y, k.map_units ⟨g y, hy y⟩
lemma map_mk' (x) (y : M) :
f.map hy k (f.mk' x y) = k.mk' (g x) ⟨g y, hy y⟩ :=
@submonoid.localization_map.map_mk' _ _ _ _ _ _ _ f.to_localization_map
g.to_monoid_hom _ hy _ _ k.to_localization_map _ _
@[simp] lemma map_id (z : S) :
f.map (λ y, show ring_hom.id R y ∈ M, from y.2) f z = z :=
f.lift_id _
/-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition
of the induced maps equals the map of localizations induced by `l ∘ g`. -/
lemma map_comp_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W]
(j : localization U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) :
(k.map hl j).comp (f.map hy k) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.map_comp_map _ _ _ _ _ _ _
f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map
_ _ _ _ _ j.to_localization_map l.to_monoid_hom hl
/-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition
of the induced maps equals the map of localizations induced by `l ∘ g`. -/
lemma map_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W]
(j : localization U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) (x) :
k.map hl j (f.map hy k x) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j x :=
by rw ←f.map_comp_map hy j hl; refl
/-- Given localization maps `f : R →+* S, k : P →+* Q` for submonoids `M, T` respectively, an
isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations
`S ≃+* Q`. -/
noncomputable def ring_equiv_of_ring_equiv (k : localization T Q) (h : R ≃+* P)
(H : M.map h.to_monoid_hom = T) :
S ≃+* Q :=
(f.to_localization_map.mul_equiv_of_mul_equiv k.to_localization_map H).to_ring_equiv $
(@lift _ _ _ _ _ _ _ f (k.to_map.comp h.to_ring_hom)
(λ y, k.map_units ⟨(h y), H ▸ set.mem_image_of_mem h y.2⟩)).map_add
@[simp] lemma ring_equiv_of_ring_equiv_eq_map_apply {j : R ≃+* P}
(H : M.map j.to_monoid_hom = T) (x) :
f.ring_equiv_of_ring_equiv k j H x =
f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k x := rfl
lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) :
(f.ring_equiv_of_ring_equiv k j H).to_monoid_hom =
f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k := rfl
@[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) :
f.ring_equiv_of_ring_equiv k j H (f.to_map x) = k.to_map (j x) :=
f.to_localization_map.mul_equiv_of_mul_equiv_eq H _
lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x y) :
f.ring_equiv_of_ring_equiv k j H (f.mk' x y) =
k.mk' (j x) ⟨j y, H ▸ set.mem_image_of_mem j y.2⟩ :=
f.to_localization_map.mul_equiv_of_mul_equiv_mk' H _ _
/-!
### `algebra` section
Defines the `R`-algebra instance on a copy of `S` carrying the data of the localization map
`f` needed to induce the `R`-algebra structure. -/
variables (f)
/-- We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that
the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra
structure. -/
@[reducible, nolint unused_arguments] def codomain (f : localization M S) := S
/-- We use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the
`R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. -/
instance : algebra R f.codomain := f.to_map.to_algebra
@[simp] lemma of_id (a : R) :
(algebra.of_id R f.codomain) a = f.to_map a :=
rfl
variables (f)
/-- Localization map `f` from `R` to `S` as an `R`-linear map. -/
def lin_coe : R →ₗ[R] f.codomain :=
{ to_fun := f.to_map,
add := f.to_map.map_add,
smul := f.to_map.map_mul }
variables {f}
instance coe_submodules : has_coe (ideal R) (submodule R f.codomain) :=
⟨λ I, submodule.map f.lin_coe I⟩
lemma mem_coe (I : ideal R) {x : S} :
x ∈ (I : submodule R f.codomain) ↔ ∃ y : R, y ∈ I ∧ f.to_map y = x :=
iff.rfl
@[simp] lemma lin_coe_apply {x} : f.lin_coe x = f.to_map x := rfl
end localization
variables (R)
/-- The submonoid of non-zero-divisors of a `comm_ring` `R`. -/
def non_zero_divisors : submonoid R :=
{ carrier := {x | ∀ z, z * x = 0 → z = 0},
one_mem' := λ z hz, by rwa mul_one at hz,
mul_mem' := λ x₁ x₂ hx₁ hx₂ z hz,
have z * x₁ * x₂ = 0, by rwa mul_assoc,
hx₁ z $ hx₂ (z * x₁) this }
lemma eq_zero_of_ne_zero_of_mul_eq_zero {A : Type*} [integral_domain A]
{x y : A} (hnx : x ≠ 0) (hxy : y * x = 0) :
y = 0 := or.resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx
lemma mem_non_zero_divisors_iff_ne_zero {A : Type*} [integral_domain A] {x : A} :
x ∈ non_zero_divisors A ↔ x ≠ 0 :=
⟨λ hm hz, zero_ne_one (hm 1 $ by rw [hz, one_mul]).symm,
λ hnx z, eq_zero_of_ne_zero_of_mul_eq_zero hnx⟩
variables (K : Type*)
/-- Localization map from an integral domain `R` to its field of fractions. -/
@[reducible] def fraction_map [comm_ring K] := localization (non_zero_divisors R) K
namespace fraction_map
open localization
variables {R K}
lemma to_map_eq_zero_iff [comm_ring K] (φ : fraction_map R K) {x : R} :
x = 0 ↔ φ.to_map x = 0 :=
begin
rw ← φ.to_map.map_zero,
split; intro h,
{ rw h },
{ cases φ.eq_iff_exists.mp h with c hc,
rw zero_mul at hc,
exact c.2 x hc }
end
protected theorem injective [comm_ring K] (φ : fraction_map R K) :
injective φ.to_map :=
φ.to_map.injective_iff.2 (λ _ h, φ.to_map_eq_zero_iff.mpr h)
variables {A : Type*} [integral_domain A]
local attribute [instance] classical.dec_eq
/-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is an
integral domain. -/
def to_integral_domain [comm_ring K] (φ : fraction_map A K) : integral_domain K :=
{ eq_zero_or_eq_zero_of_mul_eq_zero :=
begin
intros z w h,
cases φ.surj z with x hx,
cases φ.surj w with y hy,
have : z * w * φ.to_map y.2 * φ.to_map x.2 = φ.to_map x.1 * φ.to_map y.1, by
rw [mul_assoc z, hy, ←hx]; ac_refl,
erw h at this,
rw [zero_mul, zero_mul, ←φ.to_map.map_mul] at this,
cases eq_zero_or_eq_zero_of_mul_eq_zero (φ.to_map_eq_zero_iff.mpr this.symm) with H H,
{ exact or.inl (φ.eq_zero_of_fst_eq_zero hx H) },
{ exact or.inr (φ.eq_zero_of_fst_eq_zero hy H) },
end,
zero_ne_one := by erw [←φ.to_map.map_zero, ←φ.to_map.map_one];
exact λ h, zero_ne_one (φ.injective h),
..(infer_instance : comm_ring K) }
/-- The inverse of an element in the field of fractions of an integral domain. -/
protected noncomputable def inv [comm_ring K] (φ : fraction_map A K) (z : K) : K :=
if h : z = 0 then 0 else
φ.mk' (φ.to_localization_map.sec z).2 ⟨(φ.to_localization_map.sec z).1,
mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, h $ φ.eq_zero_of_fst_eq_zero (sec_spec z) h0⟩
protected lemma mul_inv_cancel [comm_ring K] (φ : fraction_map A K) (x : K) (hx : x ≠ 0) :
x * φ.inv x = 1 :=
show x * dite _ _ _ = 1, by rw [dif_neg hx,
←is_unit.mul_left_inj (φ.map_units ⟨(φ.to_localization_map.sec x).1,
mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, hx $ φ.eq_zero_of_fst_eq_zero (sec_spec x) h0⟩),
one_mul, mul_assoc, mk'_spec, ←eq_mk'_iff_mul_eq]; exact (φ.mk'_sec x).symm
/-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is a
field. -/
noncomputable def to_field [comm_ring K] (φ : fraction_map A K) : field K :=
{ inv := φ.inv,
mul_inv_cancel := φ.mul_inv_cancel,
inv_zero := dif_pos rfl, ..φ.to_integral_domain }
end fraction_map
|
96cddad034f489df5046d14babf1ea1c8329b9a7 | e91b0bc0bcf14cf6e1bfc20ad1f00ad7cfa5fa76 | /src/sheaves/presheaf_of_rings_on_basis.lean | cc975737ef88fe70841a1b12df6d9c18c2884709 | [] | no_license | kckennylau/lean-scheme | b2de50025289a0339d97798466ef777e1899b0f8 | 8dc513ef9606d2988227490e915b7c7e173a2791 | refs/heads/master | 1,587,165,137,978 | 1,548,172,249,000 | 1,548,172,249,000 | 167,025,881 | 0 | 0 | null | 1,548,173,930,000 | 1,548,173,924,000 | Lean | UTF-8 | Lean | false | false | 1,360 | lean | import sheaves.presheaf_of_types_on_basis
universe u
open topological_space
structure presheaf_of_rings_on_basis (α : Type u) [TX : topological_space α]
{B : set (set α)} (HB : topological_space.is_topological_basis B)
extends presheaf_of_types_on_basis α HB :=
(Fring : ∀ {U} (BU : U ∈ B), comm_ring (F BU))
(res_is_ring_hom : ∀ {U V} (BU : U ∈ B) (BV : V ∈ B) (HVU : V ⊆ U),
is_ring_hom (res BU BV HVU))
attribute [instance] presheaf_of_rings_on_basis.Fring
attribute [instance] presheaf_of_rings_on_basis.res_is_ring_hom
namespace presheaf_of_rings_on_basis
variables {α : Type u} [T : topological_space α]
variables {B : set (set α)} {HB : is_topological_basis B}
include T
-- Morphism of presheaf of rings on basis.
structure morphism (F G : presheaf_of_rings_on_basis α HB)
extends presheaf_of_types_on_basis.morphism
F.to_presheaf_of_types_on_basis G.to_presheaf_of_types_on_basis :=
(ring_homs : ∀ {U} (BU : U ∈ B), is_ring_hom (map BU))
-- Isomorphic presheaves of rings on basis.
def are_isomorphic (F G : presheaf_of_rings_on_basis α HB) :=
∃ (fg : morphism F G) (gf : morphism G F),
presheaf_of_types_on_basis.morphism.is_identity (fg.to_morphism ⊚ gf.to_morphism)
∧ presheaf_of_types_on_basis.morphism.is_identity (gf.to_morphism ⊚ fg.to_morphism)
end presheaf_of_rings_on_basis
|
07ef64fdecd3e11dfb40bc7704cb1a676524084f | 947b78d97130d56365ae2ec264df196ce769371a | /tests/lean/run/coeIssue3.lean | 3cd710985d9ccaf00b07e27a032eb0a46c60e22c | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 512 | lean | new_frontend
structure Var : Type := (name : String)
instance Var.nameCoe : Coe String Var := ⟨Var.mk⟩
structure A : Type := (u : Unit)
structure B : Type := (u : Unit)
def a : A := A.mk ()
def b : B := B.mk ()
def Foo.chalk : A → List Var → Unit := fun _ _ => ()
def Bar.chalk : B → Unit := fun _ => ()
instance listCoe {α β} [Coe α β] : Coe (List α) (List β) :=
⟨fun as => as.map fun a => coe a⟩
open Foo
open Bar
#check Foo.chalk a ["foo"] -- works
#check chalk a ["foo"] -- works
|
36fdef7b66e11163407732ad4fd0d7f1e04290d4 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/data/complex/module.lean | 0c13030e78d2e0c973ddb53a6379eebbd6b8658e | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 11,565 | lean | /-
Copyright (c) 2020 Alexander Bentkamp, Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp, Sébastien Gouëzel, Eric Wieser
-/
import algebra.order.smul
import data.complex.basic
import data.fin.vec_notation
import field_theory.tower
/-!
# Complex number as a vector space over `ℝ`
This file contains the following instances:
* Any `•`-structure (`has_smul`, `mul_action`, `distrib_mul_action`, `module`, `algebra`) on
`ℝ` imbues a corresponding structure on `ℂ`. This includes the statement that `ℂ` is an `ℝ`
algebra.
* any complex vector space is a real vector space;
* any finite dimensional complex vector space is a finite dimensional real vector space;
* the space of `ℝ`-linear maps from a real vector space to a complex vector space is a complex
vector space.
It also defines bundled versions of four standard maps (respectively, the real part, the imaginary
part, the embedding of `ℝ` in `ℂ`, and the complex conjugate):
* `complex.re_lm` (`ℝ`-linear map);
* `complex.im_lm` (`ℝ`-linear map);
* `complex.of_real_am` (`ℝ`-algebra (homo)morphism);
* `complex.conj_ae` (`ℝ`-algebra equivalence).
It also provides a universal property of the complex numbers `complex.lift`, which constructs a
`ℂ →ₐ[ℝ] A` into any `ℝ`-algebra `A` given a square root of `-1`.
-/
namespace complex
open_locale complex_conjugate
variables {R : Type*} {S : Type*}
section
variables [has_smul R ℝ]
/- The useless `0` multiplication in `smul` is to make sure that
`restrict_scalars.module ℝ ℂ ℂ = complex.module` definitionally. -/
instance : has_smul R ℂ :=
{ smul := λ r x, ⟨r • x.re - 0 * x.im, r • x.im + 0 * x.re⟩ }
lemma smul_re (r : R) (z : ℂ) : (r • z).re = r • z.re := by simp [(•)]
lemma smul_im (r : R) (z : ℂ) : (r • z).im = r • z.im := by simp [(•)]
@[simp] lemma real_smul {x : ℝ} {z : ℂ} : x • z = x * z := rfl
end
instance [has_smul R ℝ] [has_smul S ℝ] [smul_comm_class R S ℝ] : smul_comm_class R S ℂ :=
{ smul_comm := λ r s x, by ext; simp [smul_re, smul_im, smul_comm] }
instance [has_smul R S] [has_smul R ℝ] [has_smul S ℝ] [is_scalar_tower R S ℝ] :
is_scalar_tower R S ℂ :=
{ smul_assoc := λ r s x, by ext; simp [smul_re, smul_im, smul_assoc] }
instance [has_smul R ℝ] [has_smul Rᵐᵒᵖ ℝ] [is_central_scalar R ℝ] :
is_central_scalar R ℂ :=
{ op_smul_eq_smul := λ r x, by ext; simp [smul_re, smul_im, op_smul_eq_smul] }
instance [monoid R] [mul_action R ℝ] : mul_action R ℂ :=
{ one_smul := λ x, by ext; simp [smul_re, smul_im, one_smul],
mul_smul := λ r s x, by ext; simp [smul_re, smul_im, mul_smul] }
instance [semiring R] [distrib_mul_action R ℝ] : distrib_mul_action R ℂ :=
{ smul_add := λ r x y, by ext; simp [smul_re, smul_im, smul_add],
smul_zero := λ r, by ext; simp [smul_re, smul_im, smul_zero] }
instance [semiring R] [module R ℝ] : module R ℂ :=
{ add_smul := λ r s x, by ext; simp [smul_re, smul_im, add_smul],
zero_smul := λ r, by ext; simp [smul_re, smul_im, zero_smul] }
instance [comm_semiring R] [algebra R ℝ] : algebra R ℂ :=
{ smul := (•),
smul_def' := λ r x, by ext; simp [smul_re, smul_im, algebra.smul_def],
commutes' := λ r ⟨xr, xi⟩, by ext; simp [smul_re, smul_im, algebra.commutes],
..complex.of_real.comp (algebra_map R ℝ) }
instance : star_module ℝ ℂ :=
⟨λ r x, by simp only [star_def, star_trivial, real_smul, map_mul, conj_of_real]⟩
@[simp] lemma coe_algebra_map : (algebra_map ℝ ℂ : ℝ → ℂ) = coe := rfl
section
variables {A : Type*} [semiring A] [algebra ℝ A]
/-- We need this lemma since `complex.coe_algebra_map` diverts the simp-normal form away from
`alg_hom.commutes`. -/
@[simp] lemma _root_.alg_hom.map_coe_real_complex (f : ℂ →ₐ[ℝ] A) (x : ℝ) :
f x = algebra_map ℝ A x :=
f.commutes x
/-- Two `ℝ`-algebra homomorphisms from ℂ are equal if they agree on `complex.I`. -/
@[ext]
lemma alg_hom_ext ⦃f g : ℂ →ₐ[ℝ] A⦄ (h : f I = g I) : f = g :=
begin
ext ⟨x, y⟩,
simp only [mk_eq_add_mul_I, alg_hom.map_add, alg_hom.map_coe_real_complex, alg_hom.map_mul, h]
end
end
section
open_locale complex_order
protected lemma ordered_smul : ordered_smul ℝ ℂ :=
ordered_smul.mk' $ λ a b r hab hr, ⟨by simp [hr, hab.1.le], by simp [hab.2]⟩
localized "attribute [instance] complex.ordered_smul" in complex_order
end
open submodule finite_dimensional
/-- `ℂ` has a basis over `ℝ` given by `1` and `I`. -/
noncomputable def basis_one_I : basis (fin 2) ℝ ℂ :=
basis.of_equiv_fun
{ to_fun := λ z, ![z.re, z.im],
inv_fun := λ c, c 0 + c 1 • I,
left_inv := λ z, by simp,
right_inv := λ c, by { ext i, fin_cases i; simp },
map_add' := λ z z', by simp,
-- why does `simp` not know how to apply `smul_cons`, which is a `@[simp]` lemma, here?
map_smul' := λ c z, by simp [matrix.smul_cons c z.re, matrix.smul_cons c z.im] }
@[simp] lemma coe_basis_one_I_repr (z : ℂ) : ⇑(basis_one_I.repr z) = ![z.re, z.im] := rfl
@[simp] lemma coe_basis_one_I : ⇑basis_one_I = ![1, I] :=
funext $ λ i, basis.apply_eq_iff.mpr $ finsupp.ext $ λ j,
by fin_cases i; fin_cases j;
simp only [coe_basis_one_I_repr, finsupp.single_eq_same, finsupp.single_eq_of_ne,
matrix.cons_val_zero, matrix.cons_val_one, matrix.head_cons,
nat.one_ne_zero, fin.one_eq_zero_iff, fin.zero_eq_one_iff, ne.def, not_false_iff,
one_re, one_im, I_re, I_im]
instance : finite_dimensional ℝ ℂ := of_fintype_basis basis_one_I
@[simp] lemma finrank_real_complex : finite_dimensional.finrank ℝ ℂ = 2 :=
by rw [finrank_eq_card_basis basis_one_I, fintype.card_fin]
@[simp] lemma dim_real_complex : module.rank ℝ ℂ = 2 :=
by simp [← finrank_eq_dim, finrank_real_complex]
lemma {u} dim_real_complex' : cardinal.lift.{u} (module.rank ℝ ℂ) = 2 :=
by simp [← finrank_eq_dim, finrank_real_complex, bit0]
/-- `fact` version of the dimension of `ℂ` over `ℝ`, locally useful in the definition of the
circle. -/
lemma finrank_real_complex_fact : fact (finrank ℝ ℂ = 2) := ⟨finrank_real_complex⟩
end complex
/- Register as an instance (with low priority) the fact that a complex vector space is also a real
vector space. -/
@[priority 900]
instance module.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E] : module ℝ E :=
restrict_scalars.module ℝ ℂ E
instance module.real_complex_tower (E : Type*) [add_comm_group E] [module ℂ E] :
is_scalar_tower ℝ ℂ E :=
restrict_scalars.is_scalar_tower ℝ ℂ E
@[simp, norm_cast] lemma complex.coe_smul {E : Type*} [add_comm_group E] [module ℂ E]
(x : ℝ) (y : E) :
(x : ℂ) • y = x • y :=
rfl
@[priority 100]
instance finite_dimensional.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E]
[finite_dimensional ℂ E] : finite_dimensional ℝ E :=
finite_dimensional.trans ℝ ℂ E
lemma dim_real_of_complex (E : Type*) [add_comm_group E] [module ℂ E] :
module.rank ℝ E = 2 * module.rank ℂ E :=
cardinal.lift_inj.1 $
by { rw [← dim_mul_dim' ℝ ℂ E, complex.dim_real_complex], simp [bit0] }
lemma finrank_real_of_complex (E : Type*) [add_comm_group E] [module ℂ E] :
finite_dimensional.finrank ℝ E = 2 * finite_dimensional.finrank ℂ E :=
by rw [← finite_dimensional.finrank_mul_finrank ℝ ℂ E, complex.finrank_real_complex]
@[priority 900]
instance star_module.complex_to_real {E : Type*} [add_comm_group E] [has_star E] [module ℂ E]
[star_module ℂ E] : star_module ℝ E :=
⟨λ r a, by rw [star_trivial r, restrict_scalars_smul_def, restrict_scalars_smul_def, star_smul,
complex.coe_algebra_map, complex.star_def, complex.conj_of_real]⟩
namespace complex
open_locale complex_conjugate
/-- Linear map version of the real part function, from `ℂ` to `ℝ`. -/
def re_lm : ℂ →ₗ[ℝ] ℝ :=
{ to_fun := λx, x.re,
map_add' := add_re,
map_smul' := by simp, }
@[simp] lemma re_lm_coe : ⇑re_lm = re := rfl
/-- Linear map version of the imaginary part function, from `ℂ` to `ℝ`. -/
def im_lm : ℂ →ₗ[ℝ] ℝ :=
{ to_fun := λx, x.im,
map_add' := add_im,
map_smul' := by simp, }
@[simp] lemma im_lm_coe : ⇑im_lm = im := rfl
/-- `ℝ`-algebra morphism version of the canonical embedding of `ℝ` in `ℂ`. -/
def of_real_am : ℝ →ₐ[ℝ] ℂ := algebra.of_id ℝ ℂ
@[simp] lemma of_real_am_coe : ⇑of_real_am = coe := rfl
/-- `ℝ`-algebra isomorphism version of the complex conjugation function from `ℂ` to `ℂ` -/
def conj_ae : ℂ ≃ₐ[ℝ] ℂ :=
{ inv_fun := conj,
left_inv := star_star,
right_inv := star_star,
commutes' := conj_of_real,
.. conj }
@[simp] lemma conj_ae_coe : ⇑conj_ae = conj := rfl
/-- The matrix representation of `conj_ae`. -/
@[simp] lemma to_matrix_conj_ae :
linear_map.to_matrix basis_one_I basis_one_I conj_ae.to_linear_map = !![1, 0; 0, -1] :=
begin
ext i j,
simp [linear_map.to_matrix_apply],
fin_cases i; fin_cases j; simp
end
section lift
variables {A : Type*} [ring A] [algebra ℝ A]
/-- There is an alg_hom from `ℂ` to any `ℝ`-algebra with an element that squares to `-1`.
See `complex.lift` for this as an equiv. -/
def lift_aux (I' : A) (hf : I' * I' = -1) : ℂ →ₐ[ℝ] A :=
alg_hom.of_linear_map
((algebra.of_id ℝ A).to_linear_map.comp re_lm + (linear_map.to_span_singleton _ _ I').comp im_lm)
(show algebra_map ℝ A 1 + (0 : ℝ) • I' = 1,
by rw [ring_hom.map_one, zero_smul, add_zero])
(λ ⟨x₁, y₁⟩ ⟨x₂, y₂⟩, show algebra_map ℝ A (x₁ * x₂ - y₁ * y₂) + (x₁ * y₂ + y₁ * x₂) • I'
= (algebra_map ℝ A x₁ + y₁ • I') * (algebra_map ℝ A x₂ + y₂ • I'),
begin
rw [add_mul, mul_add, mul_add, add_comm _ (y₁ • I' * y₂ • I'), add_add_add_comm],
congr' 1, -- equate "real" and "imaginary" parts
{ rw [smul_mul_smul, hf, smul_neg, ←algebra.algebra_map_eq_smul_one, ←sub_eq_add_neg,
←ring_hom.map_mul, ←ring_hom.map_sub], },
{ rw [algebra.smul_def, algebra.smul_def, algebra.smul_def, ←algebra.right_comm _ x₂,
←mul_assoc, ←add_mul, ←ring_hom.map_mul, ←ring_hom.map_mul, ←ring_hom.map_add] }
end)
@[simp]
lemma lift_aux_apply (I' : A) (hI') (z : ℂ) :
lift_aux I' hI' z = algebra_map ℝ A z.re + z.im • I' := rfl
lemma lift_aux_apply_I (I' : A) (hI') : lift_aux I' hI' I = I' := by simp
/-- A universal property of the complex numbers, providing a unique `ℂ →ₐ[ℝ] A` for every element
of `A` which squares to `-1`.
This can be used to embed the complex numbers in the `quaternion`s.
This isomorphism is named to match the very similar `zsqrtd.lift`. -/
@[simps {simp_rhs := tt}]
def lift : {I' : A // I' * I' = -1} ≃ (ℂ →ₐ[ℝ] A) :=
{ to_fun := λ I', lift_aux I' I'.prop,
inv_fun := λ F, ⟨F I, by rw [←F.map_mul, I_mul_I, alg_hom.map_neg, alg_hom.map_one]⟩,
left_inv := λ I', subtype.ext $ lift_aux_apply_I I' I'.prop,
right_inv := λ F, alg_hom_ext $ lift_aux_apply_I _ _, }
/- When applied to `complex.I` itself, `lift` is the identity. -/
@[simp]
lemma lift_aux_I : lift_aux I I_mul_I = alg_hom.id ℝ ℂ :=
alg_hom_ext $ lift_aux_apply_I _ _
/- When applied to `-complex.I`, `lift` is conjugation, `conj`. -/
@[simp]
lemma lift_aux_neg_I : lift_aux (-I) ((neg_mul_neg _ _).trans I_mul_I) = conj_ae :=
alg_hom_ext $ (lift_aux_apply_I _ _).trans conj_I.symm
end lift
end complex
|
ce301c0e20655f1db58f4616d77f08c8dd71de89 | 42c01158c2730cc6ac3e058c1339c18cb90366e2 | /M1P2/group_theory.lean | e39076ef882041508eb426afd5dbed14949abaeb | [] | no_license | ChrisHughes24/xena | c80d94355d0c2ae8deddda9d01e6d31bc21c30ae | 337a0d7c9f0e255e08d6d0a383e303c080c6ec0c | refs/heads/master | 1,631,059,898,392 | 1,511,200,551,000 | 1,511,200,551,000 | 111,468,589 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 194 | lean | noncomputable theory
constant G : Type
@[instance] constant G_group : group G
variables a b c : G
example : a * (b⁻¹ * 1) = (b * a⁻¹)⁻¹ :=
begin
rw [mul_one,mul_inv_rev,inv_inv]
end
|
2fce7f691e1c7551b77797ad3bc4645e04bb72b1 | 74caf7451c921a8d5ab9c6e2b828c9d0a35aae95 | /library/init/meta/vm.lean | 1397c4d2a3448433329708e76bdcb647cb44176d | [
"Apache-2.0"
] | permissive | sakas--/lean | f37b6fad4fd4206f2891b89f0f8135f57921fc3f | 570d9052820be1d6442a5cc58ece37397f8a9e4c | refs/heads/master | 1,586,127,145,194 | 1,480,960,018,000 | 1,480,960,635,000 | 40,137,176 | 0 | 0 | null | 1,438,621,351,000 | 1,438,621,351,000 | null | UTF-8 | Lean | false | false | 6,365 | 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.data.option.basic
meta constant vm_obj : Type
inductive vm_obj_kind
| simple | constructor | closure | mpz
| name | level | expr | declaration
| environment | tactic_state | format
| options | other
namespace vm_obj
meta constant kind : vm_obj → vm_obj_kind
/- For simple and constructor vm_obj's, it returns the constructor tag/index.
Return 0 otherwise. -/
meta constant cidx : vm_obj → nat
/- For closure vm_obj's, it returns the internal function index. -/
meta constant fn_idx : vm_obj → nat
/- For constructor vm_obj's, it returns the data stored in the object.
For closure vm_obj's, it returns the local arguments captured by the closure. -/
meta constant fields : vm_obj → list vm_obj
/- For simple and mpz vm_obj's -/
meta constant to_nat : vm_obj → nat
/- For name vm_obj's, it returns the name wrapped by the vm_obj. -/
meta constant to_name : vm_obj → name
/- For level vm_obj's, it returns the universe level wrapped by the vm_obj. -/
meta constant to_level : vm_obj → level
/- For expr vm_obj's, it returns the expression wrapped by the vm_obj. -/
meta constant to_expr : vm_obj → expr
/- For declaration vm_obj's, it returns the declaration wrapped by the vm_obj. -/
meta constant to_declaration : vm_obj → declaration
/- For environment vm_obj's, it returns the environment wrapped by the vm_obj. -/
meta constant to_environment : vm_obj → environment
/- For tactic_state vm_obj's, it returns the tactic_state object wrapped by the vm_obj. -/
meta constant to_tactic_state : vm_obj → tactic_state
/- For format vm_obj's, it returns the format object wrapped by the vm_obj. -/
meta constant to_format : vm_obj → format
end vm_obj
meta constant vm_decl : Type
inductive vm_decl_kind
| bytecode | builtin | cfun
/- Information for local variables and arguments on the VM stack.
Remark: type is only available if it is a closed term at compilation time. -/
meta structure vm_local_info :=
(id : name) (type : option expr)
namespace vm_decl
meta constant kind : vm_decl → vm_decl_kind
meta constant to_name : vm_decl → name
/- Internal function index associated with the given VM declaration. -/
meta constant idx : vm_decl → nat
/- Number of arguments needed to execute the given VM declaration. -/
meta constant arity : vm_decl → nat
/- Return (line, column) if available -/
meta constant pos : vm_decl → option (nat × nat)
/- Return .olean file where the given VM declaration was imported from. -/
meta constant olean : vm_decl → option string
/- Return names .olean file where the given VM declaration was imported from. -/
meta constant args_info : vm_decl → list vm_local_info
end vm_decl
meta constant vm_core : Type → Type
meta constant vm_core.map {α β : Type} : (α → β) → vm_core α → vm_core β
meta constant vm_core.ret {α : Type} : α → vm_core α
meta constant vm_core.bind {α β : Type} : vm_core α → (α → vm_core β) → vm_core β
meta instance : monad vm_core :=
⟨@vm_core.map, @vm_core.ret, @vm_core.bind⟩
@[reducible] meta def vm (α : Type) : Type := option_t.{1 1} vm_core α
namespace vm
meta constant get_env : vm environment
meta constant get_decl : name → vm vm_decl
meta constant get_options : vm options
meta constant stack_size : vm nat
/- Return the vm_obj stored at the given position on the execution stack.
It fails if position >= vm.stack_size -/
meta constant stack_obj : nat → vm vm_obj
/- Return (name, type) for the object at the given position on the execution stack.
It fails if position >= vm.stack_size.
The name is anonymous if vm_obj is a transient value created by the compiler.
Type information is only recorded if the type is a closed term at compilation time. -/
meta constant stack_obj_info : nat → vm (name × option expr)
/- Pretty print the vm_obj at the given position on the execution stack. -/
meta constant pp_stack_obj : nat → vm format
/- Pretty print the given expression. -/
meta constant pp_expr : expr → vm format
/- Number of frames on the call stack. -/
meta constant call_stack_size : vm nat
/- Return the function name at the given stack frame.
Action fails if position >= vm.call_stack_size. -/
meta constant call_stack_fn : nat → vm name
/- Return the range [start, end) for the given stack frame.
Action fails if position >= vm.call_stack_size.
The values start and end correspond to positions at the execution stack.
We have that 0 <= start < end <= vm.stack_size -/
meta constant call_stack_var_range : nat → vm (nat × nat)
/- Return the name of the function on top of the call stack. -/
meta constant curr_fn : vm name
/- Return the base stack pointer for the frame on top of the call stack. -/
meta constant bp : vm nat
/- Return the program counter. -/
meta constant pc : vm nat
/- Convert the given vm_obj into a string -/
meta constant obj_to_string : vm_obj → vm string
meta constant put_str : string → vm unit
meta constant get_line : vm string
/- Return tt if end of the input stream has been reached.
For example, this can happen if the user presses Ctrl-D -/
meta constant eof : vm bool
/- Return the list of declarations tagged with the given attribute. -/
meta constant get_attribute : name → vm (list name)
meta def trace {α : Type} [has_to_format α] (a : α) : vm unit :=
do fmt ← return $ to_fmt a,
return $ _root_.trace_fmt fmt (λ u, ())
end vm
meta structure vm_monitor (s : Type) :=
(init : s) (step : s → vm s)
/- Registers a new virtual machine monitor. The argument must be the name of a definition of type
`vm_monitor S`. The command will override the last monitor.
If option 'debugger' is true, then the VM will initialize the vm_monitor state using the
'init' field, and will invoke the function 'step' before each instruction is invoked. -/
meta constant vm_monitor.register : name → command
|
ab399b92a085eb26c79d52a938d362b4a10ee944 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/data/zmod/basic.lean | 0ad419b8e5e77e00c6753b5d047e82b86d75cdb8 | [
"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 | 28,763 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import data.int.modeq
import algebra.char_p.basic
import data.nat.totient
import ring_theory.ideal.operations
import tactic.fin_cases
/-!
# Integers mod `n`
Definition of the integers mod n, and the field structure on the integers mod p.
## Definitions
* `zmod n`, which is for integers modulo a nat `n : ℕ`
* `val a` is defined as a natural number:
- for `a : zmod 0` it is the absolute value of `a`
- for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class
* `val_min_abs` returns the integer closest to zero in the equivalence class.
* A coercion `cast` is defined from `zmod n` into any ring.
This is a ring hom if the ring has characteristic dividing `n`
-/
namespace fin
/-!
## Ring structure on `fin n`
We define a commutative ring structure on `fin n`, but we do not register it as instance.
Afterwords, when we define `zmod n` in terms of `fin n`, we use these definitions
to register the ring structure on `zmod n` as type class instance.
-/
open nat nat.modeq int
/-- Multiplicative commutative semigroup structure on `fin (n+1)`. -/
instance (n : ℕ) : comm_semigroup (fin (n+1)) :=
{ mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(calc ((a * b) % (n+1) * c) ≡ a * b * c [MOD (n+1)] : modeq_mul (nat.mod_mod _ _) rfl
... ≡ a * (b * c) [MOD (n+1)] : by rw mul_assoc
... ≡ a * (b * c % (n+1)) [MOD (n+1)] : modeq_mul rfl (nat.mod_mod _ _).symm),
mul_comm := λ ⟨a, _⟩ ⟨b, _⟩,
fin.eq_of_veq (show (a * b) % (n+1) = (b * a) % (n+1), by rw mul_comm),
..fin.has_mul }
private lemma left_distrib_aux (n : ℕ) : ∀ a b c : fin (n+1), a * (b + c) = a * b + a * c :=
λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(calc a * ((b + c) % (n+1)) ≡ a * (b + c) [MOD (n+1)] : modeq_mul rfl (nat.mod_mod _ _)
... ≡ a * b + a * c [MOD (n+1)] : by rw mul_add
... ≡ (a * b) % (n+1) + (a * c) % (n+1) [MOD (n+1)] :
modeq_add (nat.mod_mod _ _).symm (nat.mod_mod _ _).symm)
/-- Commutative ring structure on `fin (n+1)`. -/
instance (n : ℕ) : comm_ring (fin (n+1)) :=
{ one_mul := fin.one_mul,
mul_one := fin.mul_one,
left_distrib := left_distrib_aux n,
right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl,
..fin.has_one,
..fin.add_comm_group n,
..fin.comm_semigroup n }
end fin
/-- The integers modulo `n : ℕ`. -/
def zmod : ℕ → Type
| 0 := ℤ
| (n+1) := fin (n+1)
namespace zmod
instance fintype : Π (n : ℕ) [fact (0 < n)], fintype (zmod n)
| 0 h := false.elim $ nat.not_lt_zero 0 h.1
| (n+1) _ := fin.fintype (n+1)
lemma card (n : ℕ) [fact (0 < n)] : fintype.card (zmod n) = n :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
{ exact fintype.card_fin (n+1) }
end
instance decidable_eq : Π (n : ℕ), decidable_eq (zmod n)
| 0 := int.decidable_eq
| (n+1) := fin.decidable_eq _
instance has_repr : Π (n : ℕ), has_repr (zmod n)
| 0 := int.has_repr
| (n+1) := fin.has_repr _
instance comm_ring : Π (n : ℕ), comm_ring (zmod n)
| 0 := int.comm_ring
| (n+1) := fin.comm_ring n
instance inhabited (n : ℕ) : inhabited (zmod n) := ⟨0⟩
/-- `val a` is a natural number defined as:
- for `a : zmod 0` it is the absolute value of `a`
- for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class
See `zmod.val_min_abs` for a variant that takes values in the integers.
-/
def val : Π {n : ℕ}, zmod n → ℕ
| 0 := int.nat_abs
| (n+1) := (coe : fin (n + 1) → ℕ)
lemma val_lt {n : ℕ} [fact (0 < n)] (a : zmod n) : a.val < n :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
exact fin.is_lt a
end
@[simp] lemma val_zero : ∀ {n}, (0 : zmod n).val = 0
| 0 := rfl
| (n+1) := rfl
@[simp] lemma val_one' : (1 : zmod 0).val = 1 := rfl
@[simp] lemma val_neg' {n : zmod 0} : (-n).val = n.val := by simp [val]
@[simp] lemma val_mul' {m n : zmod 0} : (m * n).val = m.val * n.val :=
by simp [val, int.nat_abs_mul]
lemma val_nat_cast {n : ℕ} (a : ℕ) : (a : zmod n).val = a % n :=
begin
casesI n,
{ rw [nat.mod_zero, int.nat_cast_eq_coe_nat],
exact int.nat_abs_of_nat a, },
rw ← fin.of_nat_eq_coe,
refl
end
instance (n : ℕ) : char_p (zmod n) n :=
{ cast_eq_zero_iff :=
begin
intro k,
cases n,
{ simp only [int.nat_cast_eq_coe_nat, zero_dvd_iff, int.coe_nat_eq_zero], },
rw [fin.eq_iff_veq],
show (k : zmod (n+1)).val = (0 : zmod (n+1)).val ↔ _,
rw [val_nat_cast, val_zero, nat.dvd_iff_mod_eq_zero],
end }
@[simp] lemma nat_cast_self (n : ℕ) : (n : zmod n) = 0 :=
char_p.cast_eq_zero (zmod n) n
@[simp] lemma nat_cast_self' (n : ℕ) : (n + 1 : zmod (n + 1)) = 0 :=
by rw [← nat.cast_add_one, nat_cast_self (n + 1)]
section universal_property
variables {n : ℕ} {R : Type*}
section
variables [has_zero R] [has_one R] [has_add R] [has_neg R]
/-- Cast an integer modulo `n` to another semiring.
This function is a morphism if the characteristic of `R` divides `n`.
See `zmod.cast_hom` for a bundled version. -/
def cast : Π {n : ℕ}, zmod n → R
| 0 := int.cast
| (n+1) := λ i, i.val
-- see Note [coercion into rings]
@[priority 900] instance (n : ℕ) : has_coe_t (zmod n) R := ⟨cast⟩
@[simp] lemma cast_zero : ((0 : zmod n) : R) = 0 :=
by { cases n; refl }
end
/-- So-named because the coercion is `nat.cast` into `zmod`. For `nat.cast` into an arbitrary ring,
see `zmod.nat_cast_val`. -/
lemma nat_cast_zmod_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : zmod n) = a :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
{ apply fin.coe_coe_eq_self }
end
lemma nat_cast_right_inverse [fact (0 < n)] : function.right_inverse val (coe : ℕ → zmod n) :=
nat_cast_zmod_val
lemma nat_cast_zmod_surjective [fact (0 < n)] : function.surjective (coe : ℕ → zmod n) :=
nat_cast_right_inverse.surjective
/-- So-named because the outer coercion is `int.cast` into `zmod`. For `int.cast` into an arbitrary
ring, see `zmod.int_cast_cast`. -/
lemma int_cast_zmod_cast (a : zmod n) : ((a : ℤ) : zmod n) = a :=
begin
cases n,
{ rw [int.cast_id a, int.cast_id a], },
{ rw [coe_coe, int.nat_cast_eq_coe_nat, int.cast_coe_nat, fin.coe_coe_eq_self] }
end
lemma int_cast_right_inverse : function.right_inverse (coe : zmod n → ℤ) (coe : ℤ → zmod n) :=
int_cast_zmod_cast
lemma int_cast_surjective : function.surjective (coe : ℤ → zmod n) :=
int_cast_right_inverse.surjective
@[norm_cast]
lemma cast_id : ∀ n (i : zmod n), ↑i = i
| 0 i := int.cast_id i
| (n+1) i := nat_cast_zmod_val i
@[simp]
lemma cast_id' : (coe : zmod n → zmod n) = id := funext (cast_id n)
variables (R) [ring R]
/-- The coercions are respectively `nat.cast` and `zmod.cast`. -/
@[simp] lemma nat_cast_comp_val [fact (0 < n)] :
(coe : ℕ → R) ∘ (val : zmod n → ℕ) = coe :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
refl
end
/-- The coercions are respectively `int.cast`, `zmod.cast`, and `zmod.cast`. -/
@[simp] lemma int_cast_comp_cast : (coe : ℤ → R) ∘ (coe : zmod n → ℤ) = coe :=
begin
cases n,
{ exact congr_arg ((∘) int.cast) zmod.cast_id', },
{ ext, simp }
end
variables {R}
@[simp] lemma nat_cast_val [fact (0 < n)] (i : zmod n) : (i.val : R) = i :=
congr_fun (nat_cast_comp_val R) i
@[simp] lemma int_cast_cast (i : zmod n) : ((i : ℤ) : R) = i :=
congr_fun (int_cast_comp_cast R) i
section char_dvd
/-! If the characteristic of `R` divides `n`, then `cast` is a homomorphism. -/
variables {n} {m : ℕ} [char_p R m]
@[simp] lemma cast_one (h : m ∣ n) : ((1 : zmod n) : R) = 1 :=
begin
casesI n,
{ exact int.cast_one },
show ((1 % (n+1) : ℕ) : R) = 1,
cases n, { rw [nat.dvd_one] at h, substI m, apply subsingleton.elim },
rw nat.mod_eq_of_lt,
{ exact nat.cast_one },
exact nat.lt_of_sub_eq_succ rfl
end
lemma cast_add (h : m ∣ n) (a b : zmod n) : ((a + b : zmod n) : R) = a + b :=
begin
casesI n,
{ apply int.cast_add },
simp only [coe_coe],
symmetry,
erw [fin.coe_add, ← nat.cast_add, ← sub_eq_zero, ← nat.cast_sub (nat.mod_le _ _),
@char_p.cast_eq_zero_iff R _ _ m],
exact dvd_trans h (nat.dvd_sub_mod _),
end
lemma cast_mul (h : m ∣ n) (a b : zmod n) : ((a * b : zmod n) : R) = a * b :=
begin
casesI n,
{ apply int.cast_mul },
simp only [coe_coe],
symmetry,
erw [fin.coe_mul, ← nat.cast_mul, ← sub_eq_zero, ← nat.cast_sub (nat.mod_le _ _),
@char_p.cast_eq_zero_iff R _ _ m],
exact dvd_trans h (nat.dvd_sub_mod _),
end
/-- The canonical ring homomorphism from `zmod n` to a ring of characteristic `n`. -/
def cast_hom (h : m ∣ n) (R : Type*) [ring R] [char_p R m] : zmod n →+* R :=
{ to_fun := coe,
map_zero' := cast_zero,
map_one' := cast_one h,
map_add' := cast_add h,
map_mul' := cast_mul h }
@[simp] lemma cast_hom_apply {h : m ∣ n} (i : zmod n) : cast_hom h R i = i := rfl
@[simp, norm_cast]
lemma cast_sub (h : m ∣ n) (a b : zmod n) : ((a - b : zmod n) : R) = a - b :=
(cast_hom h R).map_sub a b
@[simp, norm_cast]
lemma cast_neg (h : m ∣ n) (a : zmod n) : ((-a : zmod n) : R) = -a :=
(cast_hom h R).map_neg a
@[simp, norm_cast]
lemma cast_pow (h : m ∣ n) (a : zmod n) (k : ℕ) : ((a ^ k : zmod n) : R) = a ^ k :=
(cast_hom h R).map_pow a k
@[simp, norm_cast]
lemma cast_nat_cast (h : m ∣ n) (k : ℕ) : ((k : zmod n) : R) = k :=
(cast_hom h R).map_nat_cast k
@[simp, norm_cast]
lemma cast_int_cast (h : m ∣ n) (k : ℤ) : ((k : zmod n) : R) = k :=
(cast_hom h R).map_int_cast k
end char_dvd
section char_eq
/-! Some specialised simp lemmas which apply when `R` has characteristic `n`. -/
variable [char_p R n]
@[simp] lemma cast_one' : ((1 : zmod n) : R) = 1 :=
cast_one (dvd_refl _)
@[simp] lemma cast_add' (a b : zmod n) : ((a + b : zmod n) : R) = a + b :=
cast_add (dvd_refl _) a b
@[simp] lemma cast_mul' (a b : zmod n) : ((a * b : zmod n) : R) = a * b :=
cast_mul (dvd_refl _) a b
@[simp] lemma cast_sub' (a b : zmod n) : ((a - b : zmod n) : R) = a - b :=
cast_sub (dvd_refl _) a b
@[simp] lemma cast_pow' (a : zmod n) (k : ℕ) : ((a ^ k : zmod n) : R) = a ^ k :=
cast_pow (dvd_refl _) a k
@[simp, norm_cast]
lemma cast_nat_cast' (k : ℕ) : ((k : zmod n) : R) = k :=
cast_nat_cast (dvd_refl _) k
@[simp, norm_cast]
lemma cast_int_cast' (k : ℤ) : ((k : zmod n) : R) = k :=
cast_int_cast (dvd_refl _) k
instance (R : Type*) [comm_ring R] [char_p R n] : algebra (zmod n) R :=
(zmod.cast_hom (dvd_refl n) R).to_algebra
variables (R)
lemma cast_hom_injective : function.injective (zmod.cast_hom (dvd_refl n) R) :=
begin
rw ring_hom.injective_iff,
intro x,
obtain ⟨k, rfl⟩ := zmod.int_cast_surjective x,
rw [ring_hom.map_int_cast, char_p.int_cast_eq_zero_iff R n,
char_p.int_cast_eq_zero_iff (zmod n) n],
exact id
end
lemma cast_hom_bijective [fintype R] (h : fintype.card R = n) :
function.bijective (zmod.cast_hom (dvd_refl n) R) :=
begin
haveI : fact (0 < n) :=
⟨begin
rw [pos_iff_ne_zero],
intro hn,
rw hn at h,
exact (fintype.card_eq_zero_iff.mp h).elim' 0
end⟩,
rw [fintype.bijective_iff_injective_and_card, zmod.card, h, eq_self_iff_true, and_true],
apply zmod.cast_hom_injective
end
/-- The unique ring isomorphism between `zmod n` and a ring `R`
of characteristic `n` and cardinality `n`. -/
noncomputable def ring_equiv [fintype R] (h : fintype.card R = n) : zmod n ≃+* R :=
ring_equiv.of_bijective _ (zmod.cast_hom_bijective R h)
end char_eq
end universal_property
lemma int_coe_eq_int_coe_iff (a b : ℤ) (c : ℕ) :
(a : zmod c) = (b : zmod c) ↔ a ≡ b [ZMOD c] :=
char_p.int_coe_eq_int_coe_iff (zmod c) c a b
lemma int_coe_eq_int_coe_iff' (a b : ℤ) (c : ℕ) :
(a : zmod c) = (b : zmod c) ↔ a % c = b % c :=
zmod.int_coe_eq_int_coe_iff a b c
lemma nat_coe_eq_nat_coe_iff (a b c : ℕ) :
(a : zmod c) = (b : zmod c) ↔ a ≡ b [MOD c] :=
begin
convert zmod.int_coe_eq_int_coe_iff a b c,
simp [nat.modeq.modeq_iff_dvd, int.modeq.modeq_iff_dvd],
end
lemma int_coe_zmod_eq_zero_iff_dvd (a : ℤ) (b : ℕ) : (a : zmod b) = 0 ↔ (b : ℤ) ∣ a :=
begin
change (a : zmod b) = ((0 : ℤ) : zmod b) ↔ (b : ℤ) ∣ a,
rw [zmod.int_coe_eq_int_coe_iff, int.modeq.modeq_zero_iff],
end
lemma nat_coe_zmod_eq_zero_iff_dvd (a b : ℕ) : (a : zmod b) = 0 ↔ b ∣ a :=
begin
change (a : zmod b) = ((0 : ℕ) : zmod b) ↔ b ∣ a,
rw [zmod.nat_coe_eq_nat_coe_iff, nat.modeq.modeq_zero_iff],
end
@[push_cast, simp]
lemma int_cast_mod (a : ℤ) (b : ℕ) : ((a % b : ℤ) : zmod b) = (a : zmod b) :=
begin
rw zmod.int_coe_eq_int_coe_iff,
apply int.modeq.mod_modeq,
end
local attribute [semireducible] int.nonneg
@[simp] lemma nat_cast_to_nat (p : ℕ) :
∀ {z : ℤ} (h : 0 ≤ z), (z.to_nat : zmod p) = z
| (n : ℕ) h := by simp only [int.cast_coe_nat, int.to_nat_coe_nat]
| -[1+n] h := false.elim h
lemma val_injective (n : ℕ) [fact (0 < n)] :
function.injective (zmod.val : zmod n → ℕ) :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
assume a b h,
ext,
exact h
end
lemma val_one_eq_one_mod (n : ℕ) : (1 : zmod n).val = 1 % n :=
by rw [← nat.cast_one, val_nat_cast]
lemma val_one (n : ℕ) [fact (1 < n)] : (1 : zmod n).val = 1 :=
by { rw val_one_eq_one_mod, exact nat.mod_eq_of_lt (fact.out _) }
lemma val_add {n : ℕ} [fact (0 < n)] (a b : zmod n) : (a + b).val = (a.val + b.val) % n :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out _) },
{ apply fin.val_add }
end
lemma val_mul {n : ℕ} (a b : zmod n) : (a * b).val = (a.val * b.val) % n :=
begin
cases n,
{ rw nat.mod_zero, apply int.nat_abs_mul },
{ apply fin.val_mul }
end
instance nontrivial (n : ℕ) [fact (1 < n)] : nontrivial (zmod n) :=
⟨⟨0, 1, assume h, zero_ne_one $
calc 0 = (0 : zmod n).val : by rw val_zero
... = (1 : zmod n).val : congr_arg zmod.val h
... = 1 : val_one n ⟩⟩
/-- The inversion on `zmod n`.
It is setup in such a way that `a * a⁻¹` is equal to `gcd a.val n`.
In particular, if `a` is coprime to `n`, and hence a unit, `a * a⁻¹ = 1`. -/
def inv : Π (n : ℕ), zmod n → zmod n
| 0 i := int.sign i
| (n+1) i := nat.gcd_a i.val (n+1)
instance (n : ℕ) : has_inv (zmod n) := ⟨inv n⟩
lemma inv_zero : ∀ (n : ℕ), (0 : zmod n)⁻¹ = 0
| 0 := int.sign_zero
| (n+1) := show (nat.gcd_a _ (n+1) : zmod (n+1)) = 0,
by { rw val_zero, unfold nat.gcd_a nat.xgcd nat.xgcd_aux, refl }
lemma mul_inv_eq_gcd {n : ℕ} (a : zmod n) :
a * a⁻¹ = nat.gcd a.val n :=
begin
cases n,
{ calc a * a⁻¹ = a * int.sign a : rfl
... = a.nat_abs : by rw [int.mul_sign, int.nat_cast_eq_coe_nat]
... = a.val.gcd 0 : by rw nat.gcd_zero_right; refl },
{ set k := n.succ,
calc a * a⁻¹ = a * a⁻¹ + k * nat.gcd_b (val a) k : by rw [nat_cast_self, zero_mul, add_zero]
... = ↑(↑a.val * nat.gcd_a (val a) k + k * nat.gcd_b (val a) k) :
by { push_cast, rw nat_cast_zmod_val, refl }
... = nat.gcd a.val k : (congr_arg coe (nat.gcd_eq_gcd_ab a.val k)).symm, }
end
@[simp] lemma nat_cast_mod (n : ℕ) (a : ℕ) : ((a % n : ℕ) : zmod n) = a :=
by conv {to_rhs, rw ← nat.mod_add_div a n}; simp
lemma eq_iff_modeq_nat (n : ℕ) {a b : ℕ} : (a : zmod n) = b ↔ a ≡ b [MOD n] :=
begin
cases n,
{ simp only [nat.modeq, int.coe_nat_inj', nat.mod_zero, int.nat_cast_eq_coe_nat], },
{ rw [fin.ext_iff, nat.modeq, ← val_nat_cast, ← val_nat_cast], exact iff.rfl, }
end
lemma coe_mul_inv_eq_one {n : ℕ} (x : ℕ) (h : nat.coprime x n) :
(x * x⁻¹ : zmod n) = 1 :=
begin
rw [nat.coprime, nat.gcd_comm, nat.gcd_rec] at h,
rw [mul_inv_eq_gcd, val_nat_cast, h, nat.cast_one],
end
/-- `unit_of_coprime` makes an element of `units (zmod n)` given
a natural number `x` and a proof that `x` is coprime to `n` -/
def unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : units (zmod n) :=
⟨x, x⁻¹, coe_mul_inv_eq_one x h, by rw [mul_comm, coe_mul_inv_eq_one x h]⟩
@[simp] lemma coe_unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) :
(unit_of_coprime x h : zmod n) = x := rfl
lemma val_coe_unit_coprime {n : ℕ} (u : units (zmod n)) :
nat.coprime (u : zmod n).val n :=
begin
cases n,
{ rcases int.units_eq_one_or u with rfl|rfl; simp },
apply nat.modeq.coprime_of_mul_modeq_one ((u⁻¹ : units (zmod (n+1))) : zmod (n+1)).val,
have := units.ext_iff.1 (mul_right_inv u),
rw [units.coe_one] at this,
rw [← eq_iff_modeq_nat, nat.cast_one, ← this], clear this,
rw [← nat_cast_zmod_val ((u * u⁻¹ : units (zmod (n+1))) : zmod (n+1))],
rw [units.coe_mul, val_mul, nat_cast_mod],
end
@[simp] lemma inv_coe_unit {n : ℕ} (u : units (zmod n)) :
(u : zmod n)⁻¹ = (u⁻¹ : units (zmod n)) :=
begin
have := congr_arg (coe : ℕ → zmod n) (val_coe_unit_coprime u),
rw [← mul_inv_eq_gcd, nat.cast_one] at this,
let u' : units (zmod n) := ⟨u, (u : zmod n)⁻¹, this, by rwa mul_comm⟩,
have h : u = u', { apply units.ext, refl },
rw h,
refl
end
lemma mul_inv_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) :
a * a⁻¹ = 1 :=
begin
rcases h with ⟨u, rfl⟩,
rw [inv_coe_unit, u.mul_inv],
end
lemma inv_mul_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) :
a⁻¹ * a = 1 :=
by rw [mul_comm, mul_inv_of_unit a h]
/-- Equivalence between the units of `zmod n` and
the subtype of terms `x : zmod n` for which `x.val` is comprime to `n` -/
def units_equiv_coprime {n : ℕ} [fact (0 < n)] :
units (zmod n) ≃ {x : zmod n // nat.coprime x.val n} :=
{ to_fun := λ x, ⟨x, val_coe_unit_coprime x⟩,
inv_fun := λ x, unit_of_coprime x.1.val x.2,
left_inv := λ ⟨_, _, _, _⟩, units.ext (nat_cast_zmod_val _),
right_inv := λ ⟨_, _⟩, by simp }
section totient
open_locale nat
@[simp] lemma card_units_eq_totient (n : ℕ) [fact (0 < n)] :
fintype.card (units (zmod n)) = φ n :=
calc fintype.card (units (zmod n)) = fintype.card {x : zmod n // x.val.coprime n} :
fintype.card_congr zmod.units_equiv_coprime
... = φ n :
begin
apply finset.card_congr (λ (a : {x : zmod n // x.val.coprime n}) _, a.1.val),
{ intro a, simp [(a : zmod n).val_lt, a.prop.symm] {contextual := tt} },
{ intros _ _ _ _ h, rw subtype.ext_iff_val, apply val_injective, exact h, },
{ intros b hb,
rw [finset.mem_filter, finset.mem_range] at hb,
refine ⟨⟨b, _⟩, finset.mem_univ _, _⟩,
{ let u := unit_of_coprime b hb.2.symm,
exact val_coe_unit_coprime u },
{ show zmod.val (b : zmod n) = b,
rw [val_nat_cast, nat.mod_eq_of_lt hb.1], } }
end
end totient
instance subsingleton_units : subsingleton (units (zmod 2)) :=
⟨λ x y, begin
ext1,
cases x with x xi hx1 hx2,
cases y with y yi hy1 hy2,
revert hx1 hx2 hy1 hy2,
fin_cases x; fin_cases y; simp
end⟩
lemma le_div_two_iff_lt_neg (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)]
{x : zmod n} (hx0 : x ≠ 0) : x.val ≤ (n / 2 : ℕ) ↔ (n / 2 : ℕ) < (-x).val :=
begin
haveI npos : fact (0 < n) := ⟨by
{ apply (nat.eq_zero_or_pos n).resolve_left,
unfreezingI { rintro rfl },
simpa [fact_iff] using hn, }⟩,
have hn2 : (n : ℕ) / 2 < n := nat.div_lt_of_lt_mul
((lt_mul_iff_one_lt_left npos.1).2 dec_trivial),
have hn2' : (n : ℕ) - n / 2 = n / 2 + 1,
{ conv {to_lhs, congr, rw [← nat.succ_sub_one n, nat.succ_sub npos.1]},
rw [← nat.two_mul_odd_div_two hn.1, two_mul, ← nat.succ_add, nat.add_sub_cancel], },
have hxn : (n : ℕ) - x.val < n,
{ rw [nat.sub_lt_iff (le_of_lt x.val_lt) (le_refl _), nat.sub_self],
rw ← zmod.nat_cast_zmod_val x at hx0,
exact nat.pos_of_ne_zero (λ h, by simpa [h] using hx0) },
by conv {to_rhs, rw [← nat.succ_le_iff, nat.succ_eq_add_one, ← hn2', ← zero_add (- x),
← zmod.nat_cast_self, ← sub_eq_add_neg, ← zmod.nat_cast_zmod_val x,
← nat.cast_sub (le_of_lt x.val_lt),
zmod.val_nat_cast, nat.mod_eq_of_lt hxn, nat.sub_le_sub_left_iff (le_of_lt x.val_lt)] }
end
lemma ne_neg_self (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {a : zmod n} (ha : a ≠ 0) : a ≠ -a :=
λ h, have a.val ≤ n / 2 ↔ (n : ℕ) / 2 < (-a).val := le_div_two_iff_lt_neg n ha,
by rwa [← h, ← not_lt, not_iff_self] at this
lemma neg_one_ne_one {n : ℕ} [fact (2 < n)] :
(-1 : zmod n) ≠ 1 :=
char_p.neg_one_ne_one (zmod n) n
@[simp] lemma neg_eq_self_mod_two (a : zmod 2) : -a = a :=
by fin_cases a; ext; simp [fin.coe_neg, int.nat_mod]; norm_num
@[simp] lemma nat_abs_mod_two (a : ℤ) : (a.nat_abs : zmod 2) = a :=
begin
cases a,
{ simp only [int.nat_abs_of_nat, int.cast_coe_nat, int.of_nat_eq_coe] },
{ simp only [neg_eq_self_mod_two, nat.cast_succ, int.nat_abs, int.cast_neg_succ_of_nat] }
end
@[simp] lemma val_eq_zero : ∀ {n : ℕ} (a : zmod n), a.val = 0 ↔ a = 0
| 0 a := int.nat_abs_eq_zero
| (n+1) a := by { rw fin.ext_iff, exact iff.rfl }
lemma val_cast_of_lt {n : ℕ} {a : ℕ} (h : a < n) : (a : zmod n).val = a :=
by rw [val_nat_cast, nat.mod_eq_of_lt h]
lemma neg_val' {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = (n - a.val) % n :=
begin
have : ((-a).val + a.val) % n = (n - a.val + a.val) % n,
{ rw [←val_add, add_left_neg, nat.sub_add_cancel (le_of_lt a.val_lt), nat.mod_self, val_zero], },
calc (-a).val = val (-a) % n : by rw nat.mod_eq_of_lt ((-a).val_lt)
... = (n - val a) % n : nat.modeq.modeq_add_cancel_right rfl this
end
lemma neg_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = if a = 0 then 0 else n - a.val :=
begin
rw neg_val',
by_cases h : a = 0, { rw [if_pos h, h, val_zero, nat.sub_zero, nat.mod_self] },
rw if_neg h,
apply nat.mod_eq_of_lt,
apply nat.sub_lt (fact.out (0 < n)),
contrapose! h,
rwa [nat.le_zero_iff, val_eq_zero] at h,
end
/-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`,
The result will be in the interval `(-n/2, n/2]`. -/
def val_min_abs : Π {n : ℕ}, zmod n → ℤ
| 0 x := x
| n@(_+1) x := if x.val ≤ n / 2 then x.val else (x.val : ℤ) - n
@[simp] lemma val_min_abs_def_zero (x : zmod 0) : val_min_abs x = x := rfl
lemma val_min_abs_def_pos {n : ℕ} [fact (0 < n)] (x : zmod n) :
val_min_abs x = if x.val ≤ n / 2 then x.val else x.val - n :=
begin
casesI n,
{ exfalso, exact nat.not_lt_zero 0 (fact.out (0 < 0)) },
{ refl }
end
@[simp] lemma coe_val_min_abs : ∀ {n : ℕ} (x : zmod n), (x.val_min_abs : zmod n) = x
| 0 x := int.cast_id x
| k@(n+1) x :=
begin
rw val_min_abs_def_pos,
split_ifs,
{ rw [int.cast_coe_nat, nat_cast_zmod_val] },
{ rw [int.cast_sub, int.cast_coe_nat, nat_cast_zmod_val, int.cast_coe_nat, nat_cast_self,
sub_zero] }
end
lemma nat_abs_val_min_abs_le {n : ℕ} [fact (0 < n)] (x : zmod n) : x.val_min_abs.nat_abs ≤ n / 2 :=
begin
rw zmod.val_min_abs_def_pos,
split_ifs with h, { exact h },
have : (x.val - n : ℤ) ≤ 0,
{ rw [sub_nonpos, int.coe_nat_le], exact le_of_lt x.val_lt, },
rw [← int.coe_nat_le, int.of_nat_nat_abs_of_nonpos this, neg_sub],
conv_lhs { congr, rw [← nat.mod_add_div n 2, int.coe_nat_add, int.coe_nat_mul,
int.coe_nat_bit0, int.coe_nat_one] },
suffices : ((n % 2 : ℕ) + (n / 2) : ℤ) ≤ (val x),
{ rw ← sub_nonneg at this ⊢, apply le_trans this (le_of_eq _), ring_nf, ring },
norm_cast,
calc (n : ℕ) % 2 + n / 2 ≤ 1 + n / 2 :
nat.add_le_add_right (nat.le_of_lt_succ (nat.mod_lt _ dec_trivial)) _
... ≤ x.val :
by { rw add_comm, exact nat.succ_le_of_lt (lt_of_not_ge h) }
end
@[simp] lemma val_min_abs_zero : ∀ n, (0 : zmod n).val_min_abs = 0
| 0 := by simp only [val_min_abs_def_zero]
| (n+1) := by simp only [val_min_abs_def_pos, if_true, int.coe_nat_zero, zero_le, val_zero]
@[simp] lemma val_min_abs_eq_zero {n : ℕ} (x : zmod n) :
x.val_min_abs = 0 ↔ x = 0 :=
begin
cases n, { simp },
split,
{ simp only [val_min_abs_def_pos, int.coe_nat_succ],
split_ifs with h h; assume h0,
{ apply val_injective, rwa [int.coe_nat_eq_zero] at h0, },
{ apply absurd h0, rw sub_eq_zero, apply ne_of_lt, exact_mod_cast x.val_lt } },
{ rintro rfl, rw val_min_abs_zero }
end
lemma nat_cast_nat_abs_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) :
(a.val_min_abs.nat_abs : zmod n) = if a.val ≤ (n : ℕ) / 2 then a else -a :=
begin
have : (a.val : ℤ) - n ≤ 0,
by { erw [sub_nonpos, int.coe_nat_le], exact le_of_lt a.val_lt, },
rw [zmod.val_min_abs_def_pos],
split_ifs,
{ rw [int.nat_abs_of_nat, nat_cast_zmod_val] },
{ rw [← int.cast_coe_nat, int.of_nat_nat_abs_of_nonpos this, int.cast_neg, int.cast_sub],
rw [int.cast_coe_nat, int.cast_coe_nat, nat_cast_self, sub_zero, nat_cast_zmod_val], }
end
@[simp] lemma nat_abs_val_min_abs_neg {n : ℕ} (a : zmod n) :
(-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs :=
begin
cases n, { simp only [int.nat_abs_neg, val_min_abs_def_zero], },
by_cases ha0 : a = 0, { rw [ha0, neg_zero] },
by_cases haa : -a = a, { rw [haa] },
suffices hpa : (n+1 : ℕ) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val,
{ rw [val_min_abs_def_pos, val_min_abs_def_pos],
rw ← not_le at hpa,
simp only [if_neg ha0, neg_val, hpa, int.coe_nat_sub (le_of_lt a.val_lt)],
split_ifs,
all_goals { rw [← int.nat_abs_neg], congr' 1, ring } },
suffices : (((n+1 : ℕ) % 2) + 2 * ((n + 1) / 2)) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val,
by rwa [nat.mod_add_div] at this,
suffices : (n + 1) % 2 + (n + 1) / 2 ≤ val a ↔ (n + 1) / 2 < val a,
by rw [nat.sub_le_iff, two_mul, ← add_assoc, nat.add_sub_cancel, this],
cases (n + 1 : ℕ).mod_two_eq_zero_or_one with hn0 hn1,
{ split,
{ assume h,
apply lt_of_le_of_ne (le_trans (nat.le_add_left _ _) h),
contrapose! haa,
rw [← zmod.nat_cast_zmod_val a, ← haa, neg_eq_iff_add_eq_zero, ← nat.cast_add],
rw [char_p.cast_eq_zero_iff (zmod (n+1)) (n+1)],
rw [← two_mul, ← zero_add (2 * _), ← hn0, nat.mod_add_div] },
{ rw [hn0, zero_add], exact le_of_lt } },
{ rw [hn1, add_comm, nat.succ_le_iff] }
end
lemma val_eq_ite_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) :
(a.val : ℤ) = a.val_min_abs + if a.val ≤ n / 2 then 0 else n :=
by { rw [zmod.val_min_abs_def_pos], split_ifs; simp only [add_zero, sub_add_cancel] }
lemma prime_ne_zero (p q : ℕ) [hp : fact p.prime] [hq : fact q.prime] (hpq : p ≠ q) :
(q : zmod p) ≠ 0 :=
by rwa [← nat.cast_zero, ne.def, eq_iff_modeq_nat, nat.modeq.modeq_zero_iff,
← hp.1.coprime_iff_not_dvd, nat.coprime_primes hp.1 hq.1]
end zmod
namespace zmod
variables (p : ℕ) [fact p.prime]
private lemma mul_inv_cancel_aux (a : zmod p) (h : a ≠ 0) : a * a⁻¹ = 1 :=
begin
obtain ⟨k, rfl⟩ := nat_cast_zmod_surjective a,
apply coe_mul_inv_eq_one,
apply nat.coprime.symm,
rwa [nat.prime.coprime_iff_not_dvd (fact.out p.prime), ← char_p.cast_eq_zero_iff (zmod p)]
end
/-- Field structure on `zmod p` if `p` is prime. -/
instance : field (zmod p) :=
{ mul_inv_cancel := mul_inv_cancel_aux p,
inv_zero := inv_zero p,
.. zmod.comm_ring p,
.. zmod.has_inv p,
.. zmod.nontrivial p }
end zmod
lemma ring_hom.ext_zmod {n : ℕ} {R : Type*} [semiring R] (f g : (zmod n) →+* R) : f = g :=
begin
ext a,
obtain ⟨k, rfl⟩ := zmod.int_cast_surjective a,
let φ : ℤ →+* R := f.comp (int.cast_ring_hom (zmod n)),
let ψ : ℤ →+* R := g.comp (int.cast_ring_hom (zmod n)),
show φ k = ψ k,
rw φ.ext_int ψ,
end
namespace zmod
variables {n : ℕ} {R : Type*}
instance subsingleton_ring_hom [semiring R] : subsingleton ((zmod n) →+* R) :=
⟨ring_hom.ext_zmod⟩
instance subsingleton_ring_equiv [semiring R] : subsingleton (zmod n ≃+* R) :=
⟨λ f g, by { rw ring_equiv.coe_ring_hom_inj_iff, apply ring_hom.ext_zmod _ _ }⟩
@[simp] lemma ring_hom_map_cast [ring R] (f : R →+* (zmod n)) (k : zmod n) :
f k = k :=
by { cases n; simp }
lemma ring_hom_right_inverse [ring R] (f : R →+* (zmod n)) :
function.right_inverse (coe : zmod n → R) f :=
ring_hom_map_cast f
lemma ring_hom_surjective [ring R] (f : R →+* (zmod n)) : function.surjective f :=
(ring_hom_right_inverse f).surjective
lemma ring_hom_eq_of_ker_eq [comm_ring R] (f g : R →+* (zmod n))
(h : f.ker = g.ker) : f = g :=
begin
have := f.lift_of_right_inverse_comp _ (zmod.ring_hom_right_inverse f) ⟨g, le_of_eq h⟩,
rw subtype.coe_mk at this,
rw [←this, ring_hom.ext_zmod (f.lift_of_right_inverse _ _ _) (ring_hom.id _), ring_hom.id_comp],
end
end zmod
|
2c6c27f97322fb6c9662d99ce87d980a9f36b376 | 48eee836fdb5c613d9a20741c17db44c8e12e61c | /src/algebra/theories/monoid.lean | 705470a3c40479bfe16ed5ff2697ad22a03dbf89 | [
"Apache-2.0"
] | permissive | fgdorais/lean-universal | 06430443a4abe51e303e602684c2977d1f5c0834 | 9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1 | refs/heads/master | 1,592,479,744,136 | 1,589,473,399,000 | 1,589,473,399,000 | 196,287,552 | 1 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 3,487 | lean | -- Copyright © 2019 François G. Dorais. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
import .basic
import .semigroup
import .unital
set_option default_priority 0
namespace algebra
signature monoid (α : Type*) :=
(op : α → α → α)
(id : α)
namespace monoid_sig
variables {α : Type*} (s : monoid_sig α)
@[signature_instance]
definition to_semigroup : semigroup_sig α :=
{ op := s.op
}
@[signature_instance]
definition to_unital : unital_sig α :=
{ op := s.op
, id := s.id
}
end monoid_sig
variables {α : Type*} (s : monoid_sig α)
local infix ∙ := s.op
local notation `e` := s.id
@[theory]
class monoid : Prop := intro ::
(associative : identity.op_associative s.op)
(left_identity : identity.op_left_identity s.op s.id)
(right_identity : identity.op_right_identity s.op s.id)
namespace monoid
variable [i : monoid s]
include i
instance to_semigroup : semigroup s.to_semigroup := semigroup.infer _
instance to_unital : unital s.to_unital := unital.infer _
end monoid
@[theory]
class cancel_monoid : Prop := intro ::
(associative : identity.op_associative s.op)
(left_identity : identity.op_left_identity s.op s.id)
(right_identity : identity.op_right_identity s.op s.id)
(left_cancellative : identity.op_left_cancellative s.op)
(right_cancellative : identity.op_right_cancellative s.op)
namespace cancel_monoid
variable [i : cancel_monoid s]
include i
instance to_monoid : monoid s := monoid.infer _
instance to_cancel_semigroup : cancel_semigroup s.to_semigroup := cancel_semigroup.infer _
instance to_cancel_unital : cancel_unital s.to_unital := cancel_unital.infer _
end cancel_monoid
@[theory]
class comm_monoid : Prop := intro ::
(associative : identity.op_associative s.op)
(commutative : identity.op_commutative s.op)
(right_identity : identity.op_right_identity s.op s.id)
namespace comm_monoid
variables [i : comm_monoid s]
include i
@[identity_instance]
theorem left_identity : identity.op_left_identity s.op s.id :=
λ x, show e ∙ x = x, from calc _
= x ∙ e : by rw op_commutative s.op ...
= x : by rw op_right_identity s.op
instance to_monoid : monoid s := monoid.infer _
instance to_comm_semigroup : comm_semigroup s.to_semigroup := comm_semigroup.infer _
instance to_comm_unital : comm_unital s.to_unital := comm_unital.infer _
end comm_monoid
@[theory]
class cancel_comm_monoid : Prop := intro ::
(associative : identity.op_associative s.op)
(commutative : identity.op_commutative s.op)
(right_identity : identity.op_right_identity s.op s.id)
(right_cancellative : identity.op_right_cancellative s.op)
namespace cancel_comm_monoid
variable [i : cancel_comm_monoid s]
include i
instance to_comm_monoid : comm_monoid s := comm_monoid.infer _
instance to_cancel_comm_semigroup : cancel_comm_semigroup s.to_semigroup := cancel_comm_semigroup.infer _
instance to_cancel_monoid : cancel_monoid s := cancel_monoid.infer _
instance to_cancel_comm_unital : cancel_comm_unital s.to_unital := cancel_comm_unital.infer _
end cancel_comm_monoid
@[theory]
class left_monoid_action {β : Type*} (t : left_action_sig α β) : Prop := intro ::
(left_compatible : identity.op_left_compatible t.act s.op)
(left_identity : identity.op_left_identity t.act s.id)
@[theory]
class right_monoid_action {β : Type*} (t : right_action_sig α β) : Prop := intro ::
(right_compatible : identity.op_right_compatible t.act s.op)
(right_identity : identity.op_right_identity t.act s.id)
end algebra
|
486e5a70e227902d63275586a404a3688347d4b7 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/termElab.lean | d41055556f2c8fb42b2bf04bda58bd7b578d0c78 | [
"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 | 683 | lean | import Lean
open Lean
open Lean.Elab
open Lean.Elab.Term
def tst1 : TermElabM Unit := do
let opt ← getOptions;
let stx ← `(forall (a b : Nat), Nat);
IO.println "message 1"; -- This message goes direct to stdio. It will be displayed before trace messages.
let e ← elabTermAndSynthesize stx none;
trace[Elab.debug] m!">>> {e}"; -- display message when `trace.Elab.debug` is true
IO.println "message 2"
#eval tst1
def tst2 : TermElabM Unit := do
let opt ← getOptions;
let a := mkIdent `a;
let b := mkIdent `b;
let stx ← `((fun ($a : Type) (x : $a) => @id $a x) _ 1);
let e ← elabTermAndSynthesize stx none;
trace[Elab.debug] m!">>> {e}";
throwErrorIfErrors
#eval tst2
|
2f37d1a9c49c728de382f8a862bc6971131f6346 | 1717bcbca047a0d25d687e7e9cd482fba00d058f | /src/topology/subset_properties.lean | f4ee3a5dcaa23c59b5b2bf72ecf68e656b8c507a | [
"Apache-2.0"
] | permissive | swapnilkapoor22/mathlib | 51ad5804e6a0635ed5c7611cee73e089ab271060 | 3e7efd4ecd5d379932a89212eebd362beb01309e | refs/heads/master | 1,676,467,741,465 | 1,610,301,556,000 | 1,610,301,556,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 65,505 | 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, Yury Kudryashov
-/
import topology.continuous_on
import data.finset.order
/-!
# Properties of subsets of topological spaces
## Main definitions
`compact`, `is_clopen`, `is_irreducible`, `is_connected`, `is_totally_disconnected`,
`is_totally_separated`
TODO: write better docs
## On the definition of irreducible and connected sets/spaces
In informal mathematics, irreducible and connected spaces are assumed to be nonempty.
We formalise the predicate without that assumption
as `is_preirreducible` and `is_preconnected` respectively.
In other words, the only difference is whether the empty space
counts as irreducible and/or connected.
There are good reasons to consider the empty space to be “too simple to be simple”
See also https://ncatlab.org/nlab/show/too+simple+to+be+simple,
and in particular
https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions.
-/
open set filter classical
open_locale classical topological_space filter
universes u v
variables {α : Type u} {β : Type v} [topological_space α] {s t : set α}
/- compact sets -/
section compact
/-- A set `s` is compact if for every filter `f` that contains `s`,
every set of `f` also meets every neighborhood of some `a ∈ s`. -/
def is_compact (s : set α) := ∀ ⦃f⦄ [ne_bot f], f ≤ 𝓟 s → ∃a∈s, cluster_pt a f
/-- The complement to a compact set belongs to a filter `f` if it belongs to each filter
`𝓝 a ⊓ f`, `a ∈ s`. -/
lemma is_compact.compl_mem_sets (hs : is_compact s) {f : filter α} (hf : ∀ a ∈ s, sᶜ ∈ 𝓝 a ⊓ f) :
sᶜ ∈ f :=
begin
contrapose! hf,
simp only [mem_iff_inf_principal_compl, compl_compl, inf_assoc, ← exists_prop] at hf ⊢,
exact @hs _ hf inf_le_right
end
/-- The complement to a compact set belongs to a filter `f` if each `a ∈ s` has a neighborhood `t`
within `s` such that `tᶜ` belongs to `f`. -/
lemma is_compact.compl_mem_sets_of_nhds_within (hs : is_compact s) {f : filter α}
(hf : ∀ a ∈ s, ∃ t ∈ 𝓝[s] a, tᶜ ∈ f) :
sᶜ ∈ f :=
begin
refine hs.compl_mem_sets (λ a ha, _),
rcases hf a ha with ⟨t, ht, hst⟩,
replace ht := mem_inf_principal.1 ht,
refine mem_inf_sets.2 ⟨_, ht, _, hst, _⟩,
rintros x ⟨h₁, h₂⟩ hs,
exact h₂ (h₁ hs)
end
/-- If `p : set α → Prop` is stable under restriction and union, and each point `x of a compact set `s`
has a neighborhood `t` within `s` such that `p t`, then `p s` holds. -/
@[elab_as_eliminator]
lemma is_compact.induction_on {s : set α} (hs : is_compact s) {p : set α → Prop} (he : p ∅)
(hmono : ∀ ⦃s t⦄, s ⊆ t → p t → p s) (hunion : ∀ ⦃s t⦄, p s → p t → p (s ∪ t))
(hnhds : ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, p t) :
p s :=
let f : filter α :=
{ sets := {t | p tᶜ},
univ_sets := by simpa,
sets_of_superset := λ t₁ t₂ ht₁ ht, hmono (compl_subset_compl.2 ht) ht₁,
inter_sets := λ t₁ t₂ ht₁ ht₂, by simp [compl_inter, hunion ht₁ ht₂] } in
have sᶜ ∈ f, from hs.compl_mem_sets_of_nhds_within (by simpa using hnhds),
by simpa
/-- The intersection of a compact set and a closed set is a compact set. -/
lemma is_compact.inter_right (hs : is_compact s) (ht : is_closed t) :
is_compact (s ∩ t) :=
begin
introsI f hnf hstf,
obtain ⟨a, hsa, ha⟩ : ∃ a ∈ s, cluster_pt a f :=
hs (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))),
have : a ∈ t :=
(ht.mem_of_nhds_within_ne_bot $ ha.mono $
le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))),
exact ⟨a, ⟨hsa, this⟩, ha⟩
end
/-- The intersection of a closed set and a compact set is a compact set. -/
lemma is_compact.inter_left (ht : is_compact t) (hs : is_closed s) : is_compact (s ∩ t) :=
inter_comm t s ▸ ht.inter_right hs
/-- The set difference of a compact set and an open set is a compact set. -/
lemma compact_diff (hs : is_compact s) (ht : is_open t) : is_compact (s \ t) :=
hs.inter_right (is_closed_compl_iff.mpr ht)
/-- A closed subset of a compact set is a compact set. -/
lemma compact_of_is_closed_subset (hs : is_compact s) (ht : is_closed t) (h : t ⊆ s) :
is_compact t :=
inter_eq_self_of_subset_right h ▸ hs.inter_right ht
lemma is_compact.adherence_nhdset {f : filter α}
(hs : is_compact s) (hf₂ : f ≤ 𝓟 s) (ht₁ : is_open t) (ht₂ : ∀a∈s, cluster_pt a f → a ∈ t) :
t ∈ f :=
classical.by_cases mem_sets_of_eq_bot $
assume : f ⊓ 𝓟 tᶜ ≠ ⊥,
let ⟨a, ha, (hfa : cluster_pt a $ f ⊓ 𝓟 tᶜ)⟩ := @@hs this $ inf_le_left_of_le hf₂ in
have a ∈ t,
from ht₂ a ha (hfa.of_inf_left),
have tᶜ ∩ t ∈ 𝓝[tᶜ] a,
from inter_mem_nhds_within _ (mem_nhds_sets ht₁ this),
have A : 𝓝[tᶜ] a = ⊥,
from empty_in_sets_eq_bot.1 $ compl_inter_self t ▸ this,
have 𝓝[tᶜ] a ≠ ⊥,
from hfa.of_inf_right,
absurd A this
lemma compact_iff_ultrafilter_le_nhds :
is_compact s ↔ (∀f : ultrafilter α, ↑f ≤ 𝓟 s → ∃a∈s, ↑f ≤ 𝓝 a) :=
begin
refine (forall_ne_bot_le_iff _).trans _,
{ rintro f g hle ⟨a, has, haf⟩,
exact ⟨a, has, haf.mono hle⟩ },
{ simp only [ultrafilter.cluster_pt_iff] }
end
alias compact_iff_ultrafilter_le_nhds ↔ is_compact.ultrafilter_le_nhds _
/-- For every open cover of a compact set, there exists a finite subcover. -/
lemma is_compact.elim_finite_subcover {ι : Type v} (hs : is_compact s)
(U : ι → set α) (hUo : ∀i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) :
∃ t : finset ι, s ⊆ ⋃ i ∈ t, U i :=
is_compact.induction_on hs ⟨∅, empty_subset _⟩ (λ s₁ s₂ hs ⟨t, hs₂⟩, ⟨t, subset.trans hs hs₂⟩)
(λ s₁ s₂ ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩,
⟨t₁ ∪ t₂, by { rw [finset.bUnion_union], exact union_subset_union ht₁ ht₂ }⟩)
(λ x hx, let ⟨i, hi⟩ := mem_Union.1 (hsU hx) in
⟨U i, mem_nhds_within.2 ⟨U i, hUo i, hi, inter_subset_left _ _⟩, {i}, by simp⟩)
/-- For every family of closed sets whose intersection avoids a compact set,
there exists a finite subfamily whose intersection avoids this compact set. -/
lemma is_compact.elim_finite_subfamily_closed {s : set α} {ι : Type v} (hs : is_compact s)
(Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : s ∩ (⋂ i, Z i) = ∅) :
∃ t : finset ι, s ∩ (⋂ i ∈ t, Z i) = ∅ :=
let ⟨t, ht⟩ := hs.elim_finite_subcover (λ i, (Z i)ᶜ) hZc
(by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union,
exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using hsZ)
in
⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union,
exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using ht⟩
/-- To show that a compact set intersects the intersection of a family of closed sets,
it is sufficient to show that it intersects every finite subfamily. -/
lemma is_compact.inter_Inter_nonempty {s : set α} {ι : Type v} (hs : is_compact s)
(Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : ∀ t : finset ι, (s ∩ ⋂ i ∈ t, Z i).nonempty) :
(s ∩ ⋂ i, Z i).nonempty :=
begin
simp only [← ne_empty_iff_nonempty] at hsZ ⊢,
apply mt (hs.elim_finite_subfamily_closed Z hZc), push_neg, exact hsZ
end
/-- Cantor's intersection theorem:
the intersection of a directed family of nonempty compact closed sets is nonempty. -/
lemma is_compact.nonempty_Inter_of_directed_nonempty_compact_closed
{ι : Type v} [hι : nonempty ι] (Z : ι → set α) (hZd : directed (⊇) Z)
(hZn : ∀ i, (Z i).nonempty) (hZc : ∀ i, is_compact (Z i)) (hZcl : ∀ i, is_closed (Z i)) :
(⋂ i, Z i).nonempty :=
begin
apply hι.elim,
intro i₀,
let Z' := λ i, Z i ∩ Z i₀,
suffices : (⋂ i, Z' i).nonempty,
{ exact nonempty.mono (Inter_subset_Inter $ assume i, inter_subset_left (Z i) (Z i₀)) this },
rw ← ne_empty_iff_nonempty,
intro H,
obtain ⟨t, ht⟩ : ∃ (t : finset ι), ((Z i₀) ∩ ⋂ (i ∈ t), Z' i) = ∅,
from (hZc i₀).elim_finite_subfamily_closed Z'
(assume i, is_closed_inter (hZcl i) (hZcl i₀)) (by rw [H, inter_empty]),
obtain ⟨i₁, hi₁⟩ : ∃ i₁ : ι, Z i₁ ⊆ Z i₀ ∧ ∀ i ∈ t, Z i₁ ⊆ Z' i,
{ rcases directed.finset_le hZd t with ⟨i, hi⟩,
rcases hZd i i₀ with ⟨i₁, hi₁, hi₁₀⟩,
use [i₁, hi₁₀],
intros j hj,
exact subset_inter (subset.trans hi₁ (hi j hj)) hi₁₀ },
suffices : ((Z i₀) ∩ ⋂ (i ∈ t), Z' i).nonempty,
{ rw ← ne_empty_iff_nonempty at this, contradiction },
refine nonempty.mono _ (hZn i₁),
exact subset_inter hi₁.left (subset_bInter hi₁.right)
end
/-- Cantor's intersection theorem for sequences indexed by `ℕ`:
the intersection of a decreasing sequence of nonempty compact closed sets is nonempty. -/
lemma is_compact.nonempty_Inter_of_sequence_nonempty_compact_closed
(Z : ℕ → set α) (hZd : ∀ i, Z (i+1) ⊆ Z i)
(hZn : ∀ i, (Z i).nonempty) (hZ0 : is_compact (Z 0)) (hZcl : ∀ i, is_closed (Z i)) :
(⋂ i, Z i).nonempty :=
have Zmono : _, from @monotone_of_monotone_nat (order_dual _) _ Z hZd,
have hZd : directed (⊇) Z, from directed_of_sup Zmono,
have ∀ i, Z i ⊆ Z 0, from assume i, Zmono $ zero_le i,
have hZc : ∀ i, is_compact (Z i), from assume i, compact_of_is_closed_subset hZ0 (hZcl i) (this i),
is_compact.nonempty_Inter_of_directed_nonempty_compact_closed Z hZd hZn hZc hZcl
/-- For every open cover of a compact set, there exists a finite subcover. -/
lemma is_compact.elim_finite_subcover_image {b : set β} {c : β → set α}
(hs : is_compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) :
∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i :=
begin
rcases hs.elim_finite_subcover (λ i, c i.1 : b → set α) _ _ with ⟨d, hd⟩,
refine ⟨↑(d.image subtype.val), _, finset.finite_to_set _, _⟩,
{ intros i hi,
erw finset.mem_image at hi,
rcases hi with ⟨s, hsd, rfl⟩,
exact s.property },
{ refine subset.trans hd _,
rintros x ⟨_, ⟨s, rfl⟩, ⟨_, ⟨hsd, rfl⟩, H⟩⟩,
refine ⟨c s.val, ⟨s.val, _⟩, H⟩,
simp [finset.mem_image_of_mem subtype.val hsd] },
{ rintro ⟨i, hi⟩, exact hc₁ i hi },
{ refine subset.trans hc₂ _,
rintros x ⟨_, ⟨i, rfl⟩, ⟨_, ⟨hib, rfl⟩, H⟩⟩,
exact ⟨_, ⟨⟨i, hib⟩, rfl⟩, H⟩ },
end
/-- A set `s` is compact if for every family of closed sets whose intersection avoids `s`,
there exists a finite subfamily whose intersection avoids `s`. -/
theorem compact_of_finite_subfamily_closed
(h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) :
is_compact s :=
assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, cluster_pt x f),
have hf : ∀x∈s, 𝓝 x ⊓ f = ⊥,
by simpa only [cluster_pt, not_exists, not_not, ne_bot],
have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t,
from assume ⟨x, hxs, hx⟩,
have ∅ ∈ 𝓝 x ⊓ f, by rw [empty_in_sets_eq_bot, hf x hxs],
let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in
have ∅ ∈ 𝓝[t₂] x,
from (𝓝[t₂] x).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht,
have 𝓝[t₂] x = ⊥,
by rwa [empty_in_sets_eq_bot] at this,
by simp only [closure_eq_cluster_pts] at hx; exact hx t₂ ht₂ this,
let ⟨t, ht⟩ := h (λ i : f.sets, closure i.1) (λ i, is_closed_closure)
(by simpa [eq_empty_iff_forall_not_mem, not_exists]) in
have (⋂i∈t, subtype.val i) ∈ f,
from t.Inter_mem_sets.2 $ assume i hi, i.2,
have s ∩ (⋂i∈t, subtype.val i) ∈ f,
from inter_mem_sets (le_principal_iff.1 hfs) this,
have ∅ ∈ f,
from mem_sets_of_superset this $ assume x ⟨hxs, hx⟩,
let ⟨i, hit, hxi⟩ := (show ∃i ∈ t, x ∉ closure (subtype.val i),
by { rw [eq_empty_iff_forall_not_mem] at ht, simpa [hxs, not_forall] using ht x }) in
have x ∈ closure i.val, from subset_closure (mem_bInter_iff.mp hx i hit),
show false, from hxi this,
hfn $ by rwa [empty_in_sets_eq_bot] at this
/-- A set `s` is compact if for every open cover of `s`, there exists a finite subcover. -/
lemma compact_of_finite_subcover
(h : Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) →
s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) :
is_compact s :=
compact_of_finite_subfamily_closed $
assume ι Z hZc hsZ,
let ⟨t, ht⟩ := h (λ i, (Z i)ᶜ) (assume i, is_open_compl_iff.mpr $ hZc i)
(by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union,
exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using hsZ)
in
⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union,
exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using ht⟩
/-- A set `s` is compact if and only if
for every open cover of `s`, there exists a finite subcover. -/
lemma compact_iff_finite_subcover :
is_compact s ↔ (Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) →
s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) :=
⟨assume hs ι, hs.elim_finite_subcover, compact_of_finite_subcover⟩
/-- A set `s` is compact if and only if
for every family of closed sets whose intersection avoids `s`,
there exists a finite subfamily whose intersection avoids `s`. -/
theorem compact_iff_finite_subfamily_closed :
is_compact s ↔ (Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) :=
⟨assume hs ι, hs.elim_finite_subfamily_closed, compact_of_finite_subfamily_closed⟩
@[simp]
lemma compact_empty : is_compact (∅ : set α) :=
assume f hnf hsf, not.elim hnf $
empty_in_sets_eq_bot.1 $ le_principal_iff.1 hsf
@[simp]
lemma compact_singleton {a : α} : is_compact ({a} : set α) :=
λ f hf hfa, ⟨a, rfl, cluster_pt.of_le_nhds'
(hfa.trans $ by simpa only [principal_singleton] using pure_le_nhds a) hf⟩
lemma set.finite.compact_bUnion {s : set β} {f : β → set α} (hs : finite s)
(hf : ∀i ∈ s, is_compact (f i)) :
is_compact (⋃i ∈ s, f i) :=
compact_of_finite_subcover $ assume ι U hUo hsU,
have ∀i : subtype s, ∃t : finset ι, f i ⊆ (⋃ j ∈ t, U j), from
assume ⟨i, hi⟩, (hf i hi).elim_finite_subcover _ hUo
(calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi
... ⊆ ⋃j, U j : hsU),
let ⟨finite_subcovers, h⟩ := axiom_of_choice this in
by haveI : fintype (subtype s) := hs.fintype; exact
let t := finset.bind finset.univ finite_subcovers in
have (⋃i ∈ s, f i) ⊆ (⋃ i ∈ t, U i), from bUnion_subset $
assume i hi, calc
f i ⊆ (⋃ j ∈ finite_subcovers ⟨i, hi⟩, U j) : (h ⟨i, hi⟩)
... ⊆ (⋃ j ∈ t, U j) : bUnion_subset_bUnion_left $
assume j hj, finset.mem_bind.mpr ⟨_, finset.mem_univ _, hj⟩,
⟨t, this⟩
lemma compact_Union {f : β → set α} [fintype β]
(h : ∀i, is_compact (f i)) : is_compact (⋃i, f i) :=
by rw ← bUnion_univ; exact finite_univ.compact_bUnion (λ i _, h i)
lemma set.finite.is_compact (hs : finite s) : is_compact s :=
bUnion_of_singleton s ▸ hs.compact_bUnion (λ _ _, compact_singleton)
lemma is_compact.union (hs : is_compact s) (ht : is_compact t) : is_compact (s ∪ t) :=
by rw union_eq_Union; exact compact_Union (λ b, by cases b; assumption)
lemma is_compact.insert (hs : is_compact s) (a) : is_compact (insert a s) :=
compact_singleton.union hs
/-- `filter.cocompact` is the filter generated by complements to compact sets. -/
def filter.cocompact (α : Type*) [topological_space α] : filter α :=
⨅ (s : set α) (hs : is_compact s), 𝓟 (sᶜ)
lemma filter.has_basis_cocompact : (filter.cocompact α).has_basis is_compact compl :=
has_basis_binfi_principal'
(λ s hs t ht, ⟨s ∪ t, hs.union ht, compl_subset_compl.2 (subset_union_left s t),
compl_subset_compl.2 (subset_union_right s t)⟩)
⟨∅, compact_empty⟩
lemma filter.mem_cocompact : s ∈ filter.cocompact α ↔ ∃ t, is_compact t ∧ tᶜ ⊆ s :=
filter.has_basis_cocompact.mem_iff.trans $ exists_congr $ λ t, exists_prop
lemma filter.mem_cocompact' : s ∈ filter.cocompact α ↔ ∃ t, is_compact t ∧ sᶜ ⊆ t :=
filter.mem_cocompact.trans $ exists_congr $ λ t, and_congr_right $ λ ht, compl_subset_comm
lemma is_compact.compl_mem_cocompact (hs : is_compact s) : sᶜ ∈ filter.cocompact α :=
filter.has_basis_cocompact.mem_of_mem hs
section tube_lemma
variables [topological_space β]
/-- `nhds_contain_boxes s t` means that any open neighborhood of `s × t` in `α × β` includes
a product of an open neighborhood of `s` by an open neighborhood of `t`. -/
def nhds_contain_boxes (s : set α) (t : set β) : Prop :=
∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n),
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n
lemma nhds_contain_boxes.symm {s : set α} {t : set β} :
nhds_contain_boxes s t → nhds_contain_boxes t s :=
assume H n hn hp,
let ⟨u, v, uo, vo, su, tv, p⟩ :=
H (prod.swap ⁻¹' n)
(hn.preimage continuous_swap)
(by rwa [←image_subset_iff, image_swap_prod]) in
⟨v, u, vo, uo, tv, su,
by rwa [←image_subset_iff, image_swap_prod] at p⟩
lemma nhds_contain_boxes.comm {s : set α} {t : set β} :
nhds_contain_boxes s t ↔ nhds_contain_boxes t s :=
iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm
lemma nhds_contain_boxes_of_singleton {x : α} {y : β} :
nhds_contain_boxes ({x} : set α) ({y} : set β) :=
assume n hn hp,
let ⟨u, v, uo, vo, xu, yv, hp'⟩ :=
is_open_prod_iff.mp hn x y (hp $ by simp) in
⟨u, v, uo, vo, by simpa, by simpa, hp'⟩
lemma nhds_contain_boxes_of_compact {s : set α} (hs : is_compact s) (t : set β)
(H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t :=
assume n hn hp,
have ∀x : subtype s, ∃uv : set α × set β,
is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n,
from assume ⟨x, hx⟩,
have set.prod {x} t ⊆ n, from
subset.trans (prod_mono (by simpa) (subset.refl _)) hp,
let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩,
let ⟨uvs, h⟩ := classical.axiom_of_choice this in
have us_cover : s ⊆ ⋃i, (uvs i).1, from
assume x hx, subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1),
let ⟨s0, s0_cover⟩ :=
hs.elim_finite_subcover _ (λi, (h i).1) us_cover in
let u := ⋃(i ∈ s0), (uvs i).1 in
let v := ⋂(i ∈ s0), (uvs i).2 in
have is_open u, from is_open_bUnion (λi _, (h i).1),
have is_open v, from is_open_bInter s0.finite_to_set (λi _, (h i).2.1),
have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1),
have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩,
have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx',
let ⟨i,is0,hi⟩ := this in
(h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩,
⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩
/-- If `s` and `t` are compact sets and `n` is an open neighborhood of `s × t`, then there exist
open neighborhoods `u ⊇ s` and `v ⊇ t` such that `u × v ⊆ n`. -/
lemma generalized_tube_lemma {s : set α} (hs : is_compact s) {t : set β} (ht : is_compact t)
{n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) :
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n :=
have _, from
nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $
nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton,
this n hn hp
end tube_lemma
/-- Type class for compact spaces. Separation is sometimes included in the definition, especially
in the French literature, but we do not include it here. -/
class compact_space (α : Type*) [topological_space α] : Prop :=
(compact_univ : is_compact (univ : set α))
lemma compact_univ [h : compact_space α] : is_compact (univ : set α) := h.compact_univ
lemma cluster_point_of_compact [compact_space α] (f : filter α) [ne_bot f] :
∃ x, cluster_pt x f :=
by simpa using compact_univ (show f ≤ 𝓟 univ, by simp)
theorem compact_space_of_finite_subfamily_closed {α : Type u} [topological_space α]
(h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
(⋂ i, Z i) = ∅ → (∃ (t : finset ι), (⋂ i ∈ t, Z i) = ∅)) :
compact_space α :=
{ compact_univ :=
begin
apply compact_of_finite_subfamily_closed,
intros ι Z, specialize h Z,
simpa using h
end }
lemma is_closed.compact [compact_space α] {s : set α} (h : is_closed s) :
is_compact s :=
compact_of_is_closed_subset compact_univ h (subset_univ _)
variables [topological_space β]
lemma is_compact.image_of_continuous_on {f : α → β} (hs : is_compact s) (hf : continuous_on f s) :
is_compact (f '' s) :=
begin
intros l lne ls,
have : ne_bot (l.comap f ⊓ 𝓟 s) :=
comap_inf_principal_ne_bot_of_image_mem lne (le_principal_iff.1 ls),
obtain ⟨a, has, ha⟩ : ∃ a ∈ s, cluster_pt a (l.comap f ⊓ 𝓟 s) := @@hs this inf_le_right,
use [f a, mem_image_of_mem f has],
have : tendsto f (𝓝 a ⊓ (comap f l ⊓ 𝓟 s)) (𝓝 (f a) ⊓ l),
{ convert (hf a has).inf (@tendsto_comap _ _ f l) using 1,
rw nhds_within,
ac_refl },
exact @@tendsto.ne_bot _ this ha,
end
lemma is_compact.image {f : α → β} (hs : is_compact s) (hf : continuous f) :
is_compact (f '' s) :=
hs.image_of_continuous_on hf.continuous_on
lemma compact_range [compact_space α] {f : α → β} (hf : continuous f) :
is_compact (range f) :=
by rw ← image_univ; exact compact_univ.image hf
/-- If X is is_compact then pr₂ : X × Y → Y is a closed map -/
theorem is_closed_proj_of_compact
{X : Type*} [topological_space X] [compact_space X]
{Y : Type*} [topological_space Y] :
is_closed_map (prod.snd : X × Y → Y) :=
begin
set πX := (prod.fst : X × Y → X),
set πY := (prod.snd : X × Y → Y),
assume C (hC : is_closed C),
rw is_closed_iff_cluster_pt at hC ⊢,
assume y (y_closure : cluster_pt y $ 𝓟 (πY '' C)),
have : ne_bot (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)),
{ suffices : ne_bot (map πY (comap πY (𝓝 y) ⊓ 𝓟 C)),
by simpa only [map_ne_bot_iff],
calc map πY (comap πY (𝓝 y) ⊓ 𝓟 C) =
𝓝 y ⊓ map πY (𝓟 C) : filter.push_pull' _ _ _
... = 𝓝 y ⊓ 𝓟 (πY '' C) : by rw map_principal
... ≠ ⊥ : y_closure },
resetI,
obtain ⟨x, hx⟩ : ∃ x, cluster_pt x (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)),
from cluster_point_of_compact _,
refine ⟨⟨x, y⟩, _, by simp [πY]⟩,
apply hC,
rw [cluster_pt, ← filter.map_ne_bot_iff πX],
calc map πX (𝓝 (x, y) ⊓ 𝓟 C)
= map πX (comap πX (𝓝 x) ⊓ comap πY (𝓝 y) ⊓ 𝓟 C) : by rw [nhds_prod_eq, filter.prod]
... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C ⊓ comap πX (𝓝 x)) : by ac_refl
... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x : by rw filter.push_pull
... = 𝓝 x ⊓ map πX (comap πY (𝓝 y) ⊓ 𝓟 C) : by rw inf_comm
... ≠ ⊥ : hx,
end
lemma embedding.compact_iff_compact_image {f : α → β} (hf : embedding f) :
is_compact s ↔ is_compact (f '' s) :=
iff.intro (assume h, h.image hf.continuous) $ assume h, begin
rw compact_iff_ultrafilter_le_nhds at ⊢ h,
intros u us',
have : ↑(u.map f) ≤ 𝓟 (f '' s), begin
rw [ultrafilter.coe_map, map_le_iff_le_comap, comap_principal], convert us',
exact preimage_image_eq _ hf.inj
end,
rcases h (u.map f) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩,
refine ⟨a, ha, _⟩,
rwa [hf.induced, nhds_induced, ←map_le_iff_le_comap]
end
lemma compact_iff_compact_in_subtype {p : α → Prop} {s : set {a // p a}} :
is_compact s ↔ is_compact ((coe : _ → α) '' s) :=
embedding_subtype_coe.compact_iff_compact_image
lemma compact_iff_compact_univ {s : set α} : is_compact s ↔ is_compact (univ : set s) :=
by rw [compact_iff_compact_in_subtype, image_univ, subtype.range_coe]; refl
lemma compact_iff_compact_space {s : set α} : is_compact s ↔ compact_space s :=
compact_iff_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩
lemma is_compact.prod {s : set α} {t : set β} (hs : is_compact s) (ht : is_compact t) :
is_compact (set.prod s t) :=
begin
rw compact_iff_ultrafilter_le_nhds at hs ht ⊢,
intros f hfs,
rw le_principal_iff at hfs,
obtain ⟨a : α, sa : a ∈ s, ha : map prod.fst ↑f ≤ 𝓝 a⟩ :=
hs (f.map prod.fst) (le_principal_iff.2 $ mem_map.2 $ mem_sets_of_superset hfs (λ x, and.left)),
obtain ⟨b : β, tb : b ∈ t, hb : map prod.snd ↑f ≤ 𝓝 b⟩ :=
ht (f.map prod.snd) (le_principal_iff.2 $ mem_map.2 $
mem_sets_of_superset hfs (λ x, and.right)),
rw map_le_iff_le_comap at ha hb,
refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩,
rw nhds_prod_eq, exact le_inf ha hb
end
/-- Finite topological spaces are compact. -/
@[priority 100] instance fintype.compact_space [fintype α] : compact_space α :=
{ compact_univ := finite_univ.is_compact }
/-- The product of two compact spaces is compact. -/
instance [compact_space α] [compact_space β] : compact_space (α × β) :=
⟨by { rw ← univ_prod_univ, exact compact_univ.prod compact_univ }⟩
/-- The disjoint union of two compact spaces is compact. -/
instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) :=
⟨begin
rw ← range_inl_union_range_inr,
exact (compact_range continuous_inl).union (compact_range continuous_inr)
end⟩
section tychonoff
variables {ι : Type*} {π : ι → Type*} [∀i, topological_space (π i)]
/-- Tychonoff's theorem -/
lemma compact_pi_infinite {s : Πi:ι, set (π i)} :
(∀i, is_compact (s i)) → is_compact {x : Πi:ι, π i | ∀i, x i ∈ s i} :=
begin
simp only [compact_iff_ultrafilter_le_nhds, nhds_pi, exists_prop, mem_set_of_eq, le_infi_iff,
le_principal_iff],
intros h f hfs,
have : ∀i:ι, ∃a, a∈s i ∧ tendsto (λx:Πi:ι, π i, x i) f (𝓝 a),
{ refine λ i, h i (f.map _) (mem_map.2 _),
exact mem_sets_of_superset hfs (λ x hx, hx i) },
choose a ha,
exact ⟨a, assume i, (ha i).left, assume i, (ha i).right.le_comap⟩
end
/-- A version of Tychonoff's theorem that uses `set.pi`. -/
lemma compact_univ_pi {s : Πi:ι, set (π i)} (h : ∀i, is_compact (s i)) :
is_compact (pi univ s) :=
by { convert compact_pi_infinite h, simp only [pi, forall_prop_of_true, mem_univ] }
instance pi.compact [∀i:ι, compact_space (π i)] : compact_space (Πi, π i) :=
⟨begin
have A : is_compact {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} :=
compact_pi_infinite (λi, compact_univ),
have : {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} = univ := by ext; simp,
rwa this at A,
end⟩
end tychonoff
instance quot.compact_space {r : α → α → Prop} [compact_space α] :
compact_space (quot r) :=
⟨by { rw ← range_quot_mk, exact compact_range continuous_quot_mk }⟩
instance quotient.compact_space {s : setoid α} [compact_space α] :
compact_space (quotient s) :=
quot.compact_space
/-- There are various definitions of "locally compact space" in the literature, which agree for
Hausdorff spaces but not in general. This one is the precise condition on X needed for the
evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the
compact-open topology. -/
class locally_compact_space (α : Type*) [topological_space α] : Prop :=
(local_compact_nhds : ∀ (x : α) (n ∈ 𝓝 x), ∃ s ∈ 𝓝 x, s ⊆ n ∧ is_compact s)
/-- A reformulation of the definition of locally compact space: In a locally compact space,
every open set containing `x` has a compact subset containing `x` in its interior. -/
lemma exists_compact_subset [locally_compact_space α] {x : α} {U : set α}
(hU : is_open U) (hx : x ∈ U) : ∃ (K : set α), is_compact K ∧ x ∈ interior K ∧ K ⊆ U :=
begin
rcases locally_compact_space.local_compact_nhds x U _ with ⟨K, h1K, h2K, h3K⟩,
{ refine ⟨K, h3K, _, h2K⟩, rwa [ mem_interior_iff_mem_nhds] },
rwa [← mem_interior_iff_mem_nhds, hU.interior_eq]
end
lemma ultrafilter.le_nhds_Lim [compact_space α] (F : ultrafilter α) :
↑F ≤ 𝓝 (@Lim _ _ (F : filter α).nonempty_of_ne_bot F) :=
begin
rcases compact_univ.ultrafilter_le_nhds F (by simp) with ⟨x, -, h⟩,
exact le_nhds_Lim ⟨x,h⟩,
end
end compact
section clopen
/-- A set is clopen if it is both open and closed. -/
def is_clopen (s : set α) : Prop :=
is_open s ∧ is_closed s
theorem is_clopen_union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) :=
⟨is_open_union hs.1 ht.1, is_closed_union hs.2 ht.2⟩
theorem is_clopen_inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) :=
⟨is_open_inter hs.1 ht.1, is_closed_inter hs.2 ht.2⟩
@[simp] theorem is_clopen_empty : is_clopen (∅ : set α) :=
⟨is_open_empty, is_closed_empty⟩
@[simp] theorem is_clopen_univ : is_clopen (univ : set α) :=
⟨is_open_univ, is_closed_univ⟩
theorem is_clopen_compl {s : set α} (hs : is_clopen s) : is_clopen sᶜ :=
⟨hs.2, is_closed_compl_iff.2 hs.1⟩
@[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen sᶜ ↔ is_clopen s :=
⟨λ h, compl_compl s ▸ is_clopen_compl h, is_clopen_compl⟩
theorem is_clopen_diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s \ t) :=
is_clopen_inter hs (is_clopen_compl ht)
lemma is_clopen_Inter {β : Type*} [fintype β] {s : β → set α}
(h : ∀ i, is_clopen (s i)) : is_clopen (⋂ i, s i) :=
⟨(is_open_Inter (forall_and_distrib.1 h).1), (is_closed_Inter (forall_and_distrib.1 h).2)⟩
lemma is_clopen_bInter {β : Type*} {s : finset β} {f : β → set α} (h : ∀i∈s, is_clopen (f i)) :
is_clopen (⋂i∈s, f i) :=
⟨ is_open_bInter ⟨finset_coe.fintype s⟩ (λ i hi, (h i hi).1),
by {show is_closed (⋂ (i : β) (H : i ∈ (↑s : set β)), f i), rw bInter_eq_Inter,
apply is_closed_Inter, rintro ⟨i, hi⟩, exact (h i hi).2}⟩
lemma continuous_on.preimage_clopen_of_clopen {β: Type*} [topological_space β]
{f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_clopen s)
(ht : is_clopen t) : is_clopen (s ∩ f⁻¹' t) :=
⟨continuous_on.preimage_open_of_open hf hs.1 ht.1, continuous_on.preimage_closed_of_closed hf hs.2 ht.2⟩
/-- The intersection of a disjoint covering by two open sets of a clopen set will be clopen. -/
theorem is_clopen_inter_of_disjoint_cover_clopen {Z a b : set α} (h : is_clopen Z)
(cover : Z ⊆ a ∪ b) (ha : is_open a) (hb : is_open b) (hab : a ∩ b = ∅) : is_clopen (Z ∩ a) :=
begin
refine ⟨is_open_inter h.1 ha, _⟩,
have : is_closed (Z ∩ bᶜ) := is_closed_inter h.2 (is_closed_compl_iff.2 hb),
convert this using 1,
apply subset.antisymm,
{ exact inter_subset_inter_right Z (subset_compl_iff_disjoint.2 hab) },
{ rintros x ⟨hx₁, hx₂⟩,
exact ⟨hx₁, by simpa [not_mem_of_mem_compl hx₂] using cover hx₁⟩ }
end
end clopen
section preirreducible
/-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/
def is_preirreducible (s : set α) : Prop :=
∀ (u v : set α), is_open u → is_open v →
(s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty
/-- An irreducible set `s` is one that is nonempty and
where there is no non-trivial pair of disjoint opens on `s`. -/
def is_irreducible (s : set α) : Prop :=
s.nonempty ∧ is_preirreducible s
lemma is_irreducible.nonempty {s : set α} (h : is_irreducible s) :
s.nonempty := h.1
lemma is_irreducible.is_preirreducible {s : set α} (h : is_irreducible s) :
is_preirreducible s := h.2
theorem is_preirreducible_empty : is_preirreducible (∅ : set α) :=
λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim
theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) :=
⟨singleton_nonempty x,
λ u v _ _ ⟨y, h1, h2⟩ ⟨z, h3, h4⟩, by rw mem_singleton_iff at h1 h3;
substs y z; exact ⟨x, rfl, h2, h4⟩⟩
theorem is_preirreducible.closure {s : set α} (H : is_preirreducible s) :
is_preirreducible (closure s) :=
λ u v hu hv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩,
let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in
let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in
let ⟨r, hrs, hruv⟩ := H u v hu hv ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in
⟨r, subset_closure hrs, hruv⟩
lemma is_irreducible.closure {s : set α} (h : is_irreducible s) :
is_irreducible (closure s) :=
⟨h.nonempty.closure, h.is_preirreducible.closure⟩
theorem exists_preirreducible (s : set α) (H : is_preirreducible s) :
∃ t : set α, is_preirreducible t ∧ s ⊆ t ∧ ∀ u, is_preirreducible u → t ⊆ u → u = t :=
let ⟨m, hm, hsm, hmm⟩ := zorn.zorn_subset₀ {t : set α | is_preirreducible t}
(λ c hc hcc hcn, let ⟨t, htc⟩ := hcn in
⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩,
let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy,
⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in
or.cases_on (zorn.chain.total hcc hpc hqc)
(assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv
⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in
⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩)
(assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv
⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in
⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩),
λ x hxc, subset_sUnion_of_mem hxc⟩) s H in
⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩
/-- A maximal irreducible set that contains a given point. -/
def irreducible_component (x : α) : set α :=
classical.some (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible)
lemma irreducible_component_property (x : α) :
is_preirreducible (irreducible_component x) ∧ {x} ⊆ (irreducible_component x) ∧
∀ u, is_preirreducible u → (irreducible_component x) ⊆ u → u = (irreducible_component x) :=
classical.some_spec (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible)
theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x :=
singleton_subset_iff.1 (irreducible_component_property x).2.1
theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) :=
⟨⟨x, mem_irreducible_component⟩, (irreducible_component_property x).1⟩
theorem eq_irreducible_component {x : α} :
∀ {s : set α}, is_preirreducible s → irreducible_component x ⊆ s → s = irreducible_component x :=
(irreducible_component_property x).2.2
theorem is_closed_irreducible_component {x : α} :
is_closed (irreducible_component x) :=
closure_eq_iff_is_closed.1 $ eq_irreducible_component
is_irreducible_irreducible_component.is_preirreducible.closure
subset_closure
/-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/
class preirreducible_space (α : Type u) [topological_space α] : Prop :=
(is_preirreducible_univ [] : is_preirreducible (univ : set α))
/-- An irreducible space is one that is nonempty
and where there is no non-trivial pair of disjoint opens. -/
class irreducible_space (α : Type u) [topological_space α] extends preirreducible_space α : Prop :=
(to_nonempty [] : nonempty α)
attribute [instance, priority 50] irreducible_space.to_nonempty -- see Note [lower instance priority]
theorem nonempty_preirreducible_inter [preirreducible_space α] {s t : set α} :
is_open s → is_open t → s.nonempty → t.nonempty → (s ∩ t).nonempty :=
by simpa only [univ_inter, univ_subset_iff] using
@preirreducible_space.is_preirreducible_univ α _ _ s t
theorem is_preirreducible.image [topological_space β] {s : set α} (H : is_preirreducible s)
(f : α → β) (hf : continuous_on f s) : is_preirreducible (f '' s) :=
begin
rintros u v hu hv ⟨_, ⟨⟨x, hx, rfl⟩, hxu⟩⟩ ⟨_, ⟨⟨y, hy, rfl⟩, hyv⟩⟩,
rw ← mem_preimage at hxu hyv,
rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩,
rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩,
have := H u' v' hu' hv',
rw [inter_comm s u', ← u'_eq] at this,
rw [inter_comm s v', ← v'_eq] at this,
rcases this ⟨x, hxu, hx⟩ ⟨y, hyv, hy⟩ with ⟨z, hzs, hzu', hzv'⟩,
refine ⟨f z, mem_image_of_mem f hzs, _, _⟩,
all_goals
{ rw ← mem_preimage,
apply mem_of_mem_inter_left,
show z ∈ _ ∩ s,
simp [*] }
end
theorem is_irreducible.image [topological_space β] {s : set α} (H : is_irreducible s)
(f : α → β) (hf : continuous_on f s) : is_irreducible (f '' s) :=
⟨nonempty_image_iff.mpr H.nonempty, H.is_preirreducible.image f hf⟩
lemma subtype.preirreducible_space {s : set α} (h : is_preirreducible s) :
preirreducible_space s :=
{ is_preirreducible_univ :=
begin
intros u v hu hv hsu hsv,
rw is_open_induced_iff at hu hv,
rcases hu with ⟨u, hu, rfl⟩,
rcases hv with ⟨v, hv, rfl⟩,
rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩,
rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩,
rcases h u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩,
exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩
end }
lemma subtype.irreducible_space {s : set α} (h : is_irreducible s) :
irreducible_space s :=
{ is_preirreducible_univ :=
(subtype.preirreducible_space h.is_preirreducible).is_preirreducible_univ,
to_nonempty := h.nonempty.to_subtype }
/-- A set `s` is irreducible if and only if
for every finite collection of open sets all of whose members intersect `s`,
`s` also intersects the intersection of the entire collection
(i.e., there is an element of `s` contained in every member of the collection). -/
lemma is_irreducible_iff_sInter {s : set α} :
is_irreducible s ↔
∀ (U : finset (set α)) (hU : ∀ u ∈ U, is_open u) (H : ∀ u ∈ U, (s ∩ u).nonempty),
(s ∩ ⋂₀ ↑U).nonempty :=
begin
split; intro h,
{ intro U, apply finset.induction_on U,
{ intros, simpa using h.nonempty },
{ intros u U hu IH hU H,
rw [finset.coe_insert, sInter_insert],
apply h.2,
{ solve_by_elim [finset.mem_insert_self] },
{ apply is_open_sInter (finset.finite_to_set U),
intros, solve_by_elim [finset.mem_insert_of_mem] },
{ solve_by_elim [finset.mem_insert_self] },
{ apply IH,
all_goals { intros, solve_by_elim [finset.mem_insert_of_mem] } } } },
{ split,
{ simpa using h ∅ _ _; intro u; simp },
intros u v hu hv hu' hv',
simpa using h {u,v} _ _,
all_goals
{ intro t,
rw [finset.mem_insert, finset.mem_singleton],
rintro (rfl|rfl); assumption } }
end
/-- A set is preirreducible if and only if
for every cover by two closed sets, it is contained in one of the two covering sets. -/
lemma is_preirreducible_iff_closed_union_closed {s : set α} :
is_preirreducible s ↔
∀ (z₁ z₂ : set α), is_closed z₁ → is_closed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ :=
begin
split,
all_goals
{ intros h t₁ t₂ ht₁ ht₂,
specialize h t₁ᶜ t₂ᶜ,
simp only [is_open_compl_iff, is_closed_compl_iff] at h,
specialize h ht₁ ht₂ },
{ contrapose!, simp only [not_subset],
rintro ⟨⟨x, hx, hx'⟩, ⟨y, hy, hy'⟩⟩,
rcases h ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ with ⟨z, hz, hz'⟩,
rw ← compl_union at hz',
exact ⟨z, hz, hz'⟩ },
{ rintro ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩,
rw ← compl_inter at h,
delta set.nonempty,
rw imp_iff_not_or at h,
contrapose! h,
split,
{ intros z hz hz', exact h z ⟨hz, hz'⟩ },
{ split; intro H; refine H _ ‹_›; assumption } }
end
/-- A set is irreducible if and only if
for every cover by a finite collection of closed sets,
it is contained in one of the members of the collection. -/
lemma is_irreducible_iff_sUnion_closed {s : set α} :
is_irreducible s ↔
∀ (Z : finset (set α)) (hZ : ∀ z ∈ Z, is_closed z) (H : s ⊆ ⋃₀ ↑Z),
∃ z ∈ Z, s ⊆ z :=
begin
rw [is_irreducible, is_preirreducible_iff_closed_union_closed],
split; intro h,
{ intro Z, apply finset.induction_on Z,
{ intros, rw [finset.coe_empty, sUnion_empty] at H,
rcases h.1 with ⟨x, hx⟩,
exfalso, tauto },
{ intros z Z hz IH hZ H,
cases h.2 z (⋃₀ ↑Z) _ _ _
with h' h',
{ exact ⟨z, finset.mem_insert_self _ _, h'⟩ },
{ rcases IH _ h' with ⟨z', hz', hsz'⟩,
{ exact ⟨z', finset.mem_insert_of_mem hz', hsz'⟩ },
{ intros, solve_by_elim [finset.mem_insert_of_mem] } },
{ solve_by_elim [finset.mem_insert_self] },
{ rw sUnion_eq_bUnion,
apply is_closed_bUnion (finset.finite_to_set Z),
{ intros, solve_by_elim [finset.mem_insert_of_mem] } },
{ simpa using H } } },
{ split,
{ by_contradiction hs,
simpa using h ∅ _ _,
{ intro z, simp },
{ simpa [set.nonempty] using hs } },
intros z₁ z₂ hz₁ hz₂ H,
have := h {z₁, z₂} _ _,
simp only [exists_prop, finset.mem_insert, finset.mem_singleton] at this,
{ rcases this with ⟨z, rfl|rfl, hz⟩; tauto },
{ intro t,
rw [finset.mem_insert, finset.mem_singleton],
rintro (rfl|rfl); assumption },
{ simpa using H } }
end
end preirreducible
section preconnected
/-- A preconnected set is one where there is no non-trivial open partition. -/
def is_preconnected (s : set α) : Prop :=
∀ (u v : set α), is_open u → is_open v → s ⊆ u ∪ v →
(s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty
/-- A connected set is one that is nonempty and where there is no non-trivial open partition. -/
def is_connected (s : set α) : Prop :=
s.nonempty ∧ is_preconnected s
lemma is_connected.nonempty {s : set α} (h : is_connected s) :
s.nonempty := h.1
lemma is_connected.is_preconnected {s : set α} (h : is_connected s) :
is_preconnected s := h.2
theorem is_preirreducible.is_preconnected {s : set α} (H : is_preirreducible s) :
is_preconnected s :=
λ _ _ hu hv _, H _ _ hu hv
theorem is_irreducible.is_connected {s : set α} (H : is_irreducible s) : is_connected s :=
⟨H.nonempty, H.is_preirreducible.is_preconnected⟩
theorem is_preconnected_empty : is_preconnected (∅ : set α) :=
is_preirreducible_empty.is_preconnected
theorem is_connected_singleton {x} : is_connected ({x} : set α) :=
is_irreducible_singleton.is_connected
/-- If any point of a set is joined to a fixed point by a preconnected subset,
then the original set is preconnected as well. -/
theorem is_preconnected_of_forall {s : set α} (x : α)
(H : ∀ y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) :
is_preconnected s :=
begin
rintros u v hu hv hs ⟨z, zs, zu⟩ ⟨y, ys, yv⟩,
have xs : x ∈ s, by { rcases H y ys with ⟨t, ts, xt, yt, ht⟩, exact ts xt },
wlog xu : x ∈ u := hs xs using [u v y z, v u z y],
rcases H y ys with ⟨t, ts, xt, yt, ht⟩,
have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩,
exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩)
end
/-- If any two points of a set are contained in a preconnected subset,
then the original set is preconnected as well. -/
theorem is_preconnected_of_forall_pair {s : set α}
(H : ∀ x y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) :
is_preconnected s :=
begin
rintros u v hu hv hs ⟨x, xs, xu⟩ ⟨y, ys, yv⟩,
rcases H x y xs ys with ⟨t, ts, xt, yt, ht⟩,
have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩,
exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩)
end
/-- A union of a family of preconnected sets with a common point is preconnected as well. -/
theorem is_preconnected_sUnion (x : α) (c : set (set α)) (H1 : ∀ s ∈ c, x ∈ s)
(H2 : ∀ s ∈ c, is_preconnected s) : is_preconnected (⋃₀ c) :=
begin
apply is_preconnected_of_forall x,
rintros y ⟨s, sc, ys⟩,
exact ⟨s, subset_sUnion_of_mem sc, H1 s sc, ys, H2 s sc⟩
end
theorem is_preconnected.union (x : α) {s t : set α} (H1 : x ∈ s) (H2 : x ∈ t)
(H3 : is_preconnected s) (H4 : is_preconnected t) : is_preconnected (s ∪ t) :=
sUnion_pair s t ▸ is_preconnected_sUnion x {s, t}
(by rintro r (rfl | rfl | h); assumption)
(by rintro r (rfl | rfl | h); assumption)
theorem is_connected.union {s t : set α} (H : (s ∩ t).nonempty)
(Hs : is_connected s) (Ht : is_connected t) : is_connected (s ∪ t) :=
begin
rcases H with ⟨x, hx⟩,
refine ⟨⟨x, mem_union_left t (mem_of_mem_inter_left hx)⟩, _⟩,
exact is_preconnected.union x (mem_of_mem_inter_left hx) (mem_of_mem_inter_right hx)
Hs.is_preconnected Ht.is_preconnected
end
theorem is_preconnected.closure {s : set α} (H : is_preconnected s) :
is_preconnected (closure s) :=
λ u v hu hv hcsuv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩,
let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in
let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in
let ⟨r, hrs, hruv⟩ := H u v hu hv (subset.trans subset_closure hcsuv) ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in
⟨r, subset_closure hrs, hruv⟩
theorem is_connected.closure {s : set α} (H : is_connected s) :
is_connected (closure s) :=
⟨H.nonempty.closure, H.is_preconnected.closure⟩
theorem is_preconnected.image [topological_space β] {s : set α} (H : is_preconnected s)
(f : α → β) (hf : continuous_on f s) : is_preconnected (f '' s) :=
begin
-- Unfold/destruct definitions in hypotheses
rintros u v hu hv huv ⟨_, ⟨x, xs, rfl⟩, xu⟩ ⟨_, ⟨y, ys, rfl⟩, yv⟩,
rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩,
rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩,
-- Reformulate `huv : f '' s ⊆ u ∪ v` in terms of `u'` and `v'`
replace huv : s ⊆ u' ∪ v',
{ rw [image_subset_iff, preimage_union] at huv,
replace huv := subset_inter huv (subset.refl _),
rw [inter_distrib_right, u'_eq, v'_eq, ← inter_distrib_right] at huv,
exact (subset_inter_iff.1 huv).1 },
-- Now `s ⊆ u' ∪ v'`, so we can apply `‹is_preconnected s›`
obtain ⟨z, hz⟩ : (s ∩ (u' ∩ v')).nonempty,
{ refine H u' v' hu' hv' huv ⟨x, _⟩ ⟨y, _⟩; rw inter_comm,
exacts [u'_eq ▸ ⟨xu, xs⟩, v'_eq ▸ ⟨yv, ys⟩] },
rw [← inter_self s, inter_assoc, inter_left_comm s u', ← inter_assoc,
inter_comm s, inter_comm s, ← u'_eq, ← v'_eq] at hz,
exact ⟨f z, ⟨z, hz.1.2, rfl⟩, hz.1.1, hz.2.1⟩
end
theorem is_connected.image [topological_space β] {s : set α} (H : is_connected s)
(f : α → β) (hf : continuous_on f s) : is_connected (f '' s) :=
⟨nonempty_image_iff.mpr H.nonempty, H.is_preconnected.image f hf⟩
theorem is_preconnected_closed_iff {s : set α} :
is_preconnected s ↔ ∀ t t', is_closed t → is_closed t' → s ⊆ t ∪ t' →
(s ∩ t).nonempty → (s ∩ t').nonempty → (s ∩ (t ∩ t')).nonempty :=
⟨begin
rintros h t t' ht ht' htt' ⟨x, xs, xt⟩ ⟨y, ys, yt'⟩,
by_contradiction h',
rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h',
have xt' : x ∉ t', from (h' xs).elim (absurd xt) id,
have yt : y ∉ t, from (h' ys).elim id (absurd yt'),
have := ne_empty_iff_nonempty.2 (h tᶜ t'ᶜ (is_open_compl_iff.2 ht)
(is_open_compl_iff.2 ht') h' ⟨y, ys, yt⟩ ⟨x, xs, xt'⟩),
rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this,
contradiction
end,
begin
rintros h u v hu hv huv ⟨x, xs, xu⟩ ⟨y, ys, yv⟩,
by_contradiction h',
rw [← ne_empty_iff_nonempty, ne.def, not_not,
← subset_compl_iff_disjoint, compl_inter] at h',
have xv : x ∉ v, from (h' xs).elim (absurd xu) id,
have yu : y ∉ u, from (h' ys).elim id (absurd yv),
have := ne_empty_iff_nonempty.2 (h uᶜ vᶜ (is_closed_compl_iff.2 hu)
(is_closed_compl_iff.2 hv) h' ⟨y, ys, yu⟩ ⟨x, xs, xv⟩),
rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this,
contradiction
end⟩
/-- The connected component of a point is the maximal connected set
that contains this point. -/
def connected_component (x : α) : set α :=
⋃₀ { s : set α | is_preconnected s ∧ x ∈ s }
/-- The connected component of a point inside a set. -/
def connected_component_in (F : set α) (x : F) : set α := coe '' (connected_component x)
theorem mem_connected_component {x : α} : x ∈ connected_component x :=
mem_sUnion_of_mem (mem_singleton x) ⟨is_connected_singleton.is_preconnected, mem_singleton x⟩
theorem is_connected_connected_component {x : α} : is_connected (connected_component x) :=
⟨⟨x, mem_connected_component⟩, is_preconnected_sUnion x _ (λ _, and.right) (λ _, and.left)⟩
theorem subset_connected_component {x : α} {s : set α} (H1 : is_preconnected s) (H2 : x ∈ s) :
s ⊆ connected_component x :=
λ z hz, mem_sUnion_of_mem hz ⟨H1, H2⟩
theorem is_closed_connected_component {x : α} :
is_closed (connected_component x) :=
closure_eq_iff_is_closed.1 $ subset.antisymm
(subset_connected_component
is_connected_connected_component.closure.is_preconnected
(subset_closure mem_connected_component))
subset_closure
theorem irreducible_component_subset_connected_component {x : α} :
irreducible_component x ⊆ connected_component x :=
subset_connected_component
is_irreducible_irreducible_component.is_connected.is_preconnected
mem_irreducible_component
/-- A preconnected space is one where there is no non-trivial open partition. -/
class preconnected_space (α : Type u) [topological_space α] : Prop :=
(is_preconnected_univ : is_preconnected (univ : set α))
export preconnected_space (is_preconnected_univ)
/-- A connected space is a nonempty one where there is no non-trivial open partition. -/
class connected_space (α : Type u) [topological_space α] extends preconnected_space α : Prop :=
(to_nonempty : nonempty α)
attribute [instance, priority 50] connected_space.to_nonempty -- see Note [lower instance priority]
lemma is_connected_range [topological_space β] [connected_space α] {f : α → β} (h : continuous f) :
is_connected (range f) :=
begin
inhabit α,
rw ← image_univ,
exact ⟨⟨f (default α), mem_image_of_mem _ (mem_univ _)⟩,
is_preconnected.image is_preconnected_univ _ h.continuous_on⟩
end
lemma connected_space_iff_connected_component :
connected_space α ↔ ∃ x : α, connected_component x = univ :=
begin
split,
{ rintros ⟨h, ⟨x⟩⟩,
exactI ⟨x, eq_univ_of_univ_subset $ subset_connected_component is_preconnected_univ (mem_univ x)⟩ },
{ rintros ⟨x, h⟩,
haveI : preconnected_space α := ⟨by {rw ← h, exact is_connected_connected_component.2 }⟩,
exact ⟨⟨x⟩⟩ }
end
@[priority 100] -- see Note [lower instance priority]
instance preirreducible_space.preconnected_space (α : Type u) [topological_space α]
[preirreducible_space α] : preconnected_space α :=
⟨(preirreducible_space.is_preirreducible_univ α).is_preconnected⟩
@[priority 100] -- see Note [lower instance priority]
instance irreducible_space.connected_space (α : Type u) [topological_space α]
[irreducible_space α] : connected_space α :=
{ to_nonempty := irreducible_space.to_nonempty α }
theorem nonempty_inter [preconnected_space α] {s t : set α} :
is_open s → is_open t → s ∪ t = univ → s.nonempty → t.nonempty → (s ∩ t).nonempty :=
by simpa only [univ_inter, univ_subset_iff] using
@preconnected_space.is_preconnected_univ α _ _ s t
theorem is_clopen_iff [preconnected_space α] {s : set α} : is_clopen s ↔ s = ∅ ∨ s = univ :=
⟨λ hs, classical.by_contradiction $ λ h,
have h1 : s ≠ ∅ ∧ sᶜ ≠ ∅, from ⟨mt or.inl h,
mt (λ h2, or.inr $ (by rw [← compl_compl s, h2, compl_empty] : s = univ)) h⟩,
let ⟨_, h2, h3⟩ := nonempty_inter hs.1 hs.2 (union_compl_self s)
(ne_empty_iff_nonempty.1 h1.1) (ne_empty_iff_nonempty.1 h1.2) in
h3 h2,
by rintro (rfl | rfl); [exact is_clopen_empty, exact is_clopen_univ]⟩
lemma eq_univ_of_nonempty_clopen [preconnected_space α] {s : set α}
(h : s.nonempty) (h' : is_clopen s) : s = univ :=
by { rw is_clopen_iff at h', finish [h.ne_empty] }
lemma subtype.preconnected_space {s : set α} (h : is_preconnected s) :
preconnected_space s :=
{ is_preconnected_univ :=
begin
intros u v hu hv hs hsu hsv,
rw is_open_induced_iff at hu hv,
rcases hu with ⟨u, hu, rfl⟩,
rcases hv with ⟨v, hv, rfl⟩,
rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩,
rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩,
rcases h u v hu hv _ ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩,
exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩,
intros z hz,
rcases hs (mem_univ ⟨z, hz⟩) with hzu|hzv,
{ left, assumption },
{ right, assumption }
end }
lemma subtype.connected_space {s : set α} (h : is_connected s) :
connected_space s :=
{ is_preconnected_univ :=
(subtype.preconnected_space h.is_preconnected).is_preconnected_univ,
to_nonempty := h.nonempty.to_subtype }
lemma is_preconnected_iff_preconnected_space {s : set α} :
is_preconnected s ↔ preconnected_space s :=
⟨subtype.preconnected_space,
begin
introI,
simpa using is_preconnected_univ.image (coe : s → α) continuous_subtype_coe.continuous_on
end⟩
lemma is_connected_iff_connected_space {s : set α} : is_connected s ↔ connected_space s :=
⟨subtype.connected_space,
λ h, ⟨nonempty_subtype.mp h.2, is_preconnected_iff_preconnected_space.mpr h.1⟩⟩
/-- A set `s` is preconnected if and only if
for every cover by two open sets that are disjoint on `s`,
it is contained in one of the two covering sets. -/
lemma is_preconnected_iff_subset_of_disjoint {s : set α} :
is_preconnected s ↔
∀ (u v : set α) (hu : is_open u) (hv : is_open v) (hs : s ⊆ u ∪ v) (huv : s ∩ (u ∩ v) = ∅),
s ⊆ u ∨ s ⊆ v :=
begin
split; intro h,
{ intros u v hu hv hs huv,
specialize h u v hu hv hs,
contrapose! huv,
rw ne_empty_iff_nonempty,
simp [not_subset] at huv,
rcases huv with ⟨⟨x, hxs, hxu⟩, ⟨y, hys, hyv⟩⟩,
have hxv : x ∈ v := or_iff_not_imp_left.mp (hs hxs) hxu,
have hyu : y ∈ u := or_iff_not_imp_right.mp (hs hys) hyv,
exact h ⟨y, hys, hyu⟩ ⟨x, hxs, hxv⟩ },
{ intros u v hu hv hs hsu hsv,
rw ← ne_empty_iff_nonempty,
intro H,
specialize h u v hu hv hs H,
contrapose H,
apply ne_empty_iff_nonempty.mpr,
cases h,
{ rcases hsv with ⟨x, hxs, hxv⟩, exact ⟨x, hxs, ⟨h hxs, hxv⟩⟩ },
{ rcases hsu with ⟨x, hxs, hxu⟩, exact ⟨x, hxs, ⟨hxu, h hxs⟩⟩ } }
end
/-- A set `s` is connected if and only if
for every cover by a finite collection of open sets that are pairwise disjoint on `s`,
it is contained in one of the members of the collection. -/
lemma is_connected_iff_sUnion_disjoint_open {s : set α} :
is_connected s ↔
∀ (U : finset (set α)) (H : ∀ (u v : set α), u ∈ U → v ∈ U → (s ∩ (u ∩ v)).nonempty → u = v)
(hU : ∀ u ∈ U, is_open u) (hs : s ⊆ ⋃₀ ↑U),
∃ u ∈ U, s ⊆ u :=
begin
rw [is_connected, is_preconnected_iff_subset_of_disjoint],
split; intro h,
{ intro U, apply finset.induction_on U,
{ rcases h.left,
suffices : s ⊆ ∅ → false, { simpa },
intro, solve_by_elim },
{ intros u U hu IH hs hU H,
rw [finset.coe_insert, sUnion_insert] at H,
cases h.2 u (⋃₀ ↑U) _ _ H _ with hsu hsU,
{ exact ⟨u, finset.mem_insert_self _ _, hsu⟩ },
{ rcases IH _ _ hsU with ⟨v, hvU, hsv⟩,
{ exact ⟨v, finset.mem_insert_of_mem hvU, hsv⟩ },
{ intros, apply hs; solve_by_elim [finset.mem_insert_of_mem] },
{ intros, solve_by_elim [finset.mem_insert_of_mem] } },
{ solve_by_elim [finset.mem_insert_self] },
{ apply is_open_sUnion,
intros, solve_by_elim [finset.mem_insert_of_mem] },
{ apply eq_empty_of_subset_empty,
rintro x ⟨hxs, hxu, hxU⟩,
rw mem_sUnion at hxU,
rcases hxU with ⟨v, hvU, hxv⟩,
rcases hs u v (finset.mem_insert_self _ _) (finset.mem_insert_of_mem hvU) _ with rfl,
{ contradiction },
{ exact ⟨x, hxs, hxu, hxv⟩ } } } },
{ split,
{ rw ← ne_empty_iff_nonempty,
by_contradiction hs, push_neg at hs, subst hs,
simpa using h ∅ _ _ _; simp },
intros u v hu hv hs hsuv,
rcases h {u, v} _ _ _ with ⟨t, ht, ht'⟩,
{ rw [finset.mem_insert, finset.mem_singleton] at ht,
rcases ht with rfl|rfl; tauto },
{ intros t₁ t₂ ht₁ ht₂ hst,
rw ← ne_empty_iff_nonempty at hst,
rw [finset.mem_insert, finset.mem_singleton] at ht₁ ht₂,
rcases ht₁ with rfl|rfl; rcases ht₂ with rfl|rfl,
all_goals { refl <|> contradiction <|> skip },
rw inter_comm t₁ at hst, contradiction },
{ intro t,
rw [finset.mem_insert, finset.mem_singleton],
rintro (rfl|rfl); assumption },
{ simpa using hs } }
end
/-- Preconnected sets are either contained in or disjoint to any given clopen set. -/
theorem subset_or_disjoint_of_clopen {α : Type*} [topological_space α] {s t : set α}
(h : is_preconnected t) (h1 : is_clopen s) : s ∩ t = ∅ ∨ t ⊆ s :=
begin
by_contradiction h2,
have h3 : (s ∩ t).nonempty := ne_empty_iff_nonempty.mp (mt or.inl h2),
have h4 : (t ∩ sᶜ).nonempty,
{ apply inter_compl_nonempty_iff.2,
push_neg at h2,
exact h2.2 },
rw [inter_comm] at h3,
apply ne_empty_iff_nonempty.2 (h s sᶜ h1.1 (is_open_compl_iff.2 h1.2) _ h3 h4),
{ rw [inter_compl_self, inter_empty] },
{ rw [union_compl_self],
exact subset_univ t },
end
/-- A set `s` is preconnected if and only if
for every cover by two closed sets that are disjoint on `s`,
it is contained in one of the two covering sets. -/
theorem is_preconnected_iff_subset_of_disjoint_closed {α : Type*} {s : set α} [topological_space α] :
is_preconnected s ↔
∀ (u v : set α) (hu : is_closed u) (hv : is_closed v) (hs : s ⊆ u ∪ v) (huv : s ∩ (u ∩ v) = ∅),
s ⊆ u ∨ s ⊆ v :=
begin
split; intro h,
{ intros u v hu hv hs huv,
rw is_preconnected_closed_iff at h,
specialize h u v hu hv hs,
contrapose! huv,
rw ne_empty_iff_nonempty,
simp [not_subset] at huv,
rcases huv with ⟨⟨x, hxs, hxu⟩, ⟨y, hys, hyv⟩⟩,
have hxv : x ∈ v := or_iff_not_imp_left.mp (hs hxs) hxu,
have hyu : y ∈ u := or_iff_not_imp_right.mp (hs hys) hyv,
exact h ⟨y, hys, hyu⟩ ⟨x, hxs, hxv⟩ },
{ rw is_preconnected_closed_iff,
intros u v hu hv hs hsu hsv,
rw ← ne_empty_iff_nonempty,
intro H,
specialize h u v hu hv hs H,
contrapose H,
apply ne_empty_iff_nonempty.mpr,
cases h,
{ rcases hsv with ⟨x, hxs, hxv⟩, exact ⟨x, hxs, ⟨h hxs, hxv⟩⟩ },
{ rcases hsu with ⟨x, hxs, hxu⟩, exact ⟨x, hxs, ⟨hxu, h hxs⟩⟩ } }
end
/-- A closed set `s` is preconnected if and only if
for every cover by two closed sets that are disjoint,
it is contained in one of the two covering sets. -/
theorem is_preconnected_iff_subset_of_fully_disjoint_closed {s : set α} (hs : is_closed s) :
is_preconnected s ↔
∀ (u v : set α) (hu : is_closed u) (hv : is_closed v) (hss : s ⊆ u ∪ v) (huv : u ∩ v = ∅),
s ⊆ u ∨ s ⊆ v :=
begin
split,
{ intros h u v hu hv hss huv,
apply is_preconnected_iff_subset_of_disjoint_closed.1 h u v hu hv hss,
rw huv,
exact inter_empty s },
intro H,
rw is_preconnected_iff_subset_of_disjoint_closed,
intros u v hu hv hss huv,
have H1 := H (u ∩ s) (v ∩ s),
rw [subset_inter_iff, subset_inter_iff] at H1,
simp only [subset.refl, and_true] at H1,
apply H1 (is_closed_inter hu hs) (is_closed_inter hv hs),
{ rw ←inter_distrib_right,
apply subset_inter_iff.2,
exact ⟨hss, subset.refl s⟩ },
{ rw [inter_comm v s, inter_assoc, ←inter_assoc s, inter_self s,
inter_comm, inter_assoc, inter_comm v u, huv] }
end
/-- The connected component of a point is always a subset of the intersection of all its clopen
neighbourhoods. -/
lemma connected_component_subset_Inter_clopen {x : α} :
connected_component x ⊆ ⋂ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, Z :=
begin
apply subset_Inter (λ Z, _),
cases (subset_or_disjoint_of_clopen (@is_connected_connected_component _ _ x).2 Z.2.1),
{ exfalso,
apply nonempty.ne_empty
(nonempty_of_mem (mem_inter (@mem_connected_component _ _ x) Z.2.2)),
rw inter_comm,
exact h },
exact h,
end
end preconnected
section totally_disconnected
/-- A set is called totally disconnected if all of its connected components are singletons. -/
def is_totally_disconnected (s : set α) : Prop :=
∀ t, t ⊆ s → is_preconnected t → subsingleton t
theorem is_totally_disconnected_empty : is_totally_disconnected (∅ : set α) :=
λ t ht _, ⟨λ ⟨_, h⟩, (ht h).elim⟩
theorem is_totally_disconnected_singleton {x} : is_totally_disconnected ({x} : set α) :=
λ t ht _, ⟨λ ⟨p, hp⟩ ⟨q, hq⟩, subtype.eq $ show p = q,
from (eq_of_mem_singleton (ht hp)).symm ▸ (eq_of_mem_singleton (ht hq)).symm⟩
/-- A space is totally disconnected if all of its connected components are singletons. -/
class totally_disconnected_space (α : Type u) [topological_space α] : Prop :=
(is_totally_disconnected_univ : is_totally_disconnected (univ : set α))
instance pi.totally_disconnected_space {α : Type*} {β : α → Type*} [t₂ : Πa, topological_space (β a)]
[∀a, totally_disconnected_space (β a)] : totally_disconnected_space (Π (a : α), β a) :=
⟨λ t h1 h2, ⟨λ a b, subtype.ext $ funext $ λ x, subtype.mk_eq_mk.1 $
(totally_disconnected_space.is_totally_disconnected_univ
((λ (c : Π (a : α), β a), c x) '' t) (set.subset_univ _)
(is_preconnected.image h2 _ (continuous.continuous_on (continuous_apply _)))).cases_on
(λ h3, h3
⟨(a.1 x), by {simp only [set.mem_image, subtype.val_eq_coe], use a, split,
simp only [subtype.coe_prop]}⟩
⟨(b.1 x), by {simp only [set.mem_image, subtype.val_eq_coe], use b, split,
simp only [subtype.coe_prop]}⟩)⟩⟩
instance subtype.totally_disconnected_space {α : Type*} {p : α → Prop} [topological_space α]
[totally_disconnected_space α] : totally_disconnected_space (subtype p) :=
⟨λ s h1 h2,
set.subsingleton_of_image subtype.val_injective s (
totally_disconnected_space.is_totally_disconnected_univ (subtype.val '' s) (set.subset_univ _)
((is_preconnected.image h2 _) (continuous.continuous_on (@continuous_subtype_val _ _ p))))⟩
end totally_disconnected
section totally_separated
/-- A set `s` is called totally separated if any two points of this set can be separated
by two disjoint open sets covering `s`. -/
def is_totally_separated (s : set α) : Prop :=
∀ x ∈ s, ∀ y ∈ s, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧
x ∈ u ∧ y ∈ v ∧ s ⊆ u ∪ v ∧ u ∩ v = ∅
theorem is_totally_separated_empty : is_totally_separated (∅ : set α) :=
λ x, false.elim
theorem is_totally_separated_singleton {x} : is_totally_separated ({x} : set α) :=
λ p hp q hq hpq, (hpq $ (eq_of_mem_singleton hp).symm ▸ (eq_of_mem_singleton hq).symm).elim
theorem is_totally_disconnected_of_is_totally_separated {s : set α}
(H : is_totally_separated s) : is_totally_disconnected s :=
λ t hts ht, ⟨λ ⟨x, hxt⟩ ⟨y, hyt⟩, subtype.eq $ classical.by_contradiction $
assume hxy : x ≠ y, let ⟨u, v, hu, hv, hxu, hyv, hsuv, huv⟩ := H x (hts hxt) y (hts hyt) hxy in
let ⟨r, hrt, hruv⟩ := ht u v hu hv (subset.trans hts hsuv) ⟨x, hxt, hxu⟩ ⟨y, hyt, hyv⟩ in
(ext_iff.1 huv r).1 hruv⟩
/-- A space is totally separated if any two points can be separated by two disjoint open sets
covering the whole space. -/
class totally_separated_space (α : Type u) [topological_space α] : Prop :=
(is_totally_separated_univ [] : is_totally_separated (univ : set α))
@[priority 100] -- see Note [lower instance priority]
instance totally_separated_space.totally_disconnected_space (α : Type u) [topological_space α]
[totally_separated_space α] : totally_disconnected_space α :=
⟨is_totally_disconnected_of_is_totally_separated $
totally_separated_space.is_totally_separated_univ α⟩
@[priority 100] -- see Note [lower instance priority]
instance totally_separated_space.of_discrete
(α : Type*) [topological_space α] [discrete_topology α] : totally_separated_space α :=
⟨λ a _ b _ h, ⟨{b}ᶜ, {b}, is_open_discrete _, is_open_discrete _, by simpa⟩⟩
end totally_separated
|
98deb31e97cc81ff23b754d9b58768295dd81131 | 367134ba5a65885e863bdc4507601606690974c1 | /src/data/padics/padic_integers.lean | 0b958620d7f42b51fc443a95c483ebf979083ec0 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 20,170 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis, Mario Carneiro, Johan Commelin
-/
import data.int.modeq
import data.zmod.basic
import linear_algebra.adic_completion
import data.padics.padic_numbers
import ring_theory.discrete_valuation_ring
import topology.metric_space.cau_seq_filter
/-!
# p-adic integers
This file defines the p-adic integers `ℤ_p` as the subtype of `ℚ_p` with norm `≤ 1`.
We show that `ℤ_p`
* is complete
* is nonarchimedean
* is a normed ring
* is a local ring
* is a discrete valuation ring
The relation between `ℤ_[p]` and `zmod p` is established in another file.
## Important definitions
* `padic_int` : the type of p-adic numbers
## Notation
We introduce the notation `ℤ_[p]` for the p-adic integers.
## Implementation notes
Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically
by taking `[fact (nat.prime p)] as a type class argument.
Coercions into `ℤ_p` are set up to work with the `norm_cast` tactic.
## References
* [F. Q. Gouêva, *p-adic numbers*][gouvea1997]
* [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]
* <https://en.wikipedia.org/wiki/P-adic_number>
## Tags
p-adic, p adic, padic, p-adic integer
-/
open nat padic metric local_ring
noncomputable theory
open_locale classical
/-- The p-adic integers ℤ_p are the p-adic numbers with norm ≤ 1. -/
def padic_int (p : ℕ) [fact p.prime] := {x : ℚ_[p] // ∥x∥ ≤ 1}
notation `ℤ_[`p`]` := padic_int p
namespace padic_int
/-! ### Ring structure and coercion to `ℚ_[p]` -/
variables {p : ℕ} [fact p.prime]
instance : has_coe ℤ_[p] ℚ_[p] := ⟨subtype.val⟩
lemma ext {x y : ℤ_[p]} : (x : ℚ_[p]) = y → x = y := subtype.ext_iff_val.2
/-- Addition on ℤ_p is inherited from ℚ_p. -/
instance : has_add ℤ_[p] :=
⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x+y,
le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx,hy⟩)⟩⟩
/-- Multiplication on ℤ_p is inherited from ℚ_p. -/
instance : has_mul ℤ_[p] :=
⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x*y,
begin rw padic_norm_e.mul, apply mul_le_one; {assumption <|> apply norm_nonneg} end⟩⟩
/-- Negation on ℤ_p is inherited from ℚ_p. -/
instance : has_neg ℤ_[p] :=
⟨λ ⟨x, hx⟩, ⟨-x, by simpa⟩⟩
/-- Subtraction on ℤ_p is inherited from ℚ_p. -/
instance : has_sub ℤ_[p] :=
⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x - y,
by { rw sub_eq_add_neg, rw ← norm_neg at hy,
exact le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx, hy⟩) }⟩⟩
/-- Zero on ℤ_p is inherited from ℚ_p. -/
instance : has_zero ℤ_[p] :=
⟨⟨0, by norm_num⟩⟩
instance : inhabited ℤ_[p] := ⟨0⟩
/-- One on ℤ_p is inherited from ℚ_p. -/
instance : has_one ℤ_[p] :=
⟨⟨1, by norm_num⟩⟩
@[simp] lemma mk_zero {h} : (⟨0, h⟩ : ℤ_[p]) = (0 : ℤ_[p]) := rfl
@[simp] lemma val_eq_coe (z : ℤ_[p]) : z.val = z := rfl
@[simp, norm_cast] lemma coe_add : ∀ (z1 z2 : ℤ_[p]), ((z1 + z2 : ℤ_[p]) : ℚ_[p]) = z1 + z2
| ⟨_, _⟩ ⟨_, _⟩ := rfl
@[simp, norm_cast] lemma coe_mul : ∀ (z1 z2 : ℤ_[p]), ((z1 * z2 : ℤ_[p]) : ℚ_[p]) = z1 * z2
| ⟨_, _⟩ ⟨_, _⟩ := rfl
@[simp, norm_cast] lemma coe_neg : ∀ (z1 : ℤ_[p]), ((-z1 : ℤ_[p]) : ℚ_[p]) = -z1
| ⟨_, _⟩ := rfl
@[simp, norm_cast] lemma coe_sub : ∀ (z1 z2 : ℤ_[p]), ((z1 - z2 : ℤ_[p]) : ℚ_[p]) = z1 - z2
| ⟨_, _⟩ ⟨_, _⟩ := rfl
@[simp, norm_cast] lemma coe_one : ((1 : ℤ_[p]) : ℚ_[p]) = 1 := rfl
@[simp, norm_cast] lemma coe_coe : ∀ n : ℕ, ((n : ℤ_[p]) : ℚ_[p]) = n
| 0 := rfl
| (k+1) := by simp [coe_coe]
@[simp, norm_cast] lemma coe_coe_int : ∀ (z : ℤ), ((z : ℤ_[p]) : ℚ_[p]) = z
| (int.of_nat n) := by simp
| -[1+n] := by simp
@[simp, norm_cast] lemma coe_zero : ((0 : ℤ_[p]) : ℚ_[p]) = 0 := rfl
instance : ring ℤ_[p] :=
begin
refine { add := (+),
mul := (*),
neg := has_neg.neg,
zero := 0,
one := 1,
sub := has_sub.sub,
sub_eq_add_neg := _,
.. };
intros; ext; simp; ring
end
/-- The coercion from ℤ[p] to ℚ[p] as a ring homomorphism. -/
def coe.ring_hom : ℤ_[p] →+* ℚ_[p] :=
{ to_fun := (coe : ℤ_[p] → ℚ_[p]),
map_zero' := rfl,
map_one' := rfl,
map_mul' := coe_mul,
map_add' := coe_add }
@[simp, norm_cast] lemma coe_pow (x : ℤ_[p]) (n : ℕ) : (↑(x^n) : ℚ_[p]) = (↑x : ℚ_[p])^n :=
coe.ring_hom.map_pow x n
@[simp] lemma mk_coe : ∀ (k : ℤ_[p]), (⟨k, k.2⟩ : ℤ_[p]) = k
| ⟨_, _⟩ := rfl
/-- The inverse of a p-adic integer with norm equal to 1 is also a p-adic integer. Otherwise, the
inverse is defined to be 0. -/
def inv : ℤ_[p] → ℤ_[p]
| ⟨k, _⟩ := if h : ∥k∥ = 1 then ⟨1/k, by simp [h]⟩ else 0
instance : char_zero ℤ_[p] :=
{ cast_injective :=
λ m n h, cast_injective $
show (m:ℚ_[p]) = n, by { rw subtype.ext_iff at h, norm_cast at h, exact h } }
@[simp, norm_cast] lemma coe_int_eq (z1 z2 : ℤ) : (z1 : ℤ_[p]) = z2 ↔ z1 = z2 :=
suffices (z1 : ℚ_[p]) = z2 ↔ z1 = z2, from iff.trans (by norm_cast) this,
by norm_cast
/--
A sequence of integers that is Cauchy with respect to the `p`-adic norm
converges to a `p`-adic integer.
-/
def of_int_seq (seq : ℕ → ℤ) (h : is_cau_seq (padic_norm p) (λ n, seq n)) : ℤ_[p] :=
⟨⟦⟨_, h⟩⟧,
show ↑(padic_seq.norm _) ≤ (1 : ℝ), begin
rw padic_seq.norm,
split_ifs with hne; norm_cast,
{ exact zero_le_one },
{ apply padic_norm.of_int }
end ⟩
end padic_int
namespace padic_int
/-!
### Instances
We now show that `ℤ_[p]` is a
* complete metric space
* normed ring
* integral domain
-/
variables (p : ℕ) [fact p.prime]
instance : metric_space ℤ_[p] := subtype.metric_space
instance complete_space : complete_space ℤ_[p] :=
begin
delta padic_int,
rw [complete_space_iff_is_complete_range uniform_embedding_subtype_coe,
subtype.range_coe_subtype],
have : is_complete (closed_ball (0 : ℚ_[p]) 1) := is_closed_ball.is_complete,
simpa [closed_ball],
end
instance : has_norm ℤ_[p] := ⟨λ z, ∥(z : ℚ_[p])∥⟩
variables {p}
protected lemma mul_comm : ∀ z1 z2 : ℤ_[p], z1*z2 = z2*z1
| ⟨q1, h1⟩ ⟨q2, h2⟩ := show (⟨q1*q2, _⟩ : ℤ_[p]) = ⟨q2*q1, _⟩, by simp [_root_.mul_comm]
protected lemma zero_ne_one : (0 : ℤ_[p]) ≠ 1 :=
show (⟨(0 : ℚ_[p]), _⟩ : ℤ_[p]) ≠ ⟨(1 : ℚ_[p]), _⟩, from mt subtype.ext_iff_val.1 zero_ne_one
protected lemma eq_zero_or_eq_zero_of_mul_eq_zero :
∀ (a b : ℤ_[p]), a * b = 0 → a = 0 ∨ b = 0
| ⟨a, ha⟩ ⟨b, hb⟩ := λ h : (⟨a * b, _⟩ : ℤ_[p]) = ⟨0, _⟩,
have a * b = 0, from subtype.ext_iff_val.1 h,
(mul_eq_zero.1 this).elim
(λ h1, or.inl (by simp [h1]; refl))
(λ h2, or.inr (by simp [h2]; refl))
lemma norm_def {z : ℤ_[p]} : ∥z∥ = ∥(z : ℚ_[p])∥ := rfl
variables (p)
instance : normed_comm_ring ℤ_[p] :=
{ dist_eq := λ ⟨_, _⟩ ⟨_, _⟩, rfl,
norm_mul := λ ⟨_, _⟩ ⟨_, _⟩, norm_mul_le _ _,
mul_comm := padic_int.mul_comm }
instance : norm_one_class ℤ_[p] := ⟨norm_def.trans norm_one⟩
instance is_absolute_value : is_absolute_value (λ z : ℤ_[p], ∥z∥) :=
{ abv_nonneg := norm_nonneg,
abv_eq_zero := λ ⟨_, _⟩, by simp [norm_eq_zero],
abv_add := λ ⟨_,_⟩ ⟨_, _⟩, norm_add_le _ _,
abv_mul := λ _ _, by simp only [norm_def, padic_norm_e.mul, padic_int.coe_mul]}
variables {p}
instance : integral_domain ℤ_[p] :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y, padic_int.eq_zero_or_eq_zero_of_mul_eq_zero x y,
exists_pair_ne := ⟨0, 1, padic_int.zero_ne_one⟩,
.. padic_int.normed_comm_ring p }
end padic_int
namespace padic_int
/-! ### Norm -/
variables {p : ℕ} [fact p.prime]
lemma norm_le_one : ∀ z : ℤ_[p], ∥z∥ ≤ 1
| ⟨_, h⟩ := h
@[simp] lemma norm_mul (z1 z2 : ℤ_[p]) : ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ :=
by simp [norm_def]
@[simp] lemma norm_pow (z : ℤ_[p]) : ∀ n : ℕ, ∥z^n∥ = ∥z∥^n
| 0 := by simp
| (k+1) := show ∥z*z^k∥ = ∥z∥*∥z∥^k, by {rw norm_mul, congr, apply norm_pow}
theorem nonarchimedean : ∀ (q r : ℤ_[p]), ∥q + r∥ ≤ max (∥q∥) (∥r∥)
| ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.nonarchimedean _ _
theorem norm_add_eq_max_of_ne : ∀ {q r : ℤ_[p]}, ∥q∥ ≠ ∥r∥ → ∥q+r∥ = max (∥q∥) (∥r∥)
| ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.add_eq_max_of_ne
lemma norm_eq_of_norm_add_lt_right {z1 z2 : ℤ_[p]}
(h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ :=
by_contradiction $ λ hne,
not_lt_of_ge (by rw norm_add_eq_max_of_ne hne; apply le_max_right) h
lemma norm_eq_of_norm_add_lt_left {z1 z2 : ℤ_[p]}
(h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ :=
by_contradiction $ λ hne,
not_lt_of_ge (by rw norm_add_eq_max_of_ne hne; apply le_max_left) h
@[simp] lemma padic_norm_e_of_padic_int (z : ℤ_[p]) : ∥(↑z : ℚ_[p])∥ = ∥z∥ :=
by simp [norm_def]
lemma norm_int_cast_eq_padic_norm (z : ℤ) : ∥(z : ℤ_[p])∥ = ∥(z : ℚ_[p])∥ :=
by simp [norm_def]
@[simp] lemma norm_eq_padic_norm {q : ℚ_[p]} (hq : ∥q∥ ≤ 1) :
@norm ℤ_[p] _ ⟨q, hq⟩ = ∥q∥ := rfl
@[simp] lemma norm_p : ∥(p : ℤ_[p])∥ = p⁻¹ :=
show ∥((p : ℤ_[p]) : ℚ_[p])∥ = p⁻¹, by exact_mod_cast padic_norm_e.norm_p
@[simp] lemma norm_p_pow (n : ℕ) : ∥(p : ℤ_[p])^n∥ = p^(-n:ℤ) :=
show ∥((p^n : ℤ_[p]) : ℚ_[p])∥ = p^(-n:ℤ),
by { convert padic_norm_e.norm_p_pow n, simp, }
private def cau_seq_to_rat_cau_seq (f : cau_seq ℤ_[p] norm) :
cau_seq ℚ_[p] (λ a, ∥a∥) :=
⟨ λ n, f n,
λ _ hε, by simpa [norm, norm_def] using f.cauchy hε ⟩
variables (p)
instance complete : cau_seq.is_complete ℤ_[p] norm :=
⟨ λ f,
have hqn : ∥cau_seq.lim (cau_seq_to_rat_cau_seq f)∥ ≤ 1,
from padic_norm_e_lim_le zero_lt_one (λ _, norm_le_one _),
⟨ ⟨_, hqn⟩,
λ ε, by simpa [norm, norm_def] using cau_seq.equiv_lim (cau_seq_to_rat_cau_seq f) ε⟩⟩
end padic_int
namespace padic_int
variables (p : ℕ) [hp_prime : fact p.prime]
include hp_prime
lemma exists_pow_neg_lt {ε : ℝ} (hε : 0 < ε) :
∃ (k : ℕ), ↑p ^ -((k : ℕ) : ℤ) < ε :=
begin
obtain ⟨k, hk⟩ := exists_nat_gt ε⁻¹,
use k,
rw ← inv_lt_inv hε (_root_.fpow_pos_of_pos _ _),
{ rw [fpow_neg, inv_inv', fpow_coe_nat],
apply lt_of_lt_of_le hk,
norm_cast,
apply le_of_lt,
convert nat.lt_pow_self _ _ using 1,
exact hp_prime.one_lt },
{ exact_mod_cast hp_prime.pos }
end
lemma exists_pow_neg_lt_rat {ε : ℚ} (hε : 0 < ε) :
∃ (k : ℕ), ↑p ^ -((k : ℕ) : ℤ) < ε :=
begin
obtain ⟨k, hk⟩ := @exists_pow_neg_lt p _ ε (by exact_mod_cast hε),
use k,
rw (show (p : ℝ) = (p : ℚ), by simp) at hk,
exact_mod_cast hk
end
variable {p}
lemma norm_int_lt_one_iff_dvd (k : ℤ) : ∥(k : ℤ_[p])∥ < 1 ↔ ↑p ∣ k :=
suffices ∥(k : ℚ_[p])∥ < 1 ↔ ↑p ∣ k, by rwa norm_int_cast_eq_padic_norm,
padic_norm_e.norm_int_lt_one_iff_dvd k
lemma norm_int_le_pow_iff_dvd {k : ℤ} {n : ℕ} : ∥(k : ℤ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑p^n ∣ k :=
suffices ∥(k : ℚ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑(p^n) ∣ k, by simpa [norm_int_cast_eq_padic_norm],
padic_norm_e.norm_int_le_pow_iff_dvd _ _
/-! ### Valuation on `ℤ_[p]` -/
/-- `padic_int.valuation` lifts the p-adic valuation on `ℚ` to `ℤ_[p]`. -/
def valuation (x : ℤ_[p]) := padic.valuation (x : ℚ_[p])
lemma norm_eq_pow_val {x : ℤ_[p]} (hx : x ≠ 0) :
∥x∥ = p^(-x.valuation) :=
begin
convert padic.norm_eq_pow_val _,
contrapose! hx,
exact subtype.val_injective hx
end
@[simp] lemma valuation_zero : valuation (0 : ℤ_[p]) = 0 :=
padic.valuation_zero
@[simp] lemma valuation_one : valuation (1 : ℤ_[p]) = 0 :=
padic.valuation_one
@[simp] lemma valuation_p : valuation (p : ℤ_[p]) = 1 :=
by simp [valuation, -cast_eq_of_rat_of_nat]
lemma valuation_nonneg (x : ℤ_[p]) : 0 ≤ x.valuation :=
begin
by_cases hx : x = 0,
{ simp [hx] },
have h : (1 : ℝ) < p := by exact_mod_cast hp_prime.one_lt,
rw [← neg_nonpos, ← (fpow_strict_mono h).le_iff_le],
show (p : ℝ) ^ -valuation x ≤ p ^ 0,
rw [← norm_eq_pow_val hx],
simpa using x.property,
end
@[simp] lemma valuation_p_pow_mul (n : ℕ) (c : ℤ_[p]) (hc : c ≠ 0) :
(↑p ^ n * c).valuation = n + c.valuation :=
begin
have : ∥↑p ^ n * c∥ = ∥(p ^ n : ℤ_[p])∥ * ∥c∥,
{ exact norm_mul _ _ },
have aux : ↑p ^ n * c ≠ 0,
{ contrapose! hc, rw mul_eq_zero at hc, cases hc,
{ refine (hp_prime.ne_zero _).elim,
exact_mod_cast (pow_eq_zero hc) },
{ exact hc } },
rwa [norm_eq_pow_val aux, norm_p_pow, norm_eq_pow_val hc,
← fpow_add, ← neg_add, fpow_inj, neg_inj] at this,
{ exact_mod_cast hp_prime.pos },
{ exact_mod_cast hp_prime.ne_one },
{ exact_mod_cast hp_prime.ne_zero },
end
section units
/-! ### Units of `ℤ_[p]` -/
local attribute [reducible] padic_int
lemma mul_inv : ∀ {z : ℤ_[p]}, ∥z∥ = 1 → z * z.inv = 1
| ⟨k, _⟩ h :=
begin
have hk : k ≠ 0, from λ h', @zero_ne_one ℚ_[p] _ _ (by simpa [h'] using h),
unfold padic_int.inv, split_ifs,
{ change (⟨k * (1/k), _⟩ : ℤ_[p]) = 1,
simp [hk], refl },
{ apply subtype.ext_iff_val.2, simp [mul_inv_cancel hk] }
end
lemma inv_mul {z : ℤ_[p]} (hz : ∥z∥ = 1) : z.inv * z = 1 :=
by rw [mul_comm, mul_inv hz]
lemma is_unit_iff {z : ℤ_[p]} : is_unit z ↔ ∥z∥ = 1 :=
⟨λ h, begin
rcases is_unit_iff_dvd_one.1 h with ⟨w, eq⟩,
refine le_antisymm (norm_le_one _) _,
have := mul_le_mul_of_nonneg_left (norm_le_one w) (norm_nonneg z),
rwa [mul_one, ← norm_mul, ← eq, norm_one] at this
end, λ h, ⟨⟨z, z.inv, mul_inv h, inv_mul h⟩, rfl⟩⟩
lemma norm_lt_one_add {z1 z2 : ℤ_[p]} (hz1 : ∥z1∥ < 1) (hz2 : ∥z2∥ < 1) : ∥z1 + z2∥ < 1 :=
lt_of_le_of_lt (nonarchimedean _ _) (max_lt hz1 hz2)
lemma norm_lt_one_mul {z1 z2 : ℤ_[p]} (hz2 : ∥z2∥ < 1) : ∥z1 * z2∥ < 1 :=
calc ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ : by simp
... < 1 : mul_lt_one_of_nonneg_of_lt_one_right (norm_le_one _) (norm_nonneg _) hz2
@[simp] lemma mem_nonunits {z : ℤ_[p]} : z ∈ nonunits ℤ_[p] ↔ ∥z∥ < 1 :=
by rw lt_iff_le_and_ne; simp [norm_le_one z, nonunits, is_unit_iff]
/-- A `p`-adic number `u` with `∥u∥ = 1` is a unit of `ℤ_[p]`. -/
def mk_units {u : ℚ_[p]} (h : ∥u∥ = 1) : units ℤ_[p] :=
let z : ℤ_[p] := ⟨u, le_of_eq h⟩ in ⟨z, z.inv, mul_inv h, inv_mul h⟩
@[simp]
lemma mk_units_eq {u : ℚ_[p]} (h : ∥u∥ = 1) : ((mk_units h : ℤ_[p]) : ℚ_[p]) = u :=
rfl
@[simp] lemma norm_units (u : units ℤ_[p]) : ∥(u : ℤ_[p])∥ = 1 :=
is_unit_iff.mp $ by simp
/-- `unit_coeff hx` is the unit `u` in the unique representation `x = u * p ^ n`.
See `unit_coeff_spec`. -/
def unit_coeff {x : ℤ_[p]} (hx : x ≠ 0) : units ℤ_[p] :=
let u : ℚ_[p] := x*p^(-x.valuation) in
have hu : ∥u∥ = 1,
by simp [hx, nat.fpow_ne_zero_of_pos (by exact_mod_cast hp_prime.pos) x.valuation,
norm_eq_pow_val, fpow_neg, inv_mul_cancel, -cast_eq_of_rat_of_nat],
mk_units hu
@[simp] lemma unit_coeff_coe {x : ℤ_[p]} (hx : x ≠ 0) :
(unit_coeff hx : ℚ_[p]) = x * p ^ (-x.valuation) := rfl
lemma unit_coeff_spec {x : ℤ_[p]} (hx : x ≠ 0) :
x = (unit_coeff hx : ℤ_[p]) * p ^ int.nat_abs (valuation x) :=
begin
apply subtype.coe_injective,
push_cast,
have repr : (x : ℚ_[p]) = (unit_coeff hx) * p ^ x.valuation,
{ rw [unit_coeff_coe, mul_assoc, ← fpow_add],
{ simp },
{ exact_mod_cast hp_prime.ne_zero } },
convert repr using 2,
rw [← fpow_coe_nat, int.nat_abs_of_nonneg (valuation_nonneg x)],
end
end units
section norm_le_iff
/-! ### Various characterizations of open unit balls -/
lemma norm_le_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) :
∥x∥ ≤ p ^ (-n : ℤ) ↔ ↑n ≤ x.valuation :=
begin
rw norm_eq_pow_val hx,
lift x.valuation to ℕ using x.valuation_nonneg with k hk,
simp only [int.coe_nat_le, fpow_neg, fpow_coe_nat],
have aux : ∀ n : ℕ, 0 < (p ^ n : ℝ),
{ apply pow_pos, exact_mod_cast nat.prime.pos ‹_› },
rw [inv_le_inv (aux _) (aux _)],
have : p ^ n ≤ p ^ k ↔ n ≤ k := (pow_right_strict_mono (nat.prime.two_le ‹_›)).le_iff_le,
rw [← this],
norm_cast,
end
lemma mem_span_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) :
x ∈ (ideal.span {p ^ n} : ideal ℤ_[p]) ↔ ↑n ≤ x.valuation :=
begin
rw [ideal.mem_span_singleton],
split,
{ rintro ⟨c, rfl⟩,
suffices : c ≠ 0,
{ rw [valuation_p_pow_mul _ _ this, le_add_iff_nonneg_right], apply valuation_nonneg, },
contrapose! hx, rw [hx, mul_zero], },
{ rw [unit_coeff_spec hx] { occs := occurrences.pos [2] },
lift x.valuation to ℕ using x.valuation_nonneg with k hk,
simp only [int.nat_abs_of_nat, is_unit_unit, is_unit.dvd_mul_left, int.coe_nat_le],
intro H,
obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le H,
simp only [pow_add, dvd_mul_right], }
end
lemma norm_le_pow_iff_mem_span_pow (x : ℤ_[p]) (n : ℕ) :
∥x∥ ≤ p ^ (-n : ℤ) ↔ x ∈ (ideal.span {p ^ n} : ideal ℤ_[p]) :=
begin
by_cases hx : x = 0,
{ subst hx,
simp only [norm_zero, fpow_neg, fpow_coe_nat, inv_nonneg, iff_true, submodule.zero_mem],
exact_mod_cast nat.zero_le _ },
rw [norm_le_pow_iff_le_valuation x hx, mem_span_pow_iff_le_valuation x hx],
end
lemma norm_le_pow_iff_norm_lt_pow_add_one (x : ℤ_[p]) (n : ℤ) :
∥x∥ ≤ p ^ n ↔ ∥x∥ < p ^ (n + 1) :=
begin
have aux : ∀ n : ℤ, 0 < (p ^ n : ℝ),
{ apply nat.fpow_pos_of_pos, exact nat.prime.pos ‹_› },
by_cases hx0 : x = 0, { simp [hx0, norm_zero, aux, le_of_lt (aux _)], },
rw norm_eq_pow_val hx0,
have h1p : 1 < (p : ℝ), { exact_mod_cast nat.prime.one_lt ‹_› },
have H := fpow_strict_mono h1p,
rw [H.le_iff_le, H.lt_iff_lt, int.lt_add_one_iff],
end
lemma norm_lt_pow_iff_norm_le_pow_sub_one (x : ℤ_[p]) (n : ℤ) :
∥x∥ < p ^ n ↔ ∥x∥ ≤ p ^ (n - 1) :=
by rw [norm_le_pow_iff_norm_lt_pow_add_one, sub_add_cancel]
lemma norm_lt_one_iff_dvd (x : ℤ_[p]) : ∥x∥ < 1 ↔ ↑p ∣ x :=
begin
have := norm_le_pow_iff_mem_span_pow x 1,
rw [ideal.mem_span_singleton, pow_one] at this,
rw [← this, norm_le_pow_iff_norm_lt_pow_add_one],
simp only [fpow_zero, int.coe_nat_zero, int.coe_nat_succ, add_left_neg, zero_add],
end
@[simp] lemma pow_p_dvd_int_iff (n : ℕ) (a : ℤ) : (p ^ n : ℤ_[p]) ∣ a ↔ ↑p ^ n ∣ a :=
by rw [← norm_int_le_pow_iff_dvd, norm_le_pow_iff_mem_span_pow, ideal.mem_span_singleton]
end norm_le_iff
section dvr
/-! ### Discrete valuation ring -/
instance : local_ring ℤ_[p] :=
local_of_nonunits_ideal zero_ne_one $ λ x y, by simp; exact norm_lt_one_add
lemma p_nonnunit : (p : ℤ_[p]) ∈ nonunits ℤ_[p] :=
have (p : ℝ)⁻¹ < 1, from inv_lt_one $ by exact_mod_cast hp_prime.one_lt,
by simp [this]
lemma maximal_ideal_eq_span_p : maximal_ideal ℤ_[p] = ideal.span {p} :=
begin
apply le_antisymm,
{ intros x hx,
rw ideal.mem_span_singleton,
simp only [local_ring.mem_maximal_ideal, mem_nonunits] at hx,
rwa ← norm_lt_one_iff_dvd, },
{ rw [ideal.span_le, set.singleton_subset_iff], exact p_nonnunit }
end
lemma prime_p : prime (p : ℤ_[p]) :=
begin
rw [← ideal.span_singleton_prime, ← maximal_ideal_eq_span_p],
{ apply_instance },
{ exact_mod_cast hp_prime.ne_zero }
end
lemma irreducible_p : irreducible (p : ℤ_[p]) :=
irreducible_of_prime prime_p
instance : discrete_valuation_ring ℤ_[p] :=
discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization
⟨p, irreducible_p, λ x hx, ⟨x.valuation.nat_abs, unit_coeff hx,
by rw [mul_comm, ← unit_coeff_spec hx]⟩⟩
lemma ideal_eq_span_pow_p {s : ideal ℤ_[p]} (hs : s ≠ ⊥) :
∃ n : ℕ, s = ideal.span {p ^ n} :=
discrete_valuation_ring.ideal_eq_span_pow_irreducible hs irreducible_p
end dvr
end padic_int
|
95883f3ad7f804cb0bfceca0e7dfc4290dddacfb | 59aed81a2ce7741e690907fc374be338f4f88b6f | /src/math-688/homework/hw-3.lean | c7fb08d3d99e5c1166b711e2e4acfc016e348816 | [] | no_license | agusakov/math-688-lean | c84d5e1423eb208a0281135f0214b91b30d0ef48 | 67dc27ebff55a74c6b5a1c469ba04e7981d2e550 | refs/heads/main | 1,679,699,340,788 | 1,616,602,782,000 | 1,616,602,782,000 | 332,894,454 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 662 | lean | /- Homework 3 -/
/-
1. Let `A` be a real and symmetric `n × n` matrix. For each eigenvalue `θ` of `A`,
let `Uθ` be a matrix whose columns form an orthonormal basis for the eigenspace
corresponding to `θ` and denote `Eθ = Uθ * Uθᵀ`. The matrices `Eθ` are called
the principal idempotents of `A`. The set of (distinct) eigenvalues of `A` is
denoted by `ev(A)`.
-/
/- 1a. Prove that `Eθ² = Uθ * Uθᵀ` and `Eθ * Er = 0` if `θ ≠ r`. -/
/-
2. Let `G` be an undirected simple graph on n vertices with adjacency matrix
`A` whose eigenvalues are `λ1, λ2, ..., λn`. Let `H` be the graph obtained
from `G` by removing vertex `1`.
-/ |
dc6a5c9794a5591578b5c6aa6c2bd4c6578a3f09 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/trans.lean | 9d782e6d253a5c28ea6c39760ed1b684c070bbde | [
"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 | 1,090 | lean | -- Copyright (c) 2014 Microsoft Corporation. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Author: Leonardo de Moura
import logic
open eq
definition refl := @eq.refl
definition transport {A : Type} {a b : A} {P : A → Type} (p : a = b) (H : P a) : P b
:= eq.rec H p
theorem transport_refl {A : Type} {a : A} {P : A → Type} (H : P a) : transport (refl a) H = H
:= refl H
attribute transport [irreducible]
theorem transport_proof_irrel {A : Type} {a b : A} {P : A → Type} (p1 p2 : a = b) (H : P a) : transport p1 H = transport p2 H
:= refl (transport p1 H)
theorem transport_eq {A : Type} {a : A} {P : A → Type} (p : a = a) (H : P a) : transport p H = H
:= calc transport p H = transport (refl a) H : transport_proof_irrel p (refl a) H
... = H : transport_refl H
theorem dcongr {A : Type} {B : A → Type} {a b : A} (f : Π x, B x) (p : a = b) : transport p (f a) = f b
:= have H1 : ∀ p1 : a = a, transport p1 (f a) = f a, from
assume p1 : a = a, transport_eq p1 (f a),
eq.rec H1 p p
|
b692e30f0d119671b68e6d928df554fe657566a4 | c2b0bd5aa4b3f4fb8a887fab57c5fc08be03aa01 | /lambda.lean | 1ec452a7cc82bf3a2c47421bfcc621e20ddcf2be | [] | no_license | cipher1024/lambda-calc | f72aa6dedea96fc7831d1898f3150a18baefdf0b | 327eaa12588018c01b2205f3e4e0048de1d97afd | refs/heads/master | 1,625,672,854,392 | 1,507,233,523,000 | 1,507,233,523,000 | 99,383,225 | 4 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,417 | lean |
import data.vector
import .variables.nary
import .lens
universes u u₀ u₁ u₂ u₃
namespace lambda
open nat has_map nary lenses
inductive expr (α β : Type u) : list ℕ → Type u
| var : ∀{n}, var α n → expr n
| app : ∀{n}, expr n → expr n → expr n
| abstr : ∀n {xs}, vector β n → expr (n :: xs) → expr xs
| skip : ∀n {xs}, expr xs → expr (n :: xs)
def expand {α β : Type u} {n : ℕ} {xs : list ℕ}
: expr α β xs → expr α β (n :: xs) :=
expr.skip n
def bind {γ α α'}
: ∀ {xs xs'},
expr α γ xs →
(var α xs → expr α' γ xs') →
expr α' γ xs'
| xs xs' (expr.var ._ v) f := f v
| xs xs' (expr.app e₀ e₁) f := expr.app (bind e₀ f) (bind e₁ f)
| xs xs' (expr.abstr n' v e) f := expr.abstr n' v
(bind e $ var.rec' (expr.var _ ∘ var.mk_bound) (expr.skip _ ∘ f) )
| (x :: xs) xs' (expr.skip ._ e) f :=
bind e (f ∘ var.bump)
def expr.free {α β : Type u} {xs : list ℕ} : α -> expr α β xs :=
expr.var _ ∘ var.free _
def expr.bound {α β : Type u} {xs : list ℕ} : sum_of xs -> expr α β xs :=
expr.var _ ∘ var.bound _
def expr.mk_bound {α β : Type u} {x : ℕ} {xs : list ℕ} : fin x -> expr α β (x::xs) :=
expr.var _ ∘ var.mk_bound
def substitute {γ α β : Type u} {xs : list ℕ}
(f : α → expr β γ xs)
(e : expr α γ xs)
: expr β γ xs :=
bind e $ λ r, var.rec_on r expr.bound f
def instantiate {α β : Type u} {n : ℕ}
(f : fin n → α) {xs : list ℕ}
(e : expr α β (n :: xs))
: expr α β xs :=
bind e $ λ r, var.rec' (expr.free ∘ f) (expr.var _) r
def abstract {α β : Type u} {n : ℕ}
(f : α → option (fin n)) {xs : list ℕ}
(e : expr α β xs)
: expr α β (n :: xs) :=
bind e $ λ r, var.rec_on r
(expr.bound ∘ sum_of.inr)
(λ r, option.rec_on (f r) (expr.free r) expr.mk_bound)
def vars_ln {β f} [applicative f] {α α'}
: ∀ {n n'},
(var α n → f (var α' n')) →
(expr α β n → f (expr α' β n'))
| n n' F (expr.var ._ v) :=
expr.var _ <$> F v
| n n' F (expr.app e₀ e₁) := expr.app <$> vars_ln F e₀ <*> vars_ln F e₁
| (n :: ns) n' F (expr.skip ._ e) := vars_ln (F ∘ var.bump) e
| ns ns' F (expr.abstr n v e) := expr.abstr n v <$> vars_ln (var.splitting F) e
def vars {α α' n n' β}
: traversal (expr α β n) (expr α' β n') (var α n) (var α' n')
| F _inst := @vars_ln _ F _inst _ _ _ _
end lambda
|
6a398a3017764d6194ee0f1646ae5b327ab8ffd2 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/order/countable_dense_linear_order.lean | 3ff3aaed0191968b793f3c6ffc0bf0b6879c0944 | [
"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 | 9,636 | lean | /-
Copyright (c) 2020 David Wärn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Wärn
-/
import order.ideal
import data.finset
/-!
# The back and forth method and countable dense linear orders
## Results
Suppose `α β` are linear orders, with `α` countable and `β` dense, nonempty, without endpoints.
Then there is an order embedding `α ↪ β`. If in addition `α` is dense, nonempty, without
endpoints and `β` is countable, then we can upgrade this to an order isomorphism `α ≃ β`.
The idea for both results is to consider "partial isomorphisms", which
identify a finite subset of `α` with a finite subset of `β`, and prove that
for any such partial isomorphism `f` and `a : α`, we can extend `f` to
include `a` in its domain.
## References
https://en.wikipedia.org/wiki/Back-and-forth_method
## Tags
back and forth, dense, countable, order
-/
noncomputable theory
open_locale classical
namespace order
/-- Suppose `α` is a nonempty dense linear order without endpoints, and
suppose `lo`, `hi`, are finite subssets with all of `lo` strictly
before `hi`. Then there is an element of `α` strictly between `lo`
and `hi`. -/
lemma exists_between_finsets {α : Type*} [linear_order α]
[densely_ordered α] [no_bot_order α] [no_top_order α] [nonem : nonempty α]
(lo hi : finset α) (lo_lt_hi : ∀ (x ∈ lo) (y ∈ hi), x < y) :
∃ m : α, (∀ x ∈ lo, x < m) ∧ (∀ y ∈ hi, m < y) :=
if nlo : lo.nonempty then
if nhi : hi.nonempty then -- both sets are nonempty, use densely_ordered
exists.elim (exists_between (lo_lt_hi _ (finset.max'_mem _ nlo) _ (finset.min'_mem _ nhi)))
(λ m hm, ⟨m, λ x hx, lt_of_le_of_lt (finset.le_max' lo x hx) hm.1,
λ y hy, lt_of_lt_of_le hm.2 (finset.min'_le hi y hy)⟩)
else -- upper set is empty, use no_top_order
exists.elim (no_top (finset.max' lo nlo)) (λ m hm,
⟨m, λ x hx, lt_of_le_of_lt (finset.le_max' lo x hx) hm,
λ y hy, (nhi ⟨y, hy⟩).elim⟩)
else
if nhi : hi.nonempty then -- lower set is empty, use no_bot_order
exists.elim (no_bot (finset.min' hi nhi)) (λ m hm,
⟨m, λ x hx, (nlo ⟨x, hx⟩).elim,
λ y hy, lt_of_lt_of_le hm (finset.min'_le hi y hy)⟩)
else -- both sets are empty, use nonempty
nonem.elim (λ m,
⟨m, λ x hx, (nlo ⟨x, hx⟩).elim,
λ y hy, (nhi ⟨y, hy⟩).elim⟩)
variables (α β : Type*) [linear_order α] [linear_order β]
/-- The type of partial order isomorphisms between `α` and `β` defined on finite subsets.
A partial order isomorphism is encoded as a finite subset of `α × β`, consisting
of pairs which should be identified. -/
def partial_iso : Type* :=
{ f : finset (α × β) // ∀ (p q ∈ f),
cmp (prod.fst p) (prod.fst q) = cmp (prod.snd p) (prod.snd q) }
namespace partial_iso
instance : inhabited (partial_iso α β) := ⟨⟨∅, λ p q h, h.elim⟩⟩
instance : preorder (partial_iso α β) := subtype.preorder _
variables {α β}
/-- For each `a`, we can find a `b` in the codomain, such that `a`'s relation to
the domain of `f` is `b`'s relation to the image of `f`.
Thus, if `a` is not already in `f`, then we can extend `f` by sending `a` to `b`.
-/
lemma exists_across [densely_ordered β] [no_bot_order β] [no_top_order β] [nonempty β]
(f : partial_iso α β) (a : α) :
∃ b : β, ∀ (p ∈ f.val), cmp (prod.fst p) a = cmp (prod.snd p) b :=
begin
by_cases h : ∃ b, (a, b) ∈ f.val,
{ cases h with b hb, exact ⟨b, λ p hp, f.property _ _ hp hb⟩, },
have : ∀ (x ∈ (f.val.filter (λ (p : α × β), p.fst < a)).image prod.snd)
(y ∈ (f.val.filter (λ (p : α × β), a < p.fst)).image prod.snd),
x < y,
{ intros x hx y hy,
rw finset.mem_image at hx hy,
rcases hx with ⟨p, hp1, rfl⟩,
rcases hy with ⟨q, hq1, rfl⟩,
rw finset.mem_filter at hp1 hq1,
rw ←lt_iff_lt_of_cmp_eq_cmp (f.property _ _ hp1.1 hq1.1),
exact lt_trans hp1.right hq1.right, },
cases exists_between_finsets _ _ this with b hb,
use b,
rintros ⟨p1, p2⟩ hp,
have : p1 ≠ a := λ he, h ⟨p2, he ▸ hp⟩,
cases lt_or_gt_of_ne this with hl hr,
{ have : p1 < a ∧ p2 < b := ⟨hl, hb.1 _ (finset.mem_image.mpr ⟨(p1, p2),
finset.mem_filter.mpr ⟨hp, hl⟩, rfl⟩)⟩,
rw [←cmp_eq_lt_iff, ←cmp_eq_lt_iff] at this, cc, },
{ have : a < p1 ∧ b < p2 := ⟨hr, hb.2 _ (finset.mem_image.mpr ⟨(p1, p2),
finset.mem_filter.mpr ⟨hp, hr⟩, rfl⟩)⟩,
rw [←cmp_eq_gt_iff, ←cmp_eq_gt_iff] at this, cc, },
end
/-- A partial isomorphism between `α` and `β` is also a partial isomorphism between `β` and `α`. -/
protected def comm : partial_iso α β → partial_iso β α :=
subtype.map (finset.image (equiv.prod_comm _ _)) $ λ f hf p q hp hq,
eq.symm $ hf ((equiv.prod_comm α β).symm p) ((equiv.prod_comm α β).symm q)
(by { rw [←finset.mem_coe, finset.coe_image, equiv.image_eq_preimage] at hp, rwa ←finset.mem_coe })
(by { rw [←finset.mem_coe, finset.coe_image, equiv.image_eq_preimage] at hq, rwa ←finset.mem_coe })
variable (β)
/-- The set of partial isomorphisms defined at `a : α`, together with a proof that any
partial isomorphism can be extended to one defined at `a`. -/
def defined_at_left [densely_ordered β] [no_bot_order β] [no_top_order β] [nonempty β]
(a : α) : cofinal (partial_iso α β) :=
{ carrier := λ f, ∃ b : β, (a, b) ∈ f.val,
mem_gt :=
begin
intro f,
cases exists_across f a with b a_b,
refine ⟨⟨insert (a, b) f.val, _⟩, ⟨b, finset.mem_insert_self _ _⟩, finset.subset_insert _ _⟩,
intros p q hp hq,
rw finset.mem_insert at hp hq,
rcases hp with rfl | pf;
rcases hq with rfl | qf,
{ simp },
{ rw cmp_eq_cmp_symm, exact a_b _ qf },
{ exact a_b _ pf },
{ exact f.property _ _ pf qf },
end }
variables (α) {β}
/-- The set of partial isomorphisms defined at `b : β`, together with a proof that any
partial isomorphism can be extended to include `b`. We prove this by symmetry. -/
def defined_at_right [densely_ordered α] [no_bot_order α] [no_top_order α] [nonempty α]
(b : β) : cofinal (partial_iso α β) :=
{ carrier := λ f, ∃ a, (a, b) ∈ f.val,
mem_gt :=
begin
intro f,
rcases (defined_at_left α b).mem_gt f.comm with ⟨f', ⟨a, ha⟩, hl⟩,
use f'.comm,
split,
{ use a,
change (a, b) ∈ f'.val.image _,
rwa [←finset.mem_coe, finset.coe_image, equiv.image_eq_preimage] },
{ change _ ⊆ f'.val.image _,
rw [←finset.coe_subset, finset.coe_image, ← equiv.subset_image],
change f.val.image _ ⊆ _ at hl,
rwa [←finset.coe_subset, finset.coe_image] at hl }
end }
variable {α}
/-- Given an ideal which intersects `defined_at_left β a`, pick `b : β` such that
some partial function in the ideal maps `a` to `b`. -/
def fun_of_ideal [densely_ordered β] [no_bot_order β] [no_top_order β] [nonempty β]
(a : α) (I : ideal (partial_iso α β)) :
(∃ f, f ∈ defined_at_left β a ∧ f ∈ I) → { b // ∃ f ∈ I, (a, b) ∈ subtype.val f } :=
classical.indefinite_description _ ∘ (λ ⟨f, ⟨b, hb⟩, hf⟩, ⟨b, f, hf, hb⟩)
/-- Given an ideal which intersects `defined_at_right α b`, pick `a : α` such that
some partial function in the ideal maps `a` to `b`. -/
def inv_of_ideal [densely_ordered α] [no_bot_order α] [no_top_order α] [nonempty α]
(b : β) (I : ideal (partial_iso α β)) :
(∃ f, f ∈ defined_at_right α b ∧ f ∈ I) → { a // ∃ f ∈ I, (a, b) ∈ subtype.val f } :=
classical.indefinite_description _ ∘ (λ ⟨f, ⟨a, ha⟩, hf⟩, ⟨a, f, hf, ha⟩)
end partial_iso
open partial_iso
variables (α β)
/-- Any countable linear order embeds in any nonempty dense linear order without endpoints. -/
def embedding_from_countable_to_dense
[encodable α] [densely_ordered β] [no_bot_order β] [no_top_order β] [nonempty β] :
α ↪o β :=
let our_ideal : ideal (partial_iso α β) := ideal_of_cofinals (default _) (defined_at_left β) in
let F := λ a, fun_of_ideal a our_ideal (cofinal_meets_ideal_of_cofinals _ _ a) in
order_embedding.of_strict_mono (λ a, (F a).val)
begin
intros a₁ a₂,
rcases (F a₁).property with ⟨f, hf, ha₁⟩,
rcases (F a₂).property with ⟨g, hg, ha₂⟩,
rcases our_ideal.directed _ hf _ hg with ⟨m, hm, fm, gm⟩,
exact (lt_iff_lt_of_cmp_eq_cmp $ m.property (a₁, _) (a₂, _) (fm ha₁) (gm ha₂)).mp
end
/-- Any two countable dense, nonempty linear orders without endpoints are order isomorphic. -/
def iso_of_countable_dense
[encodable α] [densely_ordered α] [no_bot_order α] [no_top_order α] [nonempty α]
[encodable β] [densely_ordered β] [no_bot_order β] [no_top_order β] [nonempty β] :
α ≃o β :=
let to_cofinal : α ⊕ β → cofinal (partial_iso α β) :=
λ p, sum.rec_on p (defined_at_left β) (defined_at_right α) in
let our_ideal : ideal (partial_iso α β) := ideal_of_cofinals (default _) to_cofinal in
let F := λ a, fun_of_ideal a our_ideal (cofinal_meets_ideal_of_cofinals _ to_cofinal (sum.inl a)) in
let G := λ b, inv_of_ideal b our_ideal (cofinal_meets_ideal_of_cofinals _ to_cofinal (sum.inr b)) in
order_iso.of_cmp_eq_cmp (λ a, (F a).val) (λ b, (G b).val)
begin
intros a b,
rcases (F a).property with ⟨f, hf, ha⟩,
rcases (G b).property with ⟨g, hg, hb⟩,
rcases our_ideal.directed _ hf _ hg with ⟨m, hm, fm, gm⟩,
exact m.property (a, _) (_, b) (fm ha) (gm hb)
end
end order
|
65f04e994b810e57f9da960f34a8edd6a4561e01 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /docs/tutorial/category_theory/intro.lean | ccbbca5d24d812dca6d6680336844e74a0d694c8 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 9,135 | lean | import category_theory.functor.category -- this transitively imports
-- category_theory.category
-- category_theory.functor
-- category_theory.natural_transformation
/-!
# An introduction to category theory in Lean
This is an introduction to the basic usage of category theory (in the mathematical sense) in Lean.
We cover how the basic theory of categories, functors and natural transformations is set up in Lean.
Most of the below is not hard to read off from the files `category_theory/category.lean`,
`category_theory/functor.lean` and `category_theory/natural_transformation.lean`.
## Overview
A category is a collection of objects, and a collection of morphisms (also known as arrows) between
the objects. The objects and morphisms have some extra structure and satisfy some axioms -- see the
[definition on Wikipedia](https://en.wikipedia.org/wiki/Category_%28mathematics%29#Definition) for
details.
One important thing to note is that a morphism in an abstract category may not be an actual function
between two types. In particular, there is new notation `⟶` , typed as `\h` or `\hom` in VS Code,
for a morphism. Nevertheless, in most of the "concrete" categories like `Top` and `Ab`, it is still
possible to write `f x` when `x : X` and `f : X ⟶ Y` is a morphism, as there is an automatic
coercion from morphisms to functions. (If the coercion doesn't fire automatically, sometimes it is
necessary to write `(f : X → Y) x`.)
In some fonts the `⟶` morphism arrow can be virtually indistinguishable from the standard function
arrow `→` . You may want to install the [Deja Vu Sans Mono](https://dejavu-fonts.github.io/) and put
that at the beginning of the `Font Family` setting in VSCode, to get a nice readable font with
excellent unicode coverage.
Another point of confusion can be universe issues. Following Lean's conventions for universe
polymorphism, the objects of a category might live in one universe `u` and the morphisms in another
universe `v`. Note that in many categories showing up in "set-theoretic mathematics", the morphisms
between two objects often form a set, but the objects themselves may or may not form a set. In Lean
this corresponds to the two possibilities `u=v` and `u=v+1`, known as `small_category` and
`large_category` respectively. In order to avoid proving the same statements for both small and
large categories, we usually stick to the general polymorphic situation with `u` and `v` independent
universes, and we do this below.
## Getting started with categories
The structure of a category on a type `C` in Lean is done using typeclasses; terms of `C` then
correspond to objects in the category. The convention in the category theory library is to use
universes prefixed with `u` (e.g. `u`, `u₁`, `u₂`) for the objects, and universes prefixed with `v`
for morphisms. Thus we have `C : Type u`, and if `X : C` and `Y : C` then morphisms `X ⟶ Y : Type v`
(note the non-standard arrow).
We set this up as follows:
-/
open category_theory
section category
variables (C : Type*) [category C]
variables {W X Y Z : C}
variables (f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z)
/-!
This says "let `C` be a category, let `W`, `X`, `Y`, `Z` be objects of `C`, and let `f : W ⟶ X`, `g
: X ⟶ Y` and `h : Y ⟶ Z` be morphisms in `C` (with the specified source and targets)".
Note that we sometimes need to explicitly tell Lean the universe that the morphisms live in,
by writing `category.{v} C`, because Lean cannot guess this from `C` alone.
However just writing `category C` is often fine: this allows a "free" universe level.
The order in which universes are introduced at the top of the file matters:
we put the universes for morphisms first (typically `v`, `v₁` and so on),
and then universes for objects (typically `u`, `u₁` and so on).
This ensures that in any new definition we make the universe variables for morphisms come first,
so that they can be explicitly specified while still allowing the universe levels of the
objects to be inferred automatically.
## Basic notation
In categories one has morphisms between objects, such as the identity morphism from an object to
itself. One can compose morphisms, and there are standard facts about the composition of a morphism
with the identity morphism, and the fact that morphism composition is associative. In Lean all of
this looks like the following:
-/
-- The identity morphism from `X` to `X` (remember that this is the `\h` arrow):
example : X ⟶ X := 𝟙 X -- type `𝟙` as `\bb1`
-- Function composition `h ∘ g`, a morphism from `X` to `Z`:
example : X ⟶ Z := g ≫ h
/-
Note in particular the order! The "maps on the right" convention was chosen; `g ≫ h` means "`g` then
`h`". Type `≫` with `\gg` in VS Code. Here are the theorems which ensure that we have a category.
-/
open category_theory.category
example : 𝟙 X ≫ g = g := id_comp g
example : g ≫ 𝟙 Y = g := comp_id g
example : (f ≫ g) ≫ h = f ≫ (g ≫ h) := assoc f g h
example : (f ≫ g) ≫ h = f ≫ g ≫ h := assoc f g h -- note \gg is right associative
-- All four examples above can also be proved with `simp`.
-- Monomorphisms and epimorphisms are predicates on morphisms and are implemented as typeclasses.
variables (f' : W ⟶ X) (h' : Y ⟶ Z)
example [mono g] : f ≫ g = f' ≫ g → f = f' := mono.right_cancellation f f'
example [epi g] : g ≫ h = g ≫ h' → h = h' := epi.left_cancellation h h'
end category -- end of section
/-!
## Getting started with functors
A functor is a map between categories. It is implemented as a structure. The notation for a functor
from `C` to `D` is `C ⥤ D`. Type `\func` in VS Code for the symbol. Here we demonstrate how to
evaluate functors on objects and on morphisms, how to show functors preserve the identity morphism
and composition of morphisms, how to compose functors, and show the notation `𝟭` for the identity
functor.
-/
section functor
variables (C : Type*) [category C]
variables (D : Type*) [category D]
variables (E : Type*) [category E]
variables {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
-- functors
variables (F : C ⥤ D) (G : D ⥤ E)
example : D := F.obj X -- functor F on objects
example : F.obj Y ⟶ F.obj Z := F.map g -- functor F on morphisms
-- A functor sends identity objects to identity objects
example : F.map (𝟙 X) = 𝟙 (F.obj X) := F.map_id X
-- and preserves compositions
example : F.map (f ≫ g) = (F.map f) ≫ (F.map g) := F.map_comp f g
-- The identity functor is `𝟭`, which you can write as `\sb1`.
example : C ⥤ C := 𝟭 C
-- The identity functor is (definitionally) the identity on objects and morphisms:
example : (𝟭 C).obj X = X := category_theory.functor.id_obj X
example : (𝟭 C).map f = f := category_theory.functor.id_map f
-- Composition of functors; note order:
example : C ⥤ E := F ⋙ G -- typeset with `\ggg`
-- Composition of the identity either way does nothing:
example : F ⋙ 𝟭 D = F := F.comp_id
example : 𝟭 C ⋙ F = F := F.id_comp
-- Composition of functors definitionally does the right thing on objects and morphisms:
example : (F ⋙ G).obj X = G.obj (F.obj X) := F.comp_obj G X -- or rfl
example : (F ⋙ G).map f = G.map (F.map f) := rfl -- or F.comp_map G X Y f
end functor -- end of section
/-!
One can also check that associativity of composition of functors is definitionally true,
although we've observed that relying on this can result in slow proofs. (One should
rather use the natural isomorphisms provided in `src/category_theory/whiskering.lean`.)
## Getting started with natural transformations
A natural transformation is a morphism between functors. If `F` and `G` are functors from `C` to `D`
then a natural transformation is a map `F X ⟶ G X` for each object `X : C` plus the theorem that if
`f : X ⟶ Y` is a morphism then the two routes from `F X` to `G Y` are the same. One might imagine
that this is now another layer of notation, but fortunately the `category_theory.functor_category`
import gives the type of functors from `C` to `D` a category structure, which means that we can just
use morphism notation for natural transformations.
-/
section nat_trans
variables {C : Type*} [category C] {D : Type*} [category D]
variables (X Y : C)
variable (f : X ⟶ Y)
variables (F G H : C ⥤ D)
variables (α : F ⟶ G) (β : G ⟶ H) -- natural transformations (note it's the usual `\hom` arrow here)
-- Composition of natural transformations is just composition of morphisms:
example : F ⟶ H := α ≫ β
-- Applying natural transformation to an object:
example (X : C) : F.obj X ⟶ G.obj X := α.app X
/- The diagram coming from g and α
F(f)
F X ---> F Y
| |
|α(X) |α(Y)
v v
G X ---> G Y
G(f)
commutes.
-/
example : F.map f ≫ α.app Y = (α.app X) ≫ G.map f := α.naturality f
end nat_trans -- section
/-!
## What next?
There are several lean files in the [category theory docs directory of
mathlib](https://github.com/leanprover-community/mathlib/tree/master/docs/tutorial/category_theory)
which give further examples of using the category theory library in Lean.
-/
|
c8d7e959e038fb8bca49273d206c7a1fddc56327 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/smart_unfolding.lean | 58ab4ef7b6aa448745e9bcc57b105c3eb585bc4c | [
"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 | 114 | lean | constant n : nat
#reduce n + (nat.succ n)
set_option type_context.smart_unfolding false
#reduce n + (nat.succ n)
|
ea31c1f4efb087f81ab1594fed7e8d7692f0658e | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/run/num.lean | 663bca263c54695872b4c8ea016e9125449ca135 | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 51 | lean | import num
check 14
check 0
check 3
check 2
check 4 |
21d20eed9959b58e38144fe55d56c7cfda303a19 | ecad13897fdb44984cf1968424224d1750040236 | /lean/lean/examples/example04.lean | 5b367fdc43efb9350e0f45df3b0a3cb4a20a2df7 | [] | no_license | MetaBorgCube/sdf3-demo | 4899159b1cfb0a95ae3af325035bbba8a1255477 | e831606d5b404eba75b087916a1162923143b98a | refs/heads/master | 1,609,472,086,310 | 1,553,380,857,000 | 1,553,380,857,000 | 59,577,395 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 69 | lean | (a : b)(c : d)(e : f) -> e
=>
(a : b) -> (c : d) -> (e : f) -> e
|
9db6be38a99239d2cd7113f26447b3aafa6fa9c3 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/matrix/charpoly/coeff.lean | 834300d00a30bc850c8f1141b23561f7ad6b7351 | [
"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 | 8,917 | lean | /-
Copyright (c) 2020 Aaron Anderson, Jalex Stark. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson, Jalex Stark
-/
import data.polynomial.expand
import linear_algebra.matrix.charpoly.basic
/-!
# Characteristic polynomials
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We give methods for computing coefficients of the characteristic polynomial.
## Main definitions
- `matrix.charpoly_degree_eq_dim` proves that the degree of the characteristic polynomial
over a nonzero ring is the dimension of the matrix
- `matrix.det_eq_sign_charpoly_coeff` proves that the determinant is the constant term of the
characteristic polynomial, up to sign.
- `matrix.trace_eq_neg_charpoly_coeff` proves that the trace is the negative of the (d-1)th
coefficient of the characteristic polynomial, where d is the dimension of the matrix.
For a nonzero ring, this is the second-highest coefficient.
-/
noncomputable theory
universes u v w z
open polynomial matrix
open_locale big_operators polynomial
variables {R : Type u} [comm_ring R]
variables {n G : Type v} [decidable_eq n] [fintype n]
variables {α β : Type v} [decidable_eq α]
open finset
variable {M : matrix n n R}
lemma charmatrix_apply_nat_degree [nontrivial R] (i j : n) :
(charmatrix M i j).nat_degree = ite (i = j) 1 0 :=
by { by_cases i = j; simp [h, ← degree_eq_iff_nat_degree_eq_of_pos (nat.succ_pos 0)], }
lemma charmatrix_apply_nat_degree_le (i j : n) :
(charmatrix M i j).nat_degree ≤ ite (i = j) 1 0 :=
by split_ifs; simp [h, nat_degree_X_sub_C_le]
namespace matrix
variable (M)
lemma charpoly_sub_diagonal_degree_lt :
(M.charpoly - ∏ (i : n), (X - C (M i i))).degree < ↑(fintype.card n - 1) :=
begin
rw [charpoly, det_apply', ← insert_erase (mem_univ (equiv.refl n)),
sum_insert (not_mem_erase (equiv.refl n) univ), add_comm],
simp only [charmatrix_apply_eq, one_mul, equiv.perm.sign_refl, id.def, int.cast_one,
units.coe_one, add_sub_cancel, equiv.coe_refl],
rw ← mem_degree_lt, apply submodule.sum_mem (degree_lt R (fintype.card n - 1)),
intros c hc, rw [← C_eq_int_cast, C_mul'],
apply submodule.smul_mem (degree_lt R (fintype.card n - 1)) ↑↑(equiv.perm.sign c),
rw mem_degree_lt, apply lt_of_le_of_lt degree_le_nat_degree _, rw with_bot.coe_lt_coe,
apply lt_of_le_of_lt _ (equiv.perm.fixed_point_card_lt_of_ne_one (ne_of_mem_erase hc)),
apply le_trans (polynomial.nat_degree_prod_le univ (λ i : n, (charmatrix M (c i) i))) _,
rw card_eq_sum_ones, rw sum_filter, apply sum_le_sum,
intros, apply charmatrix_apply_nat_degree_le,
end
lemma charpoly_coeff_eq_prod_coeff_of_le {k : ℕ} (h : fintype.card n - 1 ≤ k) :
M.charpoly.coeff k = (∏ i : n, (X - C (M i i))).coeff k :=
begin
apply eq_of_sub_eq_zero, rw ← coeff_sub, apply polynomial.coeff_eq_zero_of_degree_lt,
apply lt_of_lt_of_le (charpoly_sub_diagonal_degree_lt M) _, rw with_bot.coe_le_coe, apply h,
end
lemma det_of_card_zero (h : fintype.card n = 0) (M : matrix n n R) : M.det = 1 :=
by { rw fintype.card_eq_zero_iff at h, suffices : M = 1, { simp [this] }, ext i, exact h.elim i }
theorem charpoly_degree_eq_dim [nontrivial R] (M : matrix n n R) :
M.charpoly.degree = fintype.card n :=
begin
by_cases fintype.card n = 0,
{ rw h, unfold charpoly, rw det_of_card_zero, {simp}, {assumption} },
rw ← sub_add_cancel M.charpoly (∏ (i : n), (X - C (M i i))),
have h1 : (∏ (i : n), (X - C (M i i))).degree = fintype.card n,
{ rw degree_eq_iff_nat_degree_eq_of_pos, swap, apply nat.pos_of_ne_zero h,
rw nat_degree_prod', simp_rw nat_degree_X_sub_C, unfold fintype.card, simp,
simp_rw (monic_X_sub_C _).leading_coeff, simp, },
rw degree_add_eq_right_of_degree_lt, exact h1, rw h1,
apply lt_trans (charpoly_sub_diagonal_degree_lt M), rw with_bot.coe_lt_coe,
rw ← nat.pred_eq_sub_one, apply nat.pred_lt, apply h,
end
theorem charpoly_nat_degree_eq_dim [nontrivial R] (M : matrix n n R) :
M.charpoly.nat_degree = fintype.card n :=
nat_degree_eq_of_degree_eq_some (charpoly_degree_eq_dim M)
lemma charpoly_monic (M : matrix n n R) : M.charpoly.monic :=
begin
nontriviality,
by_cases fintype.card n = 0, {rw [charpoly, det_of_card_zero h], apply monic_one},
have mon : (∏ (i : n), (X - C (M i i))).monic,
{ apply monic_prod_of_monic univ (λ i : n, (X - C (M i i))), simp [monic_X_sub_C], },
rw ← sub_add_cancel (∏ (i : n), (X - C (M i i))) M.charpoly at mon,
rw monic at *, rw leading_coeff_add_of_degree_lt at mon, rw ← mon,
rw charpoly_degree_eq_dim, rw ← neg_sub, rw degree_neg,
apply lt_trans (charpoly_sub_diagonal_degree_lt M), rw with_bot.coe_lt_coe,
rw ← nat.pred_eq_sub_one, apply nat.pred_lt, apply h,
end
theorem trace_eq_neg_charpoly_coeff [nonempty n] (M : matrix n n R) :
trace M = -M.charpoly.coeff (fintype.card n - 1) :=
begin
rw charpoly_coeff_eq_prod_coeff_of_le, swap, refl,
rw [fintype.card, prod_X_sub_C_coeff_card_pred univ (λ i : n, M i i) fintype.card_pos, neg_neg,
trace],
refl
end
-- I feel like this should use polynomial.alg_hom_eval₂_algebra_map
lemma mat_poly_equiv_eval (M : matrix n n R[X]) (r : R) (i j : n) :
(mat_poly_equiv M).eval ((scalar n) r) i j = (M i j).eval r :=
begin
unfold polynomial.eval, unfold eval₂,
transitivity polynomial.sum (mat_poly_equiv M) (λ (e : ℕ) (a : matrix n n R),
(a * (scalar n) r ^ e) i j),
{ unfold polynomial.sum, rw sum_apply, dsimp, refl },
{ simp_rw [←ring_hom.map_pow, ←(scalar.commute _ _).eq],
simp only [coe_scalar, matrix.one_mul, ring_hom.id_apply,
pi.smul_apply, smul_eq_mul, mul_eq_mul, algebra.smul_mul_assoc],
have h : ∀ x : ℕ, (λ (e : ℕ) (a : R), r ^ e * a) x 0 = 0 := by simp,
simp only [polynomial.sum, mat_poly_equiv_coeff_apply, mul_comm],
apply (finset.sum_subset (support_subset_support_mat_poly_equiv _ _ _) _).symm,
assume n hn h'n,
rw not_mem_support_iff at h'n,
simp only [h'n, zero_mul] }
end
lemma eval_det (M : matrix n n R[X]) (r : R) :
polynomial.eval r M.det = (polynomial.eval (scalar n r) (mat_poly_equiv M)).det :=
begin
rw [polynomial.eval, ← coe_eval₂_ring_hom, ring_hom.map_det],
apply congr_arg det, ext, symmetry, convert mat_poly_equiv_eval _ _ _ _,
end
theorem det_eq_sign_charpoly_coeff (M : matrix n n R) :
M.det = (-1)^(fintype.card n) * M.charpoly.coeff 0:=
begin
rw [coeff_zero_eq_eval_zero, charpoly, eval_det, mat_poly_equiv_charmatrix, ← det_smul],
simp
end
end matrix
variables {p : ℕ} [fact p.prime]
lemma mat_poly_equiv_eq_X_pow_sub_C {K : Type*} (k : ℕ) [field K] (M : matrix n n K) :
mat_poly_equiv
((expand K (k) : K[X] →+* K[X]).map_matrix (charmatrix (M ^ k))) =
X ^ k - C (M ^ k) :=
begin
ext m,
rw [coeff_sub, coeff_C, mat_poly_equiv_coeff_apply, ring_hom.map_matrix_apply, matrix.map_apply,
alg_hom.coe_to_ring_hom, dmatrix.sub_apply, coeff_X_pow],
by_cases hij : i = j,
{ rw [hij, charmatrix_apply_eq, alg_hom.map_sub, expand_C, expand_X, coeff_sub, coeff_X_pow,
coeff_C],
split_ifs with mp m0;
simp only [matrix.one_apply_eq, dmatrix.zero_apply] },
{ rw [charmatrix_apply_ne _ _ _ hij, alg_hom.map_neg, expand_C, coeff_neg, coeff_C],
split_ifs with m0 mp;
simp only [hij, zero_sub, dmatrix.zero_apply, sub_zero, neg_zero, matrix.one_apply_ne, ne.def,
not_false_iff] }
end
namespace matrix
/-- Any matrix polynomial `p` is equivalent under evaluation to `p %ₘ M.charpoly`; that is, `p`
is equivalent to a polynomial with degree less than the dimension of the matrix. -/
lemma aeval_eq_aeval_mod_charpoly (M : matrix n n R) (p : R[X]) :
aeval M p = aeval M (p %ₘ M.charpoly) :=
(aeval_mod_by_monic_eq_self_of_root M.charpoly_monic M.aeval_self_charpoly).symm
/-- Any matrix power can be computed as the sum of matrix powers less than `fintype.card n`.
TODO: add the statement for negative powers phrased with `zpow`. -/
lemma pow_eq_aeval_mod_charpoly (M : matrix n n R) (k : ℕ) : M^k = aeval M (X^k %ₘ M.charpoly) :=
by rw [←aeval_eq_aeval_mod_charpoly, map_pow, aeval_X]
end matrix
section ideal
lemma coeff_charpoly_mem_ideal_pow {I : ideal R} (h : ∀ i j, M i j ∈ I) (k : ℕ) :
M.charpoly.coeff k ∈ I ^ (fintype.card n - k) :=
begin
delta charpoly,
rw [matrix.det_apply, finset_sum_coeff],
apply sum_mem,
rintro c -,
rw [coeff_smul, submodule.smul_mem_iff'],
have : ∑ (x : n), 1 = fintype.card n := by rw [finset.sum_const, card_univ, smul_eq_mul, mul_one],
rw ← this,
apply coeff_prod_mem_ideal_pow_tsub,
rintro i - (_|k),
{ rw [tsub_zero, pow_one, charmatrix_apply, coeff_sub, coeff_X_mul_zero, coeff_C_zero, zero_sub,
neg_mem_iff],
exact h (c i) i },
{ rw [nat.succ_eq_one_add, tsub_self_add, pow_zero, ideal.one_eq_top],
exact submodule.mem_top }
end
end ideal
|
e4244d8707a1eef1f3eaa4645880a43f01476348 | f4bff2062c030df03d65e8b69c88f79b63a359d8 | /src/game/sets/sets_level01.lean | 7c1f707a17fa87bf8cea1e34e420c746d4360e86 | [
"Apache-2.0"
] | permissive | adastra7470/real-number-game | 776606961f52db0eb824555ed2f8e16f92216ea3 | f9dcb7d9255a79b57e62038228a23346c2dc301b | refs/heads/master | 1,669,221,575,893 | 1,594,669,800,000 | 1,594,669,800,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,227 | lean | import data.set.basic -- hide
import kb_defs -- hide
namespace xena -- hide
open_locale classical -- hide
variable X : Type -- we will think of X as a set here
/-
# Chapter 1 : Sets
## Level 1 : Introduction to sets.
This chapter assumes you are familiar with the following tactics:
`rw`, `intro`, `apply`, `exact`, `cases`, `split`, `use`, `left`, `right` and `exfalso`.
(TODO (kmb) : check this list is exhaustive)
(We might need to add `ring`)
If you are not, try playing Function World and Proposition World of the Natural Number Game.
## Sets in Lean
In this world, there will be an ambient "big" set `X` (actually `X` will be a type),
and we will consider subsets of `X`. The type of subsets of `X` is called `set X`.
So if you see `A : set X` it means that `A` is a subset of `X`.
## subsets (⊆) and `subset_iff`
If `A B : set X` (i.e. `A` and `B` are subsets of `X`), then `A ⊆ B` is a
Proposition, i.e. a true/false statement. Lean knows the following fact:
```
subset_iff : A ⊆ B ↔ ∀ x : X, x ∈ A → x ∈ B
```
Let's see if you can prove `A ⊆ A` by rewriting `subset_iff`.
-/
/- Axiom : subset_iff :
A ⊆ B ↔ ∀ x : X, x ∈ A → x ∈ B
-/
/- Hint : Tactic tip
The `assumption` tactic will close a goal if it is equal to one of your
hypotheses. It's actually longer to type than `exact hx`, but it's easier to
use because you don't have to bother remembering what you called `hx`.
-/
/- Hint : Stuck? Here's a hint.
To make progress with a goal of form `∀ a : X, ...`, introduce a term of type `X` by using a familiar tactic.
In this example, using
`intro a,`
will introduce an arbitrary term of type `X`.
Note that this is the tactic we use to assume a hypothesis (when proving an implication), or to choose an arbitrary element of some domain (when defining a function).
Use the same tactic to introduce an appropriately named hypothesis for an implication, and close the goal with the `exact` tactic.
-/
/-
If you get stuck, you can click on the hints for more details!
-/
/- Lemma
If $A$ is a set of elements of type X, then $A \subseteq A$.
-/
lemma subset.refl (A : set X) : A ⊆ A :=
begin
rw subset_iff,
intros x h,
exact h
end
end xena --hide
|
49ac18146290d61b5bf01f7a218c9543cba707aa | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/tactic/tidy.lean | cd2062af3d38d5e32f5dadc8e68fc8d09ddac32f | [
"Apache-2.0"
] | permissive | vaibhavkarve/mathlib | a574aaf68c0a431a47fa82ce0637f0f769826bfe | 17f8340912468f49bdc30acdb9a9fa02eeb0473a | refs/heads/master | 1,621,263,802,637 | 1,585,399,588,000 | 1,585,399,588,000 | 250,833,447 | 0 | 0 | Apache-2.0 | 1,585,410,341,000 | 1,585,410,341,000 | null | UTF-8 | Lean | false | false | 4,466 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import tactic.ext
import tactic.auto_cases
import tactic.chain
import tactic.solve_by_elim
import tactic.norm_cast
import tactic.hint
import tactic.interactive
namespace tactic
namespace tidy
/-- Tag interactive tactics (locally) with `[tidy]` to add them to the list of default tactics
called by `tidy`. -/
meta def tidy_attribute : user_attribute := {
name := `tidy,
descr := "A tactic that should be called by `tidy`."
}
add_tactic_doc
{ name := "tidy",
category := doc_category.attr,
decl_names := [`tactic.tidy.tidy_attribute],
tags := ["search"] }
run_cmd attribute.register ``tidy_attribute
meta def run_tactics : tactic string :=
do names ← attribute.get_instances `tidy,
first (names.map name_to_tactic) <|> fail "no @[tidy] tactics succeeded"
@[hint_tactic]
meta def ext1_wrapper : tactic string :=
do ng ← num_goals,
ext1 [] {apply_cfg . new_goals := new_goals.all},
ng' ← num_goals,
return $ if ng' > ng then
"tactic.ext1 [] {new_goals := tactic.new_goals.all}"
else "ext1"
meta def default_tactics : list (tactic string) :=
[ reflexivity >> pure "refl",
`[exact dec_trivial] >> pure "exact dec_trivial",
propositional_goal >> assumption >> pure "assumption",
intros1 >>= λ ns, pure ("intros " ++ (" ".intercalate (ns.map (λ e, e.to_string)))),
auto_cases,
`[apply_auto_param] >> pure "apply_auto_param",
`[dsimp at *] >> pure "dsimp at *",
`[simp at *] >> pure "simp at *",
ext1_wrapper,
fsplit >> pure "fsplit",
injections_and_clear >> pure "injections_and_clear",
propositional_goal >> (`[solve_by_elim]) >> pure "solve_by_elim",
`[norm_cast] >> pure "norm_cast",
`[unfold_coes] >> pure "unfold_coes",
`[unfold_aux] >> pure "unfold_aux",
tidy.run_tactics ]
meta structure cfg :=
(trace_result : bool := ff)
(trace_result_prefix : string := "Try this: ")
(tactics : list (tactic string) := default_tactics)
declare_trace tidy
meta def core (cfg : cfg := {}) : tactic (list string) :=
do
results ← chain cfg.tactics,
when (cfg.trace_result ∨ is_trace_enabled_for `tidy) $
trace (cfg.trace_result_prefix ++ (", ".intercalate results)),
return results
end tidy
meta def tidy (cfg : tidy.cfg := {}) := tactic.tidy.core cfg >> skip
namespace interactive
open lean.parser interactive
/-- Use a variety of conservative tactics to solve goals.
`tidy?` reports back the tactic script it found. As an example
```lean
example : ∀ x : unit, x = unit.star :=
begin
tidy? -- Prints the trace message: "Try this: intros x, exact dec_trivial"
end
```
The default list of tactics is stored in `tactic.tidy.default_tidy_tactics`.
This list can be overridden using `tidy { tactics := ... }`.
(The list must be a `list` of `tactic string`, so that `tidy?`
can report a usable tactic script.)
Tactics can also be added to the list by tagging them (locally) with the
`[tidy]` attribute. -/
meta def tidy (trace : parse $ optional (tk "?")) (cfg : tidy.cfg := {}) :=
tactic.tidy { trace_result := trace.is_some, ..cfg }
end interactive
add_tactic_doc
{ name := "tidy",
category := doc_category.tactic,
decl_names := [`tactic.interactive.tidy],
tags := ["search", "Try this", "finishing"] }
/-- Invoking the hole command `tidy` ("Use `tidy` to complete the goal") runs the tactic of
the same name, replacing the hole with the tactic script `tidy` produces.
-/
@[hole_command] meta def tidy_hole_cmd : hole_command :=
{ name := "tidy",
descr := "Use `tidy` to complete the goal.",
action := λ _, do script ← tidy.core,
return [("begin " ++ (", ".intercalate script) ++ " end", "by tidy")] }
add_tactic_doc
{ name := "tidy",
category := doc_category.hole_cmd,
decl_names := [`tactic.tidy_hole_cmd],
tags := ["search"] }
end tactic
|
1ce84d14136df178dbdd23fc6398b3859a522ec0 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /archive/100-theorems-list/82_cubing_a_cube.lean | 55e82c52df8ff6d513cb9b1c53ae6e223c18b90c | [
"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 | 23,609 | 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 data.real.basic
import data.set.disjointed
import data.set.intervals
import set_theory.cardinal
/-!
Proof that a cube (in dimension n ≥ 3) cannot be cubed:
There does not exist a partition of a cube into finitely many smaller cubes (at least two)
of different sizes.
We follow the proof described here:
http://www.alaricstephen.com/main-featured/2017/9/28/cubing-a-cube-proof
-/
open real set function fin
noncomputable theory
variable {n : ℕ}
/-- Given three intervals `I, J, K` such that `J ⊂ I`,
neither endpoint of `J` coincides with an endpoint of `I`, `¬ (K ⊆ J)` and
`K` does not lie completely to the left nor completely to the right of `J`.
Then `I ∩ K \ J` is nonempty. -/
lemma Ico_lemma {α} [linear_order α] {x₁ x₂ y₁ y₂ z₁ z₂ w : α}
(h₁ : x₁ < y₁) (hy : y₁ < y₂) (h₂ : y₂ < x₂)
(hz₁ : z₁ ≤ y₂) (hz₂ : y₁ ≤ z₂) (hw : w ∉ Ico y₁ y₂ ∧ w ∈ Ico z₁ z₂) :
∃w, w ∈ Ico x₁ x₂ ∧ w ∉ Ico y₁ y₂ ∧ w ∈ Ico z₁ z₂ :=
begin
simp only [not_and, not_lt, mem_Ico] at hw,
refine ⟨max x₁ (min w y₂), _, _, _⟩,
{ simp [le_refl, lt_trans h₁ (lt_trans hy h₂), h₂] },
{ simp [hw, lt_irrefl, not_le_of_lt h₁] {contextual := tt} },
{ simp [hw.2.1, hw.2.2, hz₁, lt_of_lt_of_le h₁ hz₂] at ⊢ }
end
/-- A (hyper)-cube (in standard orientation) is a vector `b` consisting of the bottom-left point
of the cube, a width `w` and a proof that `w > 0`. We use functions from `fin n` to denote vectors.
-/
structure cube (n : ℕ) : Type :=
(b : fin n → ℝ) -- bottom-left coordinate
(w : ℝ) -- width
(hw : 0 < w)
namespace cube
lemma hw' (c : cube n) : 0 ≤ c.w := le_of_lt c.hw
/-- The j-th side of a cube is the half-open interval `[b j, b j + w)` -/
def side (c : cube n) (j : fin n) : set ℝ :=
Ico (c.b j) (c.b j + c.w)
@[simp] lemma b_mem_side (c : cube n) (j : fin n) : c.b j ∈ c.side j :=
by simp [side, cube.hw, le_refl]
def to_set (c : cube n) : set (fin n → ℝ) :=
{ x | ∀j, x j ∈ side c j }
def to_set_subset {c c' : cube n} : c.to_set ⊆ c'.to_set ↔ ∀j, c.side j ⊆ c'.side j :=
begin
split, intros h j x hx,
let f : fin n → ℝ := λ j', if j' = j then x else c.b j',
have : f ∈ c.to_set,
{ intro j', by_cases hj' : j' = j; simp [f, hj', if_pos, if_neg, hx] },
convert h this j, { simp [f, if_pos] },
intros h f hf j, exact h j (hf j)
end
def to_set_disjoint {c c' : cube n} : disjoint c.to_set c'.to_set ↔
∃j, disjoint (c.side j) (c'.side j) :=
begin
split, intros h, classical, by_contra h',
simp only [not_disjoint_iff, classical.skolem, not_exists] at h',
cases h' with f hf,
apply not_disjoint_iff.mpr ⟨f, _, _⟩ h; intro j, exact (hf j).1, exact (hf j).2,
rintro ⟨j, hj⟩, rw [set.disjoint_iff], rintros f ⟨h1f, h2f⟩,
apply not_disjoint_iff.mpr ⟨f j, h1f j, h2f j⟩ hj
end
lemma b_mem_to_set (c : cube n) : c.b ∈ c.to_set :=
by simp [to_set]
protected def tail (c : cube (n+1)) : cube n :=
⟨tail c.b, c.w, c.hw⟩
lemma side_tail (c : cube (n+1)) (j : fin n) : c.tail.side j = c.side j.succ := rfl
def bottom (c : cube (n+1)) : set (fin (n+1) → ℝ) :=
{ x | x 0 = c.b 0 ∧ tail x ∈ c.tail.to_set }
lemma b_mem_bottom (c : cube (n+1)) : c.b ∈ c.bottom :=
by simp [bottom, to_set, side, cube.hw, le_refl, cube.tail]
def xm (c : cube (n+1)) : ℝ :=
c.b 0 + c.w
lemma b_lt_xm (c : cube (n+1)) : c.b 0 < c.xm := by simp [xm, hw]
lemma b_ne_xm (c : cube (n+1)) : c.b 0 ≠ c.xm := ne_of_lt c.b_lt_xm
def shift_up (c : cube (n+1)) : cube (n+1) :=
⟨cons c.xm $ tail c.b, c.w, c.hw⟩
@[simp] lemma tail_shift_up (c : cube (n+1)) : c.shift_up.tail = c.tail :=
by simp [shift_up, cube.tail]
@[simp] lemma head_shift_up (c : cube (n+1)) : c.shift_up.b 0 = c.xm := rfl
def unit_cube : cube n :=
⟨λ _, 0, 1, by norm_num⟩
@[simp] lemma side_unit_cube {j : fin n} : unit_cube.side j = Ico 0 1 :=
by norm_num [unit_cube, side]
end cube
open cube
variables {ι : Type} [fintype ι] {cs : ι → cube (n+1)} {i i' : ι}
/-- A finite family of (at least 2) cubes partitioning the unit cube with different sizes -/
def correct (cs : ι → cube n) : Prop :=
pairwise (disjoint on (cube.to_set ∘ cs)) ∧
(⋃(i : ι), (cs i).to_set) = unit_cube.to_set ∧
injective (cube.w ∘ cs) ∧
2 ≤ cardinal.mk ι ∧
3 ≤ n
variable (h : correct cs)
include h
lemma to_set_subset_unit_cube {i} : (cs i).to_set ⊆ unit_cube.to_set :=
by { rw [←h.2.1], exact subset_Union _ i }
lemma side_subset {i j} : (cs i).side j ⊆ Ico 0 1 :=
by { have := to_set_subset_unit_cube h, rw [to_set_subset] at this,
convert this j, norm_num [unit_cube] }
lemma zero_le_of_mem_side {i j x} (hx : x ∈ (cs i).side j) : 0 ≤ x :=
(side_subset h hx).1
lemma zero_le_of_mem {i p} (hp : p ∈ (cs i).to_set) (j) : 0 ≤ p j :=
zero_le_of_mem_side h (hp j)
lemma zero_le_b {i j} : 0 ≤ (cs i).b j :=
zero_le_of_mem h (cs i).b_mem_to_set j
lemma b_add_w_le_one {j} : (cs i).b j + (cs i).w ≤ 1 :=
by { have := side_subset h, rw [side, Ico_subset_Ico_iff] at this, convert this.2, simp [hw] }
/-- The width of any cube in the partition cannot be 1. -/
lemma w_ne_one (i : ι) : (cs i).w ≠ 1 :=
begin
intro hi,
have := h.2.2.2.1, rw [cardinal.two_le_iff' i] at this, cases this with i' hi',
let p := (cs i').b,
have hp : p ∈ (cs i').to_set := (cs i').b_mem_to_set,
have h2p : p ∈ (cs i).to_set,
{ intro j, split,
transitivity (0 : ℝ),
{ rw [←add_le_add_iff_right (1 : ℝ)], convert b_add_w_le_one h, rw hi, rw zero_add },
apply zero_le_b h, apply lt_of_lt_of_le (side_subset h $ (cs i').b_mem_side j).2,
simp [hi, zero_le_b h] },
apply not_disjoint_iff.mpr ⟨p, hp, h2p⟩,
apply h.1, exact hi'.symm
end
/-- The top of a cube (which is the bottom of the cube shifted up by its width) must be covered by
bottoms of (other) cubes in the family. -/
lemma shift_up_bottom_subset_bottoms (hc : (cs i).xm ≠ 1) :
(cs i).shift_up.bottom ⊆ ⋃(i : ι), (cs i).bottom :=
begin
intros p hp, cases hp with hp0 hps, rw [tail_shift_up] at hps,
have : p ∈ (unit_cube : cube (n+1)).to_set,
{ simp only [to_set, forall_fin_succ, hp0, side_unit_cube, mem_set_of_eq, mem_Ico,
head_shift_up], refine ⟨⟨_, _⟩, _⟩,
{ rw [←zero_add (0 : ℝ)], apply add_le_add, apply zero_le_b h, apply (cs i).hw' },
{ exact lt_of_le_of_ne (b_add_w_le_one h) hc },
intro j, exact side_subset h (hps j) },
rw [←h.2.1] at this, rcases this with ⟨_, ⟨i', rfl⟩, hi'⟩,
rw [mem_Union], use i', refine ⟨_, λ j, hi' j.succ⟩,
have : i ≠ i', { rintro rfl, apply not_le_of_lt (hi' 0).2, rw [hp0], refl },
have := h.1 i i' this, rw [on_fun, to_set_disjoint, exists_fin_succ] at this,
rcases this with h0|⟨j, hj⟩,
rw [hp0], symmetry, apply eq_of_Ico_disjoint h0 (by simp [hw]) _,
convert hi' 0, rw [hp0], refl,
exfalso, apply not_disjoint_iff.mpr ⟨tail p j, hps j, hi' j.succ⟩ hj
end
omit h
/-- A valley is a square on which cubes in the family of cubes are placed, so that the cubes
completely cover the valley and none of those cubes is partially outside the square.
We also require that no cube on it has the same size as the valley (so that there are at least
two cubes on the valley).
This is the main concept in the formalization.
We prove that the smallest cube on a valley has another valley on the top of it, which
gives an infinite sequence of cubes in the partition, which contradicts the finiteness.
A valley is characterized by a cube `c` (which is not a cube in the family cs) by considering
the bottom face of `c`. -/
def valley (cs : ι → cube (n+1)) (c : cube (n+1)) : Prop :=
c.bottom ⊆ (⋃(i : ι), (cs i).bottom) ∧
(∀i, (cs i).b 0 = c.b 0 → (∃x, x ∈ (cs i).tail.to_set ∩ c.tail.to_set) →
(cs i).tail.to_set ⊆ c.tail.to_set) ∧
∀(i : ι), (cs i).b 0 = c.b 0 → (cs i).w ≠ c.w
variables {c : cube (n+1)} (v : valley cs c)
/-- The bottom of the unit cube is a valley -/
lemma valley_unit_cube (h : correct cs) : valley cs unit_cube :=
begin
refine ⟨_, _, _⟩,
{ intro v,
simp only [bottom, and_imp, mem_Union, mem_set_of_eq],
intros h0 hv,
have : v ∈ (unit_cube : cube (n+1)).to_set,
{ dsimp only [to_set, unit_cube, mem_set_of_eq],
rw [forall_fin_succ, h0], split, norm_num [side, unit_cube], exact hv },
rw [←h.2.1] at this, rcases this with ⟨_, ⟨i, rfl⟩, hi⟩,
use i,
split, { apply le_antisymm, rw h0, exact zero_le_b h, exact (hi 0).1 },
intro j, exact hi _ },
{ intros i hi h', rw to_set_subset, intro j, convert side_subset h using 1, simp [side_tail] },
{ intros i hi, exact w_ne_one h i }
end
/-- the cubes which lie in the valley `c` -/
def bcubes (cs : ι → cube (n+1)) (c : cube (n+1)) : set ι :=
{ i : ι | (cs i).b 0 = c.b 0 ∧ (cs i).tail.to_set ⊆ c.tail.to_set }
/-- A cube which lies on the boundary of a valley in dimension `j` -/
def on_boundary (hi : i ∈ bcubes cs c) (j : fin n) : Prop :=
c.b j.succ = (cs i).b j.succ ∨ (cs i).b j.succ + (cs i).w = c.b j.succ + c.w
lemma tail_sub (hi : i ∈ bcubes cs c) : ∀j, (cs i).tail.side j ⊆ c.tail.side j :=
by { rw [←to_set_subset], exact hi.2 }
lemma bottom_mem_side (hi : i ∈ bcubes cs c) : c.b 0 ∈ (cs i).side 0 :=
by { convert b_mem_side (cs i) _ using 1, rw hi.1 }
lemma b_le_b (hi : i ∈ bcubes cs c) (j : fin n) : c.b j.succ ≤ (cs i).b j.succ :=
(tail_sub hi j $ b_mem_side _ _).1
lemma t_le_t (hi : i ∈ bcubes cs c) (j : fin n) :
(cs i).b j.succ + (cs i).w ≤ c.b j.succ + c.w :=
begin
have h' := tail_sub hi j, dsimp only [side] at h', rw [Ico_subset_Ico_iff] at h',
exact h'.2, simp [hw]
end
include h v
/-- Every cube in the valley must be smaller than it -/
lemma w_lt_w (hi : i ∈ bcubes cs c) : (cs i).w < c.w :=
begin
apply lt_of_le_of_ne _ (v.2.2 i hi.1),
have j : fin n := ⟨1, nat.le_of_succ_le_succ h.2.2.2.2⟩,
rw [←add_le_add_iff_left ((cs i).b j.succ)],
apply le_trans (t_le_t hi j), rw [add_le_add_iff_right], apply b_le_b hi,
end
open cardinal
/-- There are at least two cubes in a valley -/
lemma two_le_mk_bcubes : 2 ≤ cardinal.mk (bcubes cs c) :=
begin
rw [two_le_iff],
rcases v.1 c.b_mem_bottom with ⟨_, ⟨i, rfl⟩, hi⟩,
have h2i : i ∈ bcubes cs c :=
⟨hi.1.symm, v.2.1 i hi.1.symm ⟨tail c.b, hi.2, λ j, c.b_mem_side j.succ⟩⟩,
let j : fin (n+1) := ⟨2, h.2.2.2.2⟩,
have hj : 0 ≠ j := by { simp only [fin.ext_iff, ne.def], contradiction },
let p : fin (n+1) → ℝ := λ j', if j' = j then c.b j + (cs i).w else c.b j',
have hp : p ∈ c.bottom,
{ split, { simp only [bottom, p, if_neg hj] },
intro j', simp only [tail, side_tail],
by_cases hj' : j'.succ = j,
{ simp [p, -add_comm, if_pos, side, hj', hw', w_lt_w h v h2i] },
{ simp [p, -add_comm, if_neg hj'] }},
rcases v.1 hp with ⟨_, ⟨i', rfl⟩, hi'⟩,
have h2i' : i' ∈ bcubes cs c := ⟨hi'.1.symm, v.2.1 i' hi'.1.symm ⟨tail p, hi'.2, hp.2⟩⟩,
refine ⟨⟨i, h2i⟩, ⟨i', h2i'⟩, _⟩,
intro hii', cases congr_arg subtype.val hii',
apply not_le_of_lt (hi'.2 ⟨1, nat.le_of_succ_le_succ h.2.2.2.2⟩).2,
simp only [-add_comm, tail, cube.tail, p],
rw [if_pos, add_le_add_iff_right],
{ exact (hi.2 _).1 },
refl
end
/-- There is a cube in the valley -/
lemma nonempty_bcubes : (bcubes cs c).nonempty :=
begin
rw [←set.ne_empty_iff_nonempty], intro h', have := two_le_mk_bcubes h v, rw h' at this,
apply not_lt_of_le this, rw mk_emptyc, norm_cast, norm_num
end
/-- There is a smallest cube in the valley -/
lemma exists_mi : ∃(i : ι), i ∈ bcubes cs c ∧ ∀(i' ∈ bcubes cs c),
(cs i).w ≤ (cs i').w :=
by simpa
using (bcubes cs c).exists_min_image (λ i, (cs i).w) (finite.of_fintype _) (nonempty_bcubes h v)
/-- We let `mi` be the (index for the) smallest cube in the valley `c` -/
def mi : ι := classical.some $ exists_mi h v
variables {h v}
lemma mi_mem_bcubes : mi h v ∈ bcubes cs c :=
(classical.some_spec $ exists_mi h v).1
lemma mi_minimal (hi : i ∈ bcubes cs c) : (cs $ mi h v).w ≤ (cs i).w :=
(classical.some_spec $ exists_mi h v).2 i hi
lemma mi_strict_minimal (hii' : mi h v ≠ i) (hi : i ∈ bcubes cs c) :
(cs $ mi h v).w < (cs i).w :=
by { apply lt_of_le_of_ne (mi_minimal hi), apply h.2.2.1.ne, apply hii' }
/-- The top of `mi` cannot be 1, since there is a larger cube in the valley -/
lemma mi_xm_ne_one : (cs $ mi h v).xm ≠ 1 :=
begin
apply ne_of_lt, rcases (two_le_iff' _).mp (two_le_mk_bcubes h v) with ⟨⟨i, hi⟩, h2i⟩,
swap, exact ⟨mi h v, mi_mem_bcubes⟩,
apply lt_of_lt_of_le _ (b_add_w_le_one h), exact i, exact 0,
rw [xm, mi_mem_bcubes.1, hi.1, _root_.add_lt_add_iff_left],
apply mi_strict_minimal _ hi, intro h', apply h2i, rw subtype.ext_iff_val, exact h'
end
/-- If `mi` lies on the boundary of the valley in dimension j, then this lemma expresses that all
other cubes on the same boundary extend further from the boundary.
More precisely, there is a j-th coordinate `x : ℝ` in the valley, but not in `mi`,
such that every cube that shares a (particular) j-th coordinate with `mi` also contains j-th
coordinate `x` -/
lemma smallest_on_boundary {j} (bi : on_boundary (mi_mem_bcubes : mi h v ∈ _) j) :
∃(x : ℝ), x ∈ c.side j.succ \ (cs $ mi h v).side j.succ ∧
∀{{i'}} (hi' : i' ∈ bcubes cs c), i' ≠ mi h v →
(cs $ mi h v).b j.succ ∈ (cs i').side j.succ → x ∈ (cs i').side j.succ :=
begin
let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes,
cases bi,
{ refine ⟨(cs i).b j.succ + (cs i).w, ⟨_, _⟩, _⟩,
{ simp [side, bi, hw', w_lt_w h v hi] },
{ intro h', simpa [i, lt_irrefl] using h'.2 },
intros i' hi' i'_i h2i', split,
apply le_trans h2i'.1, { simp [hw'] },
apply lt_of_lt_of_le (add_lt_add_left (mi_strict_minimal i'_i.symm hi') _),
simp [bi.symm, b_le_b hi'] },
let s := bcubes cs c \ { i },
have hs : s.nonempty,
{ rcases (two_le_iff' (⟨i, hi⟩ : bcubes cs c)).mp (two_le_mk_bcubes h v) with ⟨⟨i', hi'⟩, h2i'⟩,
refine ⟨i', hi', _⟩, simp only [mem_singleton_iff], intro h, apply h2i', simp [h] },
rcases set.exists_min_image s (w ∘ cs) (finite.of_fintype _) hs with ⟨i', ⟨hi', h2i'⟩, h3i'⟩,
rw [mem_singleton_iff] at h2i',
let x := c.b j.succ + c.w - (cs i').w,
have hx : x < (cs i).b j.succ,
{ dsimp only [x], rw [←bi, add_sub_assoc, add_lt_iff_neg_left, sub_lt_zero],
apply mi_strict_minimal (ne.symm h2i') hi' },
refine ⟨x, ⟨_, _⟩, _⟩,
{ simp only [side, x, -add_comm, -add_assoc, neg_lt_zero, hw, add_lt_iff_neg_left, and_true,
mem_Ico, sub_eq_add_neg],
rw [add_assoc, le_add_iff_nonneg_right, ←sub_eq_add_neg, sub_nonneg],
apply le_of_lt (w_lt_w h v hi') },
{ simp only [side, not_and_distrib, not_lt, add_comm, not_le, mem_Ico], left, exact hx },
intros i'' hi'' h2i'' h3i'', split, swap, apply lt_trans hx h3i''.2,
simp only [x], rw [le_sub_iff_add_le],
refine le_trans _ (t_le_t hi'' j), rw [add_le_add_iff_left], apply h3i' i'' ⟨hi'', _⟩,
simp [mem_singleton, h2i'']
end
variables (h v)
/-- `mi` cannot lie on the boundary of the valley. Otherwise, the cube adjacent to it in the `j`-th
direction will intersect one of the neighbouring cubes on the same boundary as `mi`. -/
lemma mi_not_on_boundary (j : fin n) : ¬on_boundary (mi_mem_bcubes : mi h v ∈ _) j :=
begin
let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes,
rcases (two_le_iff' j).mp _ with ⟨j', hj'⟩, swap,
{ rw [mk_fin, ←nat.cast_two, nat_cast_le], apply nat.le_of_succ_le_succ h.2.2.2.2 },
intro hj,
rcases smallest_on_boundary hj with ⟨x, ⟨hx, h2x⟩, h3x⟩,
let p : fin (n+1) → ℝ := cons (c.b 0) (λ j₂, if j₂ = j then x else (cs i).b j₂.succ),
have hp : p ∈ c.bottom,
{ suffices : ∀ (j' : fin n), ite (j' = j) x ((cs i).b j'.succ) ∈ c.side j'.succ,
{ simpa [bottom, p, to_set, tail, side_tail] },
intro j₂,
by_cases hj₂ : j₂ = j, { simp [hj₂, hx] },
simp only [hj₂, if_false], apply tail_sub hi, apply b_mem_side },
rcases v.1 hp with ⟨_, ⟨i', rfl⟩, hi'⟩,
have h2i' : i' ∈ bcubes cs c := ⟨hi'.1.symm, v.2.1 i' hi'.1.symm ⟨tail p, hi'.2, hp.2⟩⟩,
have i_i' : i ≠ i', { rintro rfl, simpa [p, side_tail, i, h2x] using hi'.2 j },
have : nonempty ↥((cs i').tail.side j' \ (cs i).tail.side j'),
{ apply nonempty_Ico_sdiff, apply mi_strict_minimal i_i' h2i', apply hw },
rcases this with ⟨⟨x', hx'⟩⟩,
let p' : fin (n+1) → ℝ :=
cons (c.b 0) (λ j₂, if j₂ = j' then x' else (cs i).b j₂.succ),
have hp' : p' ∈ c.bottom,
{ suffices : ∀ (j : fin n), ite (j = j') x' ((cs i).b j.succ) ∈ c.side j.succ,
{ simpa [bottom, p', to_set, tail, side_tail] },
intro j₂,
by_cases hj₂ : j₂ = j', simp [hj₂], apply tail_sub h2i', apply hx'.1,
simp only [if_congr, if_false, hj₂], apply tail_sub hi, apply b_mem_side },
rcases v.1 hp' with ⟨_, ⟨i'', rfl⟩, hi''⟩,
have h2i'' : i'' ∈ bcubes cs c := ⟨hi''.1.symm, v.2.1 i'' hi''.1.symm ⟨tail p', hi''.2, hp'.2⟩⟩,
have i'_i'' : i' ≠ i'',
{ rintro ⟨⟩,
have : (cs i).b ∈ (cs i').to_set,
{ simp only [to_set, forall_fin_succ, hi.1, bottom_mem_side h2i', true_and, mem_set_of_eq],
intro j₂, by_cases hj₂ : j₂ = j,
{ simpa [side_tail, p', hj', hj₂] using hi''.2 j },
{ simpa [hj₂] using hi'.2 j₂ } },
apply not_disjoint_iff.mpr ⟨(cs i).b, (cs i).b_mem_to_set, this⟩ (h.1 i i' i_i') },
have i_i'' : i ≠ i'', { intro h, induction h, simpa [hx'.2] using hi''.2 j' },
apply not.elim _ (h.1 i' i'' i'_i''),
simp only [on_fun, to_set_disjoint, not_disjoint_iff, forall_fin_succ, not_exists, comp_app],
refine ⟨⟨c.b 0, bottom_mem_side h2i', bottom_mem_side h2i''⟩, _⟩,
intro j₂,
by_cases hj₂ : j₂ = j,
{ cases hj₂, refine ⟨x, _, _⟩,
{ convert hi'.2 j, simp [p] },
apply h3x h2i'' i_i''.symm, convert hi''.2 j, simp [p', hj'] },
by_cases h2j₂ : j₂ = j',
{ cases h2j₂, refine ⟨x', hx'.1, _⟩, convert hi''.2 j', simp },
refine ⟨(cs i).b j₂.succ, _, _⟩,
{ convert hi'.2 j₂, simp [hj₂] },
{ convert hi''.2 j₂, simp [h2j₂] }
end
variables {h v}
/-- The same result that `mi` cannot lie on the boundary of the valley written as inequalities. -/
lemma mi_not_on_boundary' (j : fin n) : c.tail.b j < (cs (mi h v)).tail.b j ∧
(cs (mi h v)).tail.b j + (cs (mi h v)).w < c.tail.b j + c.w :=
begin
have := mi_not_on_boundary h v j,
simp only [on_boundary, not_or_distrib] at this, cases this with h1 h2,
split,
apply lt_of_le_of_ne (b_le_b mi_mem_bcubes _) h1,
apply lt_of_le_of_ne _ h2,
apply ((Ico_subset_Ico_iff _).mp (tail_sub mi_mem_bcubes j)).2,
simp [hw]
end
/-- The top of `mi` gives rise to a new valley, since the neighbouring cubes extend further upward
than `mi`. -/
def valley_mi : valley cs ((cs (mi h v)).shift_up) :=
begin
let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes,
refine ⟨_, _, _⟩,
{ intro p, apply shift_up_bottom_subset_bottoms h mi_xm_ne_one },
{ rintros i' hi' ⟨p2, hp2, h2p2⟩, simp only [head_shift_up] at hi', classical, by_contra h2i',
rw [tail_shift_up] at h2p2, simp only [not_subset, tail_shift_up] at h2i',
rcases h2i' with ⟨p1, hp1, h2p1⟩,
have : ∃p3, p3 ∈ (cs i').tail.to_set ∧ p3 ∉ (cs i).tail.to_set ∧ p3 ∈ c.tail.to_set,
{ simp only [to_set, not_forall, mem_set_of_eq] at h2p1, cases h2p1 with j hj,
rcases Ico_lemma (mi_not_on_boundary' j).1 (by simp [hw]) (mi_not_on_boundary' j).2
(le_trans (hp2 j).1 $ le_of_lt (h2p2 j).2)
(le_trans (h2p2 j).1 $ le_of_lt (hp2 j).2) ⟨hj, hp1 j⟩ with ⟨w, hw, h2w, h3w⟩,
refine ⟨λ j', if j' = j then w else p2 j', _, _, _⟩,
{ intro j', by_cases h : j' = j,
{ simp only [if_pos h], convert h3w },
{ simp only [if_neg h], exact hp2 j' } },
{ simp only [to_set, not_forall, mem_set_of_eq], use j, rw [if_pos rfl], convert h2w },
{ intro j', by_cases h : j' = j,
{ simp only [if_pos h, side_tail], convert hw },
{ simp only [if_neg h], apply hi.2, apply h2p2 } } },
rcases this with ⟨p3, h1p3, h2p3, h3p3⟩,
let p := @cons n (λ_, ℝ) (c.b 0) p3,
have hp : p ∈ c.bottom, { refine ⟨rfl, _⟩, rwa [tail_cons] },
rcases v.1 hp with ⟨_, ⟨i'', rfl⟩, hi''⟩,
have h2i'' : i'' ∈ bcubes cs c,
{ use hi''.1.symm, apply v.2.1 i'' hi''.1.symm,
use tail p, split, exact hi''.2, rw [tail_cons], exact h3p3 },
have h3i'' : (cs i).w < (cs i'').w,
{ apply mi_strict_minimal _ h2i'', rintro rfl, apply h2p3, convert hi''.2, rw [tail_cons] },
let p' := @cons n (λ_, ℝ) (cs i).xm p3,
have hp' : p' ∈ (cs i').to_set,
{ simpa [to_set, forall_fin_succ, p', hi'.symm] using h1p3 },
have h2p' : p' ∈ (cs i'').to_set,
{ simp only [to_set, forall_fin_succ, p', cons_succ, cons_zero, mem_set_of_eq],
refine ⟨_, by simpa [to_set, p] using hi''.2⟩,
have : (cs i).b 0 = (cs i'').b 0, { by rw [hi.1, h2i''.1] },
simp [side, hw', xm, this, h3i''] },
apply not_disjoint_iff.mpr ⟨p', hp', h2p'⟩,
apply h.1, rintro rfl, apply (cs i).b_ne_xm, rw [←hi', ←hi''.1, hi.1], refl },
{ intros i' hi' h2i',
dsimp only [shift_up] at h2i',
replace h2i' := h.2.2.1 h2i'.symm,
induction h2i',
exact b_ne_xm (cs i) hi' }
end
variables (h)
omit v
/-- We get a sequence of cubes whose size is decreasing -/
noncomputable def sequence_of_cubes : ℕ → { i : ι // valley cs ((cs i).shift_up) }
| 0 := let v := valley_unit_cube h in ⟨mi h v, valley_mi⟩
| (k+1) := let v := (sequence_of_cubes k).2 in ⟨mi h v, valley_mi⟩
def decreasing_sequence (k : ℕ) : order_dual ℝ :=
(cs (sequence_of_cubes h k).1).w
lemma strict_mono_sequence_of_cubes : strict_mono $ decreasing_sequence h :=
strict_mono.nat $
begin
intro k, let v := (sequence_of_cubes h k).2, dsimp only [decreasing_sequence, sequence_of_cubes],
apply w_lt_w h v (mi_mem_bcubes : mi h v ∈ _),
end
omit h
/-- The infinite sequence of cubes contradicts the finiteness of the family. -/
theorem not_correct : ¬correct cs :=
begin
intro h, apply not_le_of_lt (lt_omega_iff_fintype.mpr ⟨_inst_1⟩),
rw [omega, lift_id], fapply mk_le_of_injective, exact λ n, (sequence_of_cubes h n).1,
intros n m hnm, apply strict_mono.injective (strict_mono_sequence_of_cubes h),
dsimp only [decreasing_sequence], rw hnm
end
/-- A cube cannot be cubed. -/
theorem cannot_cube_a_cube :
∀{n : ℕ}, n ≥ 3 → -- In ℝ^n for n ≥ 3
∀{ι : Type} [fintype ι] {cs : ι → cube n}, -- given a finite collection of (hyper)cubes
2 ≤ cardinal.mk ι → -- containing at least two elements
pairwise (disjoint on (cube.to_set ∘ cs)) → -- which is pairwise disjoint
(⋃(i : ι), (cs i).to_set) = unit_cube.to_set → -- whose union is the unit cube
injective (cube.w ∘ cs) → -- such that the widths of all cubes are different
false := -- then we can derive a contradiction
begin
intros n hn ι hι cs h1 h2 h3 h4, resetI,
rcases n, cases hn,
exact not_correct ⟨h2, h3, h4, h1, hn⟩
end
|
6144e3dfdcf64208839b52a4da8de3a191a57963 | a4673261e60b025e2c8c825dfa4ab9108246c32e | /tests/lean/run/Reparen.lean | f4f6dc925709b26ced5537cf2f0fa9ba08629813 | [
"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 | 2,005 | lean | /-! Reprint file after removing all parentheses and then passing it through the parenthesizer -/
import Lean.Parser
open Lean
open Lean.Format
def unparenAux (parens body : Syntax) : Syntax :=
match parens.getHeadInfo, body.getHeadInfo, body.getTailInfo, parens.getTailInfo with
| some bi', some bi, some ti, some ti' => (body.setHeadInfo { bi with leading := bi'.leading }).setTailInfo { ti with trailing := ti'.trailing }
| _, _, _, _ => body
partial def unparen : Syntax → Syntax
-- don't remove parentheses in syntax quotations, they might be semantically significant
| stx => if stx.isOfKind `Lean.Parser.Term.stxQuot then stx
else match_syntax stx with
| `(($stx')) => unparenAux stx $ unparen stx'
| `(level|($stx')) => unparenAux stx $ unparen stx'
| _ => stx.modifyArgs $ Array.map unparen
unsafe def main (args : List String) : IO Unit := do
let (debug, f) : Bool × String := match args with
| [f, "-d"] => (true, f)
| [f] => (false, f)
| _ => panic! "usage: file [-d]";
let env ← mkEmptyEnvironment;
let stx ← Lean.Parser.parseFile env args.head!;
let header := stx.getArg 0;
let some s ← pure header.reprint | throw $ IO.userError "header reprint failed";
IO.print s;
let cmds := (stx.getArg 1).getArgs;
cmds.forM $ fun cmd => do
let cmd := unparen cmd;
let (cmd, _) ← (tryFinally (PrettyPrinter.parenthesizeCommand cmd) printTraces).toIO { options := Options.empty.setBool `trace.PrettyPrinter.parenthesize debug } { env := env };
let some s ← pure cmd.reprint | throw $ IO.userError "cmd reprint failed";
IO.print s
#eval main ["../../../src/Init/Prelude.lean"]
def check (stx : Syntax) : CoreM Unit := do
let stx' := unparen stx;
let stx' ← PrettyPrinter.parenthesizeTerm stx';
let f ← PrettyPrinter.formatTerm stx';
IO.println f;
when (stx != stx') $
throwError "reparenthesization failed"
open Lean
syntax:80 term " ^~ " term:80 : term
syntax:70 term " *~ " term:71 : term
#eval check $ Unhygienic.run `(((1 + 2) *~ 3) ^~ 4)
|
5bc8d548f7b2fd5206decb7e207dbc9e0ed19272 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /library/algebra/field.lean | 9609ef4d0ede48e137aa653876e5c51c4b803e51 | [
"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 | 20,330 | lean | /-
Copyright (c) 2014 Robert Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Lewis
Structures with multiplicative and additive components, including division rings and fields.
The development is modeled after Isabelle's library.
-/
import logic.eq logic.connectives data.unit data.sigma data.prod
import algebra.binary algebra.group algebra.ring
open eq eq.ops
variable {A : Type}
structure division_ring [class] (A : Type) extends ring A, has_inv A, zero_ne_one_class A :=
(mul_inv_cancel : ∀{a}, a ≠ zero → mul a (inv a) = one)
(inv_mul_cancel : ∀{a}, a ≠ zero → mul (inv a) a = one)
section division_ring
variables [s : division_ring A] {a b c : A}
include s
protected definition algebra.div (a b : A) : A := a * b⁻¹
definition division_ring_has_div [instance] : has_div A :=
has_div.mk algebra.div
lemma division.def [simp] (a b : A) : a / b = a * b⁻¹ :=
rfl
theorem mul_inv_cancel [simp] (H : a ≠ 0) : a * a⁻¹ = 1 :=
division_ring.mul_inv_cancel H
theorem inv_mul_cancel [simp] (H : a ≠ 0) : a⁻¹ * a = 1 :=
division_ring.inv_mul_cancel H
theorem inv_eq_one_div (a : A) : a⁻¹ = 1 / a := !one_mul⁻¹
theorem div_eq_mul_one_div (a b : A) : a / b = a * (1 / b) :=
by simp
theorem mul_one_div_cancel [simp] (H : a ≠ 0) : a * (1 / a) = 1 :=
by simp
theorem one_div_mul_cancel [simp] (H : a ≠ 0) : (1 / a) * a = 1 :=
by simp
theorem div_self [simp] (H : a ≠ 0) : a / a = 1 :=
by simp
theorem one_div_one [simp] : 1 / 1 = (1:A) :=
div_self (ne.symm zero_ne_one)
theorem mul_div_assoc (a b : A) : (a * b) / c = a * (b / c) :=
by simp
theorem one_div_ne_zero (H : a ≠ 0) : 1 / a ≠ 0 :=
assume H2 : 1 / a = 0,
have C1 : 0 = (1:A), from symm (by rewrite [-(mul_one_div_cancel H), H2, mul_zero]),
absurd C1 zero_ne_one
theorem one_inv_eq [simp] : 1⁻¹ = (1:A) :=
by rewrite [-mul_one ((1:A)⁻¹), inv_mul_cancel (ne.symm (@zero_ne_one A _))]
theorem div_one [simp] (a : A) : a / 1 = a :=
by simp
theorem zero_div [simp] (a : A) : 0 / a = 0 :=
by simp
-- note: integral domain has a "mul_ne_zero". A commutative division ring is an integral
-- domain, but let's not define that class for now.
theorem division_ring.mul_ne_zero (Ha : a ≠ 0) (Hb : b ≠ 0) : a * b ≠ 0 :=
assume H : a * b = 0,
have C1 : a = 0, by rewrite [-mul_one a, -(mul_one_div_cancel Hb), -mul.assoc, H, zero_mul],
absurd C1 Ha
theorem mul_ne_zero_comm (H : a * b ≠ 0) : b * a ≠ 0 :=
have H2 : a ≠ 0 ∧ b ≠ 0, from ne_zero_and_ne_zero_of_mul_ne_zero H,
division_ring.mul_ne_zero (and.right H2) (and.left H2)
theorem eq_one_div_of_mul_eq_one (H : a * b = 1) : b = 1 / a :=
have a ≠ 0, from
suppose a = 0,
have 0 = (1:A), by inst_simp,
absurd this zero_ne_one,
have b = (1 / a) * a * b, by inst_simp,
show b = 1 / a, by inst_simp
theorem eq_one_div_of_mul_eq_one_left (H : b * a = 1) : b = 1 / a :=
have a ≠ 0, from
suppose a = 0,
have 0 = (1:A), by inst_simp,
absurd this zero_ne_one,
by inst_simp
theorem division_ring.one_div_mul_one_div (Ha : a ≠ 0) (Hb : b ≠ 0) :
(1 / a) * (1 / b) = 1 / (b * a) :=
have (b * a) * ((1 / a) * (1 / b)) = 1, by inst_simp,
eq_one_div_of_mul_eq_one this
theorem one_div_neg_one_eq_neg_one : (1:A) / (-1) = -1 :=
have (-1) * (-1) = (1:A), by inst_simp,
symm (eq_one_div_of_mul_eq_one this)
theorem division_ring.one_div_neg_eq_neg_one_div (H : a ≠ 0) : 1 / (- a) = - (1 / a) :=
have -1 ≠ 0, from
(suppose -1 = 0, absurd (symm (calc
1 = -(-1) : neg_neg
... = -0 : this
... = (0:A) : neg_zero)) zero_ne_one),
calc
1 / (- a) = 1 / ((-1) * a) : neg_eq_neg_one_mul
... = (1 / a) * (1 / (- 1)) : division_ring.one_div_mul_one_div H this
... = (1 / a) * (-1) : one_div_neg_one_eq_neg_one
... = - (1 / a) : mul_neg_one_eq_neg
theorem div_neg_eq_neg_div (b : A) (Ha : a ≠ 0) : b / (- a) = - (b / a) :=
calc
b / (- a) = b * (1 / (- a)) : by rewrite -inv_eq_one_div
... = b * -(1 / a) : division_ring.one_div_neg_eq_neg_one_div Ha
... = -(b * (1 / a)) : neg_mul_eq_mul_neg
... = - (b * a⁻¹) : inv_eq_one_div
theorem neg_div (a b : A) : (-b) / a = - (b / a) :=
by rewrite [neg_eq_neg_one_mul, mul_div_assoc, -neg_eq_neg_one_mul]
theorem division_ring.neg_div_neg_eq (a : A) {b : A} (Hb : b ≠ 0) : (-a) / (-b) = a / b :=
by rewrite [(div_neg_eq_neg_div _ Hb), neg_div, neg_neg]
theorem division_ring.one_div_one_div (H : a ≠ 0) : 1 / (1 / a) = a :=
symm (eq_one_div_of_mul_eq_one_left (mul_one_div_cancel H))
theorem division_ring.eq_of_one_div_eq_one_div (Ha : a ≠ 0) (Hb : b ≠ 0) (H : 1 / a = 1 / b) :
a = b :=
by rewrite [-(division_ring.one_div_one_div Ha), H, (division_ring.one_div_one_div Hb)]
theorem mul_inv_eq [simp] (Ha : a ≠ 0) (Hb : b ≠ 0) : (b * a)⁻¹ = a⁻¹ * b⁻¹ :=
eq.symm (calc
a⁻¹ * b⁻¹ = (1 / a) * (1 / b) : by inst_simp
... = (1 / (b * a)) : division_ring.one_div_mul_one_div Ha Hb
... = (b * a)⁻¹ : by simp)
theorem mul_div_cancel (a : A) {b : A} (Hb : b ≠ 0) : a * b / b = a :=
by simp
theorem div_mul_cancel (a : A) {b : A} (Hb : b ≠ 0) : a / b * b = a :=
by simp
theorem div_add_div_same (a b c : A) : a / c + b / c = (a + b) / c := !right_distrib⁻¹
theorem div_sub_div_same (a b c : A) : (a / c) - (b / c) = (a - b) / c :=
by rewrite [sub_eq_add_neg, -neg_div, div_add_div_same]
theorem one_div_mul_add_mul_one_div_eq_one_div_add_one_div (Ha : a ≠ 0) (Hb : b ≠ 0) :
(1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b :=
by rewrite [(left_distrib (1 / a)), (one_div_mul_cancel Ha), right_distrib, one_mul,
mul.assoc, (mul_one_div_cancel Hb), mul_one, add.comm]
theorem one_div_mul_sub_mul_one_div_eq_one_div_add_one_div (Ha : a ≠ 0) (Hb : b ≠ 0) :
(1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b :=
by rewrite [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel Ha), mul_sub_right_distrib,
one_mul, mul.assoc, (mul_one_div_cancel Hb), mul_one]
theorem div_eq_one_iff_eq (a : A) {b : A} (Hb : b ≠ 0) : a / b = 1 ↔ a = b :=
iff.intro
(suppose a / b = 1, calc
a = a / b * b : by inst_simp
... = 1 * b : this
... = b : by simp)
(suppose a = b, by simp)
theorem eq_of_div_eq_one (a : A) {b : A} (Hb : b ≠ 0) : a / b = 1 → a = b :=
iff.mp (!div_eq_one_iff_eq Hb)
theorem eq_div_iff_mul_eq (a : A) {b : A} (Hc : c ≠ 0) : a = b / c ↔ a * c = b :=
iff.intro
(suppose a = b / c, by rewrite [this, (!div_mul_cancel Hc)])
(suppose a * c = b, by rewrite [-(mul_div_cancel a Hc), this])
theorem eq_div_of_mul_eq (a b : A) {c : A} (Hc : c ≠ 0) : a * c = b → a = b / c :=
iff.mpr (!eq_div_iff_mul_eq Hc)
theorem mul_eq_of_eq_div (a b: A) {c : A} (Hc : c ≠ 0) : a = b / c → a * c = b :=
iff.mp (!eq_div_iff_mul_eq Hc)
theorem add_div_eq_mul_add_div (a b : A) {c : A} (Hc : c ≠ 0) : a + b / c = (a * c + b) / c :=
have (a + b / c) * c = a * c + b, by rewrite [right_distrib, (!div_mul_cancel Hc)],
(iff.elim_right (!eq_div_iff_mul_eq Hc)) this
theorem mul_mul_div (a : A) {c : A} (Hc : c ≠ 0) : a = a * c * (1 / c) :=
by simp
-- There are many similar rules to these last two in the Isabelle library
-- that haven't been ported yet. Do as necessary.
end division_ring
structure field [class] (A : Type) extends division_ring A, comm_ring A
section field
variables [s : field A] {a b c d: A}
include s
theorem field.one_div_mul_one_div (Ha : a ≠ 0) (Hb : b ≠ 0) : (1 / a) * (1 / b) = 1 / (a * b) :=
by rewrite [(division_ring.one_div_mul_one_div Ha Hb), mul.comm b]
theorem field.div_mul_right (Hb : b ≠ 0) (H : a * b ≠ 0) : a / (a * b) = 1 / b :=
have a ≠ 0, from and.left (ne_zero_and_ne_zero_of_mul_ne_zero H),
symm (calc
1 / b = a * ((1 / a) * (1 / b)) : by inst_simp
... = a * (1 / (b * a)) : division_ring.one_div_mul_one_div this Hb
... = a * (a * b)⁻¹ : by inst_simp)
theorem field.div_mul_left (Ha : a ≠ 0) (H : a * b ≠ 0) : b / (a * b) = 1 / a :=
let H1 : b * a ≠ 0 := mul_ne_zero_comm H in
by rewrite [mul.comm a, (field.div_mul_right Ha H1)]
theorem mul_div_cancel_left (Ha : a ≠ 0) : a * b / a = b :=
by rewrite [mul.comm a, (!mul_div_cancel Ha)]
theorem mul_div_cancel' (Hb : b ≠ 0) : b * (a / b) = a :=
by rewrite [mul.comm, (!div_mul_cancel Hb)]
theorem one_div_add_one_div (Ha : a ≠ 0) (Hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) :=
have a * b ≠ 0, from (division_ring.mul_ne_zero Ha Hb),
by rewrite [add.comm, -(field.div_mul_left Ha this), -(field.div_mul_right Hb this), *division.def,
-right_distrib]
theorem field.div_mul_div (a : A) {b : A} (c : A) {d : A} (Hb : b ≠ 0) (Hd : d ≠ 0) :
(a / b) * (c / d) = (a * c) / (b * d) :=
by inst_simp
theorem mul_div_mul_left (a : A) {b c : A} (Hb : b ≠ 0) (Hc : c ≠ 0) :
(c * a) / (c * b) = a / b :=
by rewrite [-(!field.div_mul_div Hc Hb), (div_self Hc), one_mul]
theorem mul_div_mul_right (a : A) {b c : A} (Hb : b ≠ 0) (Hc : c ≠ 0) :
(a * c) / (b * c) = a / b :=
by rewrite [(mul.comm a), (mul.comm b), (!mul_div_mul_left Hb Hc)]
theorem div_mul_eq_mul_div (a b c : A) : (b / c) * a = (b * a) / c :=
by rewrite [*division.def, mul.assoc, (mul.comm c⁻¹), -mul.assoc]
theorem field.div_mul_eq_mul_div_comm (a b : A) {c : A} (Hc : c ≠ 0) :
(b / c) * a = b * (a / c) :=
by rewrite [(div_mul_eq_mul_div), -(one_mul c), -(!field.div_mul_div (ne.symm zero_ne_one) Hc),
div_one, one_mul]
theorem div_add_div (a : A) {b : A} (c : A) {d : A} (Hb : b ≠ 0) (Hd : d ≠ 0) :
(a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) :=
by rewrite [-(!mul_div_mul_right Hb Hd), -(!mul_div_mul_left Hd Hb), div_add_div_same]
theorem div_sub_div (a : A) {b : A} (c : A) {d : A} (Hb : b ≠ 0) (Hd : d ≠ 0) :
(a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) :=
by rewrite [*sub_eq_add_neg, neg_eq_neg_one_mul, -mul_div_assoc, (!div_add_div Hb Hd),
-mul.assoc, (mul.comm b), mul.assoc, -neg_eq_neg_one_mul]
theorem mul_eq_mul_of_div_eq_div (a : A) {b : A} (c : A) {d : A} (Hb : b ≠ 0)
(Hd : d ≠ 0) (H : a / b = c / d) : a * d = c * b :=
by rewrite [-mul_one (a*d), mul.assoc, (mul.comm d), -mul.assoc, -(div_self Hb),
-(!field.div_mul_eq_mul_div_comm Hb), H, (div_mul_eq_mul_div), (!div_mul_cancel Hd)]
theorem field.one_div_div (Ha : a ≠ 0) (Hb : b ≠ 0) : 1 / (a / b) = b / a :=
have (a / b) * (b / a) = 1, from calc
(a / b) * (b / a) = (a * b) / (b * a) : !field.div_mul_div Hb Ha
... = (a * b) / (a * b) : mul.comm
... = 1 : div_self (division_ring.mul_ne_zero Ha Hb),
symm (eq_one_div_of_mul_eq_one this)
theorem field.div_div_eq_mul_div (a : A) {b c : A} (Hb : b ≠ 0) (Hc : c ≠ 0) :
a / (b / c) = (a * c) / b :=
by rewrite [div_eq_mul_one_div, (field.one_div_div Hb Hc), -mul_div_assoc]
theorem field.div_div_eq_div_mul (a : A) {b c : A} (Hb : b ≠ 0) (Hc : c ≠ 0) :
(a / b) / c = a / (b * c) :=
by rewrite [div_eq_mul_one_div, (!field.div_mul_div Hb Hc), mul_one]
theorem field.div_div_div_div_eq (a : A) {b c d : A} (Hb : b ≠ 0) (Hc : c ≠ 0) (Hd : d ≠ 0) :
(a / b) / (c / d) = (a * d) / (b * c) :=
by rewrite [(!field.div_div_eq_mul_div Hc Hd), (div_mul_eq_mul_div),
(!field.div_div_eq_div_mul Hb Hc)]
theorem field.div_mul_eq_div_mul_one_div (a : A) {b c : A} (Hb : b ≠ 0) (Hc : c ≠ 0) :
a / (b * c) = (a / b) * (1 / c) :=
by rewrite [-!field.div_div_eq_div_mul Hb Hc, -div_eq_mul_one_div]
theorem eq_of_mul_eq_mul_of_nonzero_left {a b c : A} (H : a ≠ 0) (H2 : a * b = a * c) : b = c :=
by rewrite [-one_mul b, -div_self H, div_mul_eq_mul_div, H2, mul_div_cancel_left H]
theorem eq_of_mul_eq_mul_of_nonzero_right {a b c : A} (H : c ≠ 0) (H2 : a * c = b * c) : a = b :=
by rewrite [-mul_one a, -div_self H, -mul_div_assoc, H2, mul_div_cancel _ H]
end field
structure discrete_field [class] (A : Type) extends field A :=
(has_decidable_eq : decidable_eq A)
(inv_zero : inv zero = zero)
attribute discrete_field.has_decidable_eq [instance]
section discrete_field
variable [s : discrete_field A]
include s
variables {a b c d : A}
-- many of the theorems in discrete_field are the same as theorems in field or division ring,
-- but with fewer hypotheses since 0⁻¹ = 0 and equality is decidable.
theorem discrete_field.eq_zero_or_eq_zero_of_mul_eq_zero
(x y : A) (H : x * y = 0) : x = 0 ∨ y = 0 :=
decidable.by_cases
(suppose x = 0, or.inl this)
(suppose x ≠ 0,
or.inr (by rewrite [-one_mul y, -(inv_mul_cancel this), mul.assoc, H, mul_zero]))
definition discrete_field.to_integral_domain [trans_instance] :
integral_domain A :=
⦃ integral_domain, s,
eq_zero_or_eq_zero_of_mul_eq_zero := discrete_field.eq_zero_or_eq_zero_of_mul_eq_zero⦄
theorem inv_zero : 0⁻¹ = (0:A) := !discrete_field.inv_zero
theorem one_div_zero : 1 / 0 = (0:A) :=
calc
1 / 0 = 1 * 0⁻¹ : refl
... = 1 * 0 : inv_zero
... = 0 : mul_zero
theorem div_zero (a : A) : a / 0 = 0 := by rewrite [div_eq_mul_one_div, one_div_zero, mul_zero]
theorem ne_zero_of_one_div_ne_zero (H : 1 / a ≠ 0) : a ≠ 0 :=
assume Ha : a = 0, absurd (Ha⁻¹ ▸ one_div_zero) H
theorem eq_zero_of_one_div_eq_zero (H : 1 / a = 0) : a = 0 :=
decidable.by_cases
(assume Ha, Ha)
(assume Ha, false.elim ((one_div_ne_zero Ha) H))
variables (a b)
theorem one_div_mul_one_div' : (1 / a) * (1 / b) = 1 / (b * a) :=
decidable.by_cases
(suppose a = 0,
by rewrite [this, div_zero, zero_mul, -(@div_zero A s 1), mul_zero b])
(assume Ha : a ≠ 0,
decidable.by_cases
(suppose b = 0,
by rewrite [this, div_zero, mul_zero, -(@div_zero A s 1), zero_mul a])
(suppose b ≠ 0, division_ring.one_div_mul_one_div Ha this))
theorem one_div_neg_eq_neg_one_div : 1 / (- a) = - (1 / a) :=
decidable.by_cases
(suppose a = 0, by rewrite [this, neg_zero, 2 div_zero, neg_zero])
(suppose a ≠ 0, division_ring.one_div_neg_eq_neg_one_div this)
theorem neg_div_neg_eq : (-a) / (-b) = a / b :=
decidable.by_cases
(assume Hb : b = 0, by rewrite [Hb, neg_zero, 2 div_zero])
(assume Hb : b ≠ 0, !division_ring.neg_div_neg_eq Hb)
theorem one_div_one_div : 1 / (1 / a) = a :=
decidable.by_cases
(assume Ha : a = 0, by rewrite [Ha, 2 div_zero])
(assume Ha : a ≠ 0, division_ring.one_div_one_div Ha)
variables {a b}
theorem eq_of_one_div_eq_one_div (H : 1 / a = 1 / b) : a = b :=
decidable.by_cases
(assume Ha : a = 0,
have Hb : b = 0, from eq_zero_of_one_div_eq_zero (by rewrite [-H, Ha, div_zero]),
Hb⁻¹ ▸ Ha)
(assume Ha : a ≠ 0,
have Hb : b ≠ 0, from ne_zero_of_one_div_ne_zero (H ▸ (one_div_ne_zero Ha)),
division_ring.eq_of_one_div_eq_one_div Ha Hb H)
variables (a b)
theorem mul_inv' : (b * a)⁻¹ = a⁻¹ * b⁻¹ :=
decidable.by_cases
(assume Ha : a = 0, by rewrite [Ha, mul_zero, 2 inv_zero, zero_mul])
(assume Ha : a ≠ 0,
decidable.by_cases
(assume Hb : b = 0, by rewrite [Hb, zero_mul, 2 inv_zero, mul_zero])
(assume Hb : b ≠ 0, mul_inv_eq Ha Hb))
-- the following are specifically for fields
theorem one_div_mul_one_div : (1 / a) * (1 / b) = 1 / (a * b) :=
by rewrite [one_div_mul_one_div', mul.comm b]
variable {a}
theorem div_mul_right (Ha : a ≠ 0) : a / (a * b) = 1 / b :=
decidable.by_cases
(assume Hb : b = 0, by rewrite [Hb, mul_zero, 2 div_zero])
(assume Hb : b ≠ 0, field.div_mul_right Hb (mul_ne_zero Ha Hb))
variables (a) {b}
theorem div_mul_left (Hb : b ≠ 0) : b / (a * b) = 1 / a :=
by rewrite [mul.comm a, div_mul_right _ Hb]
variables (a b c)
theorem div_mul_div : (a / b) * (c / d) = (a * c) / (b * d) :=
decidable.by_cases
(assume Hb : b = 0, by rewrite [Hb, div_zero, zero_mul, -(@div_zero A s (a * c)), zero_mul])
(assume Hb : b ≠ 0,
decidable.by_cases
(assume Hd : d = 0, by rewrite [Hd, div_zero, mul_zero, -(@div_zero A s (a * c)),
mul_zero])
(assume Hd : d ≠ 0, !field.div_mul_div Hb Hd))
variable {c}
theorem mul_div_mul_left' (Hc : c ≠ 0) : (c * a) / (c * b) = a / b :=
decidable.by_cases
(assume Hb : b = 0, by rewrite [Hb, mul_zero, 2 div_zero])
(assume Hb : b ≠ 0, !mul_div_mul_left Hb Hc)
theorem mul_div_mul_right' (Hc : c ≠ 0) : (a * c) / (b * c) = a / b :=
by rewrite [(mul.comm a), (mul.comm b), (!mul_div_mul_left' Hc)]
variables (a b c d)
theorem div_mul_eq_mul_div_comm : (b / c) * a = b * (a / c) :=
decidable.by_cases
(assume Hc : c = 0, by rewrite [Hc, div_zero, zero_mul, -(mul_zero b), -(@div_zero A s a)])
(assume Hc : c ≠ 0, !field.div_mul_eq_mul_div_comm Hc)
theorem one_div_div : 1 / (a / b) = b / a :=
decidable.by_cases
(assume Ha : a = 0, by rewrite [Ha, zero_div, 2 div_zero])
(assume Ha : a ≠ 0,
decidable.by_cases
(assume Hb : b = 0, by rewrite [Hb, 2 div_zero, zero_div])
(assume Hb : b ≠ 0, field.one_div_div Ha Hb))
theorem div_div_eq_mul_div : a / (b / c) = (a * c) / b :=
by rewrite [div_eq_mul_one_div, one_div_div, -mul_div_assoc]
theorem div_div_eq_div_mul : (a / b) / c = a / (b * c) :=
by rewrite [div_eq_mul_one_div, div_mul_div, mul_one]
theorem div_div_div_div_eq : (a / b) / (c / d) = (a * d) / (b * c) :=
by rewrite [div_div_eq_mul_div, div_mul_eq_mul_div, div_div_eq_div_mul]
variable {a}
theorem div_helper (H : a ≠ 0) : (1 / (a * b)) * a = 1 / b :=
by rewrite [div_mul_eq_mul_div, one_mul, !div_mul_right H]
variable (a)
theorem div_mul_eq_div_mul_one_div : a / (b * c) = (a / b) * (1 / c) :=
by rewrite [-div_div_eq_div_mul, -div_eq_mul_one_div]
end discrete_field
namespace norm_num
theorem div_add_helper [s : field A] (n d b c val : A) (Hd : d ≠ 0) (H : n + b * d = val)
(H2 : c * d = val) : n / d + b = c :=
begin
apply eq_of_mul_eq_mul_of_nonzero_right Hd,
rewrite [H2, -H, right_distrib, div_mul_cancel _ Hd]
end
theorem add_div_helper [s : field A] (n d b c val : A) (Hd : d ≠ 0) (H : d * b + n = val)
(H2 : d * c = val) : b + n / d = c :=
begin
apply eq_of_mul_eq_mul_of_nonzero_left Hd,
rewrite [H2, -H, left_distrib, mul_div_cancel' Hd]
end
theorem div_mul_helper [s : field A] (n d c v : A) (Hd : d ≠ 0) (H : (n * c) / d = v) :
(n / d) * c = v :=
by rewrite [-H, field.div_mul_eq_mul_div_comm _ _ Hd, mul_div_assoc]
theorem mul_div_helper [s : field A] (a n d v : A) (Hd : d ≠ 0) (H : (a * n) / d = v) :
a * (n / d) = v :=
by rewrite [-H, mul_div_assoc]
theorem nonzero_of_div_helper [s : field A] (a b : A) (Ha : a ≠ 0) (Hb : b ≠ 0) : a / b ≠ 0 :=
begin
intro Hab,
have Habb : (a / b) * b = 0, by rewrite [Hab, zero_mul],
rewrite [div_mul_cancel _ Hb at Habb],
exact Ha Habb
end
theorem div_helper [s : field A] (n d v : A) (Hd : d ≠ 0) (H : v * d = n) : n / d = v :=
begin
apply eq_of_mul_eq_mul_of_nonzero_right Hd,
rewrite (div_mul_cancel _ Hd),
exact eq.symm H
end
theorem div_eq_div_helper [s : field A] (a b c d v : A) (H1 : a * d = v) (H2 : c * b = v)
(Hb : b ≠ 0) (Hd : d ≠ 0) : a / b = c / d :=
begin
apply eq_div_of_mul_eq,
exact Hd,
rewrite div_mul_eq_mul_div,
apply eq.symm,
apply eq_div_of_mul_eq,
exact Hb,
rewrite [H1, H2]
end
theorem subst_into_div [s : has_div A] (a₁ b₁ a₂ b₂ v : A) (H : a₁ / b₁ = v) (H1 : a₂ = a₁)
(H2 : b₂ = b₁) : a₂ / b₂ = v :=
by rewrite [H1, H2, H]
end norm_num
|
a40cc17908c27541be5e52a4a673e3571b13ca1e | fcf3ffa92a3847189ca669cb18b34ef6b2ec2859 | /src/world8/level3.lean | 85b4f5982a85b08e76549cb5381f1751c33a5a45 | [
"Apache-2.0"
] | permissive | nomoid/lean-proofs | 4a80a97888699dee42b092b7b959b22d9aa0c066 | b9f03a24623d1a1d111d6c2bbf53c617e2596d6a | refs/heads/master | 1,674,955,317,080 | 1,607,475,706,000 | 1,607,475,706,000 | 314,104,281 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 159 | lean | import mynat.definition
namespace mynat
theorem succ_eq_succ_of_eq {a b : mynat} : a = b → succ(a) = succ(b) :=
begin
intro a,
rw a,
end
end mynat |
53a7529c7043a684aadf28bdd76c1e8bdfd5aa57 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/data/string/basic.lean | 39b7fddc7851168644d3bb6501bec7e0edf3ca5c | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 2,518 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Supplementary theorems about the `string` type.
-/
import data.list.basic
import data.char
namespace string
def ltb : iterator → iterator → bool
| s₁ s₂ := begin
cases s₂.has_next, {exact ff},
cases h₁ : s₁.has_next, {exact tt},
exact if s₁.curr = s₂.curr then
have s₁.next.2.length < s₁.2.length, from
match s₁, h₁ with ⟨_, a::l⟩, h := nat.lt_succ_self _ end,
ltb s₁.next s₂.next
else s₁.curr < s₂.curr,
end
using_well_founded {rel_tac :=
λ _ _, `[exact ⟨_, measure_wf (λ s, s.1.2.length)⟩]}
instance has_lt' : has_lt string :=
⟨λ s₁ s₂, ltb s₁.mk_iterator s₂.mk_iterator⟩
instance decidable_lt : @decidable_rel string (<) := by apply_instance -- short-circuit type class inference
@[simp] theorem lt_iff_to_list_lt :
∀ {s₁ s₂ : string}, s₁ < s₂ ↔ s₁.to_list < s₂.to_list
| ⟨i₁⟩ ⟨i₂⟩ :=
suffices ∀ {p₁ p₂ s₁ s₂}, ltb ⟨p₁, s₁⟩ ⟨p₂, s₂⟩ ↔ s₁ < s₂, from this,
begin
intros,
induction s₁ with a s₁ IH generalizing p₁ p₂ s₂;
cases s₂ with b s₂; rw ltb; simp [iterator.has_next],
{ exact iff_of_false bool.ff_ne_tt (lt_irrefl _) },
{ exact iff_of_true rfl list.lex.nil },
{ exact iff_of_false bool.ff_ne_tt (not_lt_of_lt list.lex.nil) },
{ dsimp [iterator.has_next,
iterator.curr, iterator.next],
split_ifs,
{ subst b, exact IH.trans list.lex.cons_iff.symm },
{ simp, refine ⟨list.lex.rel, λ e, _⟩,
cases e, {cases h rfl}, assumption } }
end
instance has_le : has_le string := ⟨λ s₁ s₂, ¬ s₂ < s₁⟩
instance decidable_le : @decidable_rel string (≤) := by apply_instance -- short-circuit type class inference
@[simp] theorem le_iff_to_list_le
{s₁ s₂ : string} : s₁ ≤ s₂ ↔ s₁.to_list ≤ s₂.to_list :=
(not_congr lt_iff_to_list_lt).trans not_lt
theorem to_list_inj : ∀ {s₁ s₂}, to_list s₁ = to_list s₂ ↔ s₁ = s₂
| ⟨s₁⟩ ⟨s₂⟩ := ⟨congr_arg _, congr_arg _⟩
instance : linear_order string :=
by refine_struct {
lt := (<), le := (≤),
decidable_lt := by apply_instance,
decidable_le := string.decidable_le,
decidable_eq := by apply_instance, .. };
{ simp only [le_iff_to_list_le, lt_iff_to_list_lt, ← to_list_inj], introv,
apply_field }
end string
|
117ae62e7a5b15647f5e41f8d5591176b77353e8 | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/algebra/ordered_field.lean | 3bb31b53feed7409caa87fd6fde4aa389292f72f | [
"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 | 9,494 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.ordered_ring
import algebra.field
section linear_ordered_field
variables {α : Type*} [linear_ordered_field α] {a b c d : α}
lemma div_pos : 0 < a → 0 < b → 0 < a / b := div_pos_of_pos_of_pos
@[simp] lemma inv_pos : ∀ {a : α}, 0 < a⁻¹ ↔ 0 < a :=
suffices ∀ a : α, 0 < a → 0 < a⁻¹,
from λ a, ⟨λ h, inv_inv'' a ▸ this _ h, this a⟩,
λ a, one_div_eq_inv a ▸ one_div_pos_of_pos
@[simp] lemma inv_lt_zero : ∀ {a : α}, a⁻¹ < 0 ↔ a < 0 :=
suffices ∀ a : α, a < 0 → a⁻¹ < 0,
from λ a, ⟨λ h, inv_inv'' a ▸ this _ h, this a⟩,
λ a, one_div_eq_inv a ▸ one_div_neg_of_neg
@[simp] lemma inv_nonneg {a : α} : 0 ≤ a⁻¹ ↔ 0 ≤ a :=
le_iff_le_iff_lt_iff_lt.2 inv_lt_zero
@[simp] lemma inv_nonpos {a : α} : a⁻¹ ≤ 0 ↔ a ≤ 0 :=
le_iff_le_iff_lt_iff_lt.2 inv_pos
lemma one_le_div_iff_le (hb : 0 < b) : 1 ≤ a / b ↔ b ≤ a :=
⟨le_of_one_le_div a hb, one_le_div_of_le a hb⟩
lemma one_lt_div_iff_lt (hb : 0 < b) : 1 < a / b ↔ b < a :=
⟨lt_of_one_lt_div a hb, one_lt_div_of_lt a hb⟩
lemma div_le_one_iff_le (hb : 0 < b) : a / b ≤ 1 ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 (one_lt_div_iff_lt hb)
lemma div_lt_one_iff_lt (hb : 0 < b) : a / b < 1 ↔ a < b :=
lt_iff_lt_of_le_iff_le (one_le_div_iff_le hb)
lemma le_div_iff (hc : 0 < c) : a ≤ b / c ↔ a * c ≤ b :=
⟨mul_le_of_le_div hc, le_div_of_mul_le hc⟩
lemma le_div_iff' (hc : 0 < c) : a ≤ b / c ↔ c * a ≤ b :=
by rw [mul_comm, le_div_iff hc]
lemma div_le_iff (hb : 0 < b) : a / b ≤ c ↔ a ≤ c * b :=
⟨le_mul_of_div_le hb, by rw [mul_comm]; exact div_le_of_le_mul hb⟩
lemma div_le_iff' (hb : 0 < b) : a / b ≤ c ↔ a ≤ b * c :=
by rw [mul_comm, div_le_iff hb]
lemma lt_div_iff (hc : 0 < c) : a < b / c ↔ a * c < b :=
⟨mul_lt_of_lt_div hc, lt_div_of_mul_lt hc⟩
lemma lt_div_iff' (hc : 0 < c) : a < b / c ↔ c * a < b :=
by rw [mul_comm, lt_div_iff hc]
lemma div_le_iff_of_neg (hc : c < 0) : b / c ≤ a ↔ a * c ≤ b :=
⟨mul_le_of_div_le_of_neg hc, div_le_of_mul_le_of_neg hc⟩
lemma le_div_iff_of_neg (hc : c < 0) : a ≤ b / c ↔ b ≤ a * c :=
by rw [← neg_neg c, mul_neg_eq_neg_mul_symm, div_neg, le_neg,
div_le_iff (neg_pos.2 hc), neg_mul_eq_neg_mul_symm]
lemma div_lt_iff (hc : 0 < c) : b / c < a ↔ b < a * c :=
lt_iff_lt_of_le_iff_le (le_div_iff hc)
lemma div_lt_iff' (hc : 0 < c) : b / c < a ↔ b < c * a :=
by rw [mul_comm, div_lt_iff hc]
lemma div_lt_iff_of_neg (hc : c < 0) : b / c < a ↔ a * c < b :=
⟨mul_lt_of_gt_div_of_neg hc, div_lt_of_mul_gt_of_neg hc⟩
lemma inv_le_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a :=
by rw [inv_eq_one_div, div_le_iff ha,
← div_eq_inv_mul, one_le_div_iff_le hb]
lemma inv_le (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a :=
by rw [← inv_le_inv hb (inv_pos.2 ha), inv_inv']
lemma le_inv (ha : 0 < a) (hb : 0 < b) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ :=
by rw [← inv_le_inv (inv_pos.2 hb) ha, inv_inv']
lemma one_div_le_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ 1 / b ↔ b ≤ a :=
by simpa [one_div_eq_inv] using inv_le_inv ha hb
lemma inv_lt_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b⁻¹ ↔ b < a :=
lt_iff_lt_of_le_iff_le (inv_le_inv hb ha)
lemma inv_lt (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b ↔ b⁻¹ < a :=
lt_iff_lt_of_le_iff_le (le_inv hb ha)
lemma one_div_lt (ha : 0 < a) (hb : 0 < b) : 1 / a < b ↔ 1 / b < a :=
(one_div_eq_inv a).symm ▸ (one_div_eq_inv b).symm ▸ inv_lt ha hb
lemma lt_inv (ha : 0 < a) (hb : 0 < b) : a < b⁻¹ ↔ b < a⁻¹ :=
lt_iff_lt_of_le_iff_le (inv_le hb ha)
lemma one_div_lt_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a < 1 / b ↔ b < a :=
lt_iff_lt_of_le_iff_le (one_div_le_one_div hb ha)
lemma div_nonneg : 0 ≤ a → 0 < b → 0 ≤ a / b := div_nonneg_of_nonneg_of_pos
lemma div_lt_div_right (hc : 0 < c) : a / c < b / c ↔ a < b :=
⟨lt_imp_lt_of_le_imp_le (λ h, div_le_div_of_le_of_pos h hc),
λ h, div_lt_div_of_lt_of_pos h hc⟩
lemma div_le_div_right (hc : 0 < c) : a / c ≤ b / c ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 (div_lt_div_right hc)
lemma div_lt_div_right_of_neg (hc : c < 0) : a / c < b / c ↔ b < a :=
⟨lt_imp_lt_of_le_imp_le (λ h, div_le_div_of_le_of_neg h hc),
λ h, div_lt_div_of_lt_of_neg h hc⟩
lemma div_le_div_right_of_neg (hc : c < 0) : a / c ≤ b / c ↔ b ≤ a :=
le_iff_le_iff_lt_iff_lt.2 (div_lt_div_right_of_neg hc)
lemma div_lt_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b < a / c ↔ c < b :=
(mul_lt_mul_left ha).trans (inv_lt_inv hb hc)
lemma div_le_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b ≤ a / c ↔ c ≤ b :=
le_iff_le_iff_lt_iff_lt.2 (div_lt_div_left ha hc hb)
lemma div_lt_div_iff (b0 : 0 < b) (d0 : 0 < d) :
a / b < c / d ↔ a * d < c * b :=
by rw [lt_div_iff d0, div_mul_eq_mul_div, div_lt_iff b0]
lemma div_le_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b ≤ c / d ↔ a * d ≤ c * b :=
by rw [le_div_iff d0, div_mul_eq_mul_div, div_le_iff b0]
lemma div_lt_div (hac : a < c) (hbd : d ≤ b) (c0 : 0 ≤ c) (d0 : 0 < d) :
a / b < c / d :=
(div_lt_div_iff (lt_of_lt_of_le d0 hbd) d0).2 (mul_lt_mul hac hbd d0 c0)
lemma div_lt_div' (hac : a ≤ c) (hbd : d < b) (c0 : 0 < c) (d0 : 0 < d) :
a / b < c / d :=
(div_lt_div_iff (lt_trans d0 hbd) d0).2 (mul_lt_mul' hac hbd (le_of_lt d0) c0)
lemma monotone.div_const {β : Type*} [preorder β] {f : β → α} (hf : monotone f)
{c : α} (hc : 0 ≤ c) :
monotone (λ x, (f x) / c) :=
hf.mul_const (inv_nonneg.2 hc)
lemma strict_mono.div_const {β : Type*} [preorder β] {f : β → α} (hf : strict_mono f)
{c : α} (hc : 0 < c) :
strict_mono (λ x, (f x) / c) :=
hf.mul_const (inv_pos.2 hc)
lemma half_pos {a : α} (h : 0 < a) : 0 < a / 2 := div_pos h two_pos
lemma one_half_pos : (0:α) < 1 / 2 := half_pos zero_lt_one
lemma half_lt_self : 0 < a → a / 2 < a := div_two_lt_of_pos
lemma one_half_lt_one : (1 / 2 : α) < 1 := half_lt_self zero_lt_one
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_field.to_densely_ordered : densely_ordered α :=
{ dense := assume a₁ a₂ h, ⟨(a₁ + a₂) / 2,
calc a₁ = (a₁ + a₁) / 2 : (add_self_div_two a₁).symm
... < (a₁ + a₂) / 2 : div_lt_div_of_lt_of_pos (add_lt_add_left h _) two_pos,
calc (a₁ + a₂) / 2 < (a₂ + a₂) / 2 : div_lt_div_of_lt_of_pos (add_lt_add_right h _) two_pos
... = a₂ : add_self_div_two a₂⟩ }
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_field.to_no_top_order : no_top_order α :=
{ no_top := assume a, ⟨a + 1, lt_add_of_le_of_pos (le_refl a) zero_lt_one ⟩ }
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_field.to_no_bot_order : no_bot_order α :=
{ no_bot := assume a, ⟨a + -1,
add_lt_of_le_of_neg (le_refl _) (neg_lt_of_neg_lt $ by simp [zero_lt_one]) ⟩ }
lemma inv_lt_one {a : α} (ha : 1 < a) : a⁻¹ < 1 :=
by rw [inv_eq_one_div]; exact div_lt_of_mul_lt_of_pos (lt_trans zero_lt_one ha) (by simp *)
lemma one_lt_inv (h₁ : 0 < a) (h₂ : a < 1) : 1 < a⁻¹ :=
by rw [inv_eq_one_div, lt_div_iff h₁]; simp [h₂]
lemma inv_le_one {a : α} (ha : 1 ≤ a) : a⁻¹ ≤ 1 :=
by rw [inv_eq_one_div]; exact div_le_of_le_mul (lt_of_lt_of_le zero_lt_one ha) (by simp *)
lemma one_le_inv {x : α} (hx0 : 0 < x) (hx : x ≤ 1) : 1 ≤ x⁻¹ :=
le_of_mul_le_mul_left (by simpa [mul_inv_cancel (ne.symm (ne_of_lt hx0))]) hx0
lemma mul_self_inj_of_nonneg {a b : α} (a0 : 0 ≤ a) (b0 : 0 ≤ b) : a * a = b * b ↔ a = b :=
(mul_self_eq_mul_self_iff a b).trans $ or_iff_left_of_imp $
λ h, by subst a; rw [le_antisymm (neg_nonneg.1 a0) b0, neg_zero]
lemma div_le_div_of_le_left {a b c : α} (ha : 0 ≤ a) (hc : 0 < c) (h : c ≤ b) :
a / b ≤ a / c :=
by haveI := classical.dec_eq α; exact
if ha0 : a = 0 then by simp [ha0]
else (div_le_div_left (lt_of_le_of_ne ha (ne.symm ha0)) (lt_of_lt_of_le hc h) hc).2 h
lemma inv_le_inv_of_le {a b : α} (hb : 0 < b) (h : b ≤ a) : a⁻¹ ≤ b⁻¹ :=
begin
rw [inv_eq_one_div, inv_eq_one_div],
exact one_div_le_one_div_of_le hb h
end
lemma div_nonneg' {a b : α} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a / b :=
(lt_or_eq_of_le hb).elim (div_nonneg ha) (λ h, by simp [h.symm])
lemma div_le_div_of_le_of_nonneg {a b c : α} (hab : a ≤ b) (hc : 0 ≤ c) :
a / c ≤ b / c :=
mul_le_mul_of_nonneg_right hab (inv_nonneg.2 hc)
end linear_ordered_field
namespace nat
variables {α : Type*} [linear_ordered_field α]
lemma inv_pos_of_nat {n : ℕ} : 0 < ((n : α) + 1)⁻¹ :=
inv_pos.2 $ add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one
lemma one_div_pos_of_nat {n : ℕ} : 0 < 1 / ((n : α) + 1) :=
by { rw one_div_eq_inv, exact inv_pos_of_nat }
lemma one_div_le_one_div {n m : ℕ} (h : n ≤ m) : 1 / ((m : α) + 1) ≤ 1 / ((n : α) + 1) :=
by { refine one_div_le_one_div_of_le _ _, exact nat.cast_add_one_pos _, simpa }
lemma one_div_lt_one_div {n m : ℕ} (h : n < m) : 1 / ((m : α) + 1) < 1 / ((n : α) + 1) :=
by { refine one_div_lt_one_div_of_lt _ _, exact nat.cast_add_one_pos _, simpa }
end nat
section
variables {α : Type*} [discrete_linear_ordered_field α] (a b c : α)
lemma abs_inv : abs a⁻¹ = (abs a)⁻¹ :=
have h : abs (1 / a) = 1 / abs a,
begin rw [abs_div, abs_of_nonneg], exact zero_le_one end,
by simp [*] at *
end
|
58694b6b8f21b4abed9161d35dae2ca677ccb5f4 | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/ring_theory/ideal_operations.lean | b205935cafa8bade9212520eb1e9cb85dac2af18 | [
"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 | 26,184 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
More operations on modules and ideals.
-/
import data.nat.choose
import data.equiv.ring
import ring_theory.algebra_operations
universes u v w x
namespace submodule
variables {R : Type u} {M : Type v}
variables [comm_ring R] [add_comm_group M] [module R M]
instance has_scalar' : has_scalar (ideal R) (submodule R M) :=
⟨λ I N, ⨆ r : I, N.map (r.1 • linear_map.id)⟩
def annihilator (N : submodule R M) : ideal R :=
(linear_map.lsmul R N).ker
def colon (N P : submodule R M) : ideal R :=
annihilator (P.map N.mkq)
variables {I J : ideal R} {N N₁ N₂ P P₁ P₂ : submodule R M}
theorem mem_annihilator {r} : r ∈ N.annihilator ↔ ∀ n ∈ N, r • n = (0:M) :=
⟨λ hr n hn, congr_arg subtype.val (linear_map.ext_iff.1 (linear_map.mem_ker.1 hr) ⟨n, hn⟩),
λ h, linear_map.mem_ker.2 $ linear_map.ext $ λ n, subtype.eq $ h n.1 n.2⟩
theorem mem_annihilator' {r} : r ∈ N.annihilator ↔ N ≤ comap (r • linear_map.id) ⊥ :=
mem_annihilator.trans ⟨λ H n hn, (mem_bot R).2 $ H n hn, λ H n hn, (mem_bot R).1 $ H hn⟩
theorem annihilator_bot : (⊥ : submodule R M).annihilator = ⊤ :=
(ideal.eq_top_iff_one _).2 $ mem_annihilator'.2 bot_le
theorem annihilator_eq_top_iff : N.annihilator = ⊤ ↔ N = ⊥ :=
⟨λ H, eq_bot_iff.2 $ λ (n:M) hn, (mem_bot R).2 $ one_smul R n ▸ mem_annihilator.1 ((ideal.eq_top_iff_one _).1 H) n hn,
λ H, H.symm ▸ annihilator_bot⟩
theorem annihilator_mono (h : N ≤ P) : P.annihilator ≤ N.annihilator :=
λ r hrp, mem_annihilator.2 $ λ n hn, mem_annihilator.1 hrp n $ h hn
theorem annihilator_supr (ι : Type w) (f : ι → submodule R M) :
(annihilator ⨆ i, f i) = ⨅ i, annihilator (f i) :=
le_antisymm (le_infi $ λ i, annihilator_mono $ le_supr _ _)
(λ r H, mem_annihilator'.2 $ supr_le $ λ i,
have _ := (mem_infi _).1 H i, mem_annihilator'.1 this)
theorem mem_colon {r} : r ∈ N.colon P ↔ ∀ p ∈ P, r • p ∈ N :=
mem_annihilator.trans ⟨λ H p hp, (quotient.mk_eq_zero N).1 (H (quotient.mk p) (mem_map_of_mem hp)),
λ H m ⟨p, hp, hpm⟩, hpm ▸ (N.mkq).map_smul r p ▸ (quotient.mk_eq_zero N).2 $ H p hp⟩
theorem mem_colon' {r} : r ∈ N.colon P ↔ P ≤ comap (r • linear_map.id) N :=
mem_colon
theorem colon_mono (hn : N₁ ≤ N₂) (hp : P₁ ≤ P₂) : N₁.colon P₂ ≤ N₂.colon P₁ :=
λ r hrnp, mem_colon.2 $ λ p₁ hp₁, hn $ mem_colon.1 hrnp p₁ $ hp hp₁
theorem infi_colon_supr (ι₁ : Type w) (f : ι₁ → submodule R M)
(ι₂ : Type x) (g : ι₂ → submodule R M) :
(⨅ i, f i).colon (⨆ j, g j) = ⨅ i j, (f i).colon (g j) :=
le_antisymm (le_infi $ λ i, le_infi $ λ j, colon_mono (infi_le _ _) (le_supr _ _))
(λ r H, mem_colon'.2 $ supr_le $ λ j, map_le_iff_le_comap.1 $ le_infi $ λ i,
map_le_iff_le_comap.2 $ mem_colon'.1 $ have _ := ((mem_infi _).1 H i),
have _ := ((mem_infi _).1 this j), this)
theorem smul_mem_smul {r} {n} (hr : r ∈ I) (hn : n ∈ N) : r • n ∈ I • N :=
(le_supr _ ⟨r, hr⟩ : _ ≤ I • N) ⟨n, hn, rfl⟩
theorem smul_le {P : submodule R M} : I • N ≤ P ↔ ∀ (r ∈ I) (n ∈ N), r • n ∈ P :=
⟨λ H r hr n hn, H $ smul_mem_smul hr hn,
λ H, supr_le $ λ r, map_le_iff_le_comap.2 $ λ n hn, H r.1 r.2 n hn⟩
@[elab_as_eliminator]
theorem smul_induction_on {p : M → Prop} {x} (H : x ∈ I • N)
(Hb : ∀ (r ∈ I) (n ∈ N), p (r • n)) (H0 : p 0)
(H1 : ∀ x y, p x → p y → p (x + y))
(H2 : ∀ (c:R) n, p n → p (c • n)) : p x :=
(@smul_le _ _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hb H
theorem mem_smul_span_singleton {I : ideal R} {m : M} {x : M} :
x ∈ I • span R ({m} : set M) ↔ ∃ y ∈ I, y • m = x :=
⟨λ hx, smul_induction_on hx
(λ r hri n hnm, let ⟨s, hs⟩ := mem_span_singleton.1 hnm in ⟨r * s, I.mul_mem_right hri, hs ▸ mul_smul r s m⟩)
⟨0, I.zero_mem, by rw [zero_smul]⟩
(λ m1 m2 ⟨y1, hyi1, hy1⟩ ⟨y2, hyi2, hy2⟩, ⟨y1 + y2, I.add_mem hyi1 hyi2, by rw [add_smul, hy1, hy2]⟩)
(λ c r ⟨y, hyi, hy⟩, ⟨c * y, I.mul_mem_left hyi, by rw [mul_smul, hy]⟩),
λ ⟨y, hyi, hy⟩, hy ▸ smul_mem_smul hyi (subset_span $ set.mem_singleton m)⟩
theorem smul_le_right : I • N ≤ N :=
smul_le.2 $ λ r hr n, N.smul_mem r
theorem smul_mono (hij : I ≤ J) (hnp : N ≤ P) : I • N ≤ J • P :=
smul_le.2 $ λ r hr n hn, smul_mem_smul (hij hr) (hnp hn)
theorem smul_mono_left (h : I ≤ J) : I • N ≤ J • N :=
smul_mono h (le_refl N)
theorem smul_mono_right (h : N ≤ P) : I • N ≤ I • P :=
smul_mono (le_refl I) h
variables (I J N P)
@[simp] theorem smul_bot : I • (⊥ : submodule R M) = ⊥ :=
eq_bot_iff.2 $ smul_le.2 $ λ r hri s hsb,
(submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hsb).symm ▸ smul_zero r
@[simp] theorem bot_smul : (⊥ : ideal R) • N = ⊥ :=
eq_bot_iff.2 $ smul_le.2 $ λ r hrb s hsi,
(submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hrb).symm ▸ zero_smul _ s
@[simp] theorem top_smul : (⊤ : ideal R) • N = N :=
le_antisymm smul_le_right $ λ r hri, one_smul R r ▸ smul_mem_smul mem_top hri
theorem smul_sup : I • (N ⊔ P) = I • N ⊔ I • P :=
le_antisymm (smul_le.2 $ λ r hri m hmnp, let ⟨n, hn, p, hp, hnpm⟩ := mem_sup.1 hmnp in
mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hri hp, hnpm ▸ (smul_add _ _ _).symm⟩)
(sup_le (smul_mono_right le_sup_left)
(smul_mono_right le_sup_right))
theorem sup_smul : (I ⊔ J) • N = I • N ⊔ J • N :=
le_antisymm (smul_le.2 $ λ r hrij n hn, let ⟨ri, hri, rj, hrj, hrijr⟩ := mem_sup.1 hrij in
mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hrj hn, hrijr ▸ (add_smul _ _ _).symm⟩)
(sup_le (smul_mono_left le_sup_left)
(smul_mono_left le_sup_right))
theorem smul_assoc : (I • J) • N = I • (J • N) :=
le_antisymm (smul_le.2 $ λ rs hrsij t htn,
smul_induction_on hrsij
(λ r hr s hs, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ smul_mem_smul hr (smul_mem_smul hs htn))
((zero_smul R t).symm ▸ submodule.zero_mem _)
(λ x y, (add_smul x y t).symm ▸ submodule.add_mem _)
(λ r s h, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ submodule.smul_mem _ _ h))
(smul_le.2 $ λ r hr sn hsn, suffices J • N ≤ submodule.comap (r • linear_map.id) ((I • J) • N), from this hsn,
smul_le.2 $ λ s hs n hn, show r • (s • n) ∈ (I • J) • N, from mul_smul r s n ▸ smul_mem_smul (smul_mem_smul hr hs) hn)
variables (S : set R) (T : set M)
theorem span_smul_span : (ideal.span S) • (span R T) =
span R (⋃ (s ∈ S) (t ∈ T), {s • t}) :=
le_antisymm (smul_le.2 $ λ r hrS n hnT, span_induction hrS
(λ r hrS, span_induction hnT
(λ n hnT, subset_span $ set.mem_bUnion hrS $
set.mem_bUnion hnT $ set.mem_singleton _)
((smul_zero r : r • 0 = (0:M)).symm ▸ submodule.zero_mem _)
(λ x y, (smul_add r x y).symm ▸ submodule.add_mem _)
(λ c m, by rw [smul_smul, mul_comm, mul_smul]; exact submodule.smul_mem _ _))
((zero_smul R n).symm ▸ submodule.zero_mem _)
(λ r s, (add_smul r s n).symm ▸ submodule.add_mem _)
(λ c r, by rw [smul_eq_mul, mul_smul]; exact submodule.smul_mem _ _)) $
span_le.2 $ set.bUnion_subset $ λ r hrS, set.bUnion_subset $ λ n hnT, set.singleton_subset_iff.2 $
smul_mem_smul (subset_span hrS) (subset_span hnT)
end submodule
namespace ideal
section chinese_remainder
variables {R : Type u} [comm_ring R] {ι : Type v}
theorem exists_sub_one_mem_and_mem (s : finset ι) {f : ι → ideal R}
(hf : ∀ i ∈ s, ∀ j ∈ s, i ≠ j → f i ⊔ f j = ⊤) (i : ι) (his : i ∈ s) :
∃ r : R, r - 1 ∈ f i ∧ ∀ j ∈ s, j ≠ i → r ∈ f j :=
begin
have : ∀ j ∈ s, j ≠ i → ∃ r : R, ∃ H : r - 1 ∈ f i, r ∈ f j,
{ intros j hjs hji, specialize hf i his j hjs hji.symm,
rw [eq_top_iff_one, submodule.mem_sup] at hf,
rcases hf with ⟨r, hri, s, hsj, hrs⟩, refine ⟨1 - r, _, _⟩,
{ rw [sub_right_comm, sub_self, zero_sub], exact (f i).neg_mem hri },
{ rw [← hrs, add_sub_cancel'], exact hsj } },
classical,
have : ∃ g : ι → R, (∀ j, g j - 1 ∈ f i) ∧ ∀ j ∈ s, j ≠ i → g j ∈ f j,
{ choose g hg1 hg2,
refine ⟨λ j, if H : j ∈ s ∧ j ≠ i then g j H.1 H.2 else 1, λ j, _, λ j, _⟩,
{ split_ifs with h, { apply hg1 }, rw sub_self, exact (f i).zero_mem },
{ intros hjs hji, rw dif_pos, { apply hg2 }, exact ⟨hjs, hji⟩ } },
rcases this with ⟨g, hgi, hgj⟩, use (s.erase i).prod g, split,
{ rw [← quotient.eq, quotient.mk_one, quotient.mk_prod],
apply finset.prod_eq_one, intros, rw [← quotient.mk_one, quotient.eq], apply hgi },
intros j hjs hji, rw [← quotient.eq_zero_iff_mem, quotient.mk_prod],
refine finset.prod_eq_zero (finset.mem_erase_of_ne_of_mem hji hjs) _,
rw quotient.eq_zero_iff_mem, exact hgj j hjs hji
end
theorem exists_sub_mem [fintype ι] {f : ι → ideal R}
(hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) (g : ι → R) :
∃ r : R, ∀ i, r - g i ∈ f i :=
begin
have : ∃ φ : ι → R, (∀ i, φ i - 1 ∈ f i) ∧ (∀ i j, i ≠ j → φ i ∈ f j),
{ have := exists_sub_one_mem_and_mem (finset.univ : finset ι) (λ i _ j _ hij, hf i j hij),
choose φ hφ,
existsi λ i, φ i (finset.mem_univ i),
exact ⟨λ i, (hφ i _).1, λ i j hij, (hφ i _).2 j (finset.mem_univ j) hij.symm⟩ },
rcases this with ⟨φ, hφ1, hφ2⟩,
use finset.univ.sum (λ i, g i * φ i),
intros i,
rw [← quotient.eq, quotient.mk_sum],
refine eq.trans (finset.sum_eq_single i _ _) _,
{ intros j _ hji, rw quotient.eq_zero_iff_mem, exact (f i).mul_mem_left (hφ2 j i hji) },
{ intros hi, exact (hi $ finset.mem_univ i).elim },
specialize hφ1 i, rw [← quotient.eq, quotient.mk_one] at hφ1,
rw [quotient.mk_mul, hφ1, mul_one]
end
def quotient_inf_to_pi_quotient (f : ι → ideal R) :
(⨅ i, f i).quotient →+* Π i, (f i).quotient :=
begin
refine quotient.lift (⨅ i, f i) _ _,
{ convert @@pi.ring_hom (λ i, quotient (f i)) (λ i, ring.to_semiring) ring.to_semiring
(λ i, quotient.mk_hom (f i)) },
{ intros r hr,
rw submodule.mem_infi at hr,
ext i,
exact quotient.eq_zero_iff_mem.2 (hr i) }
end
theorem bijective_quotient_inf_to_pi_quotient [fintype ι] {f : ι → ideal R}
(hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) :
function.bijective (quotient_inf_to_pi_quotient f) :=
⟨λ x y, quotient.induction_on₂' x y $ λ r s hrs, quotient.eq.2 $
(submodule.mem_infi _).2 $ λ i, quotient.eq.1 $
show quotient_inf_to_pi_quotient f (quotient.mk' r) i = _, by rw hrs; refl,
λ g, let ⟨r, hr⟩ := exists_sub_mem hf (λ i, quotient.out' (g i)) in
⟨quotient.mk _ r, funext $ λ i, quotient.out_eq' (g i) ▸ quotient.eq.2 (hr i)⟩⟩
/-- Chinese Remainder Theorem. Eisenbud Ex.2.6. Similar to Atiyah-Macdonald 1.10 and Stacks 00DT -/
noncomputable def quotient_inf_ring_equiv_pi_quotient [fintype ι] (f : ι → ideal R)
(hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) :
(⨅ i, f i).quotient ≃+* Π i, (f i).quotient :=
{ .. equiv.of_bijective (bijective_quotient_inf_to_pi_quotient hf),
.. quotient_inf_to_pi_quotient f }
end chinese_remainder
section mul_and_radical
variables {R : Type u} [comm_ring R]
variables {I J K L: ideal R}
instance : has_mul (ideal R) := ⟨(•)⟩
theorem mul_mem_mul {r s} (hr : r ∈ I) (hs : s ∈ J) : r * s ∈ I * J :=
submodule.smul_mem_smul hr hs
theorem mul_mem_mul_rev {r s} (hr : r ∈ I) (hs : s ∈ J) : s * r ∈ I * J :=
mul_comm r s ▸ mul_mem_mul hr hs
theorem mul_le : I * J ≤ K ↔ ∀ (r ∈ I) (s ∈ J), r * s ∈ K :=
submodule.smul_le
variables (I J K)
protected theorem mul_comm : I * J = J * I :=
le_antisymm (mul_le.2 $ λ r hrI s hsJ, mul_mem_mul_rev hsJ hrI)
(mul_le.2 $ λ r hrJ s hsI, mul_mem_mul_rev hsI hrJ)
protected theorem mul_assoc : (I * J) * K = I * (J * K) :=
submodule.smul_assoc I J K
theorem span_mul_span (S T : set R) : span S * span T =
span ⋃ (s ∈ S) (t ∈ T), {s * t} :=
submodule.span_smul_span S T
variables {I J K}
theorem mul_le_inf : I * J ≤ I ⊓ J :=
mul_le.2 $ λ r hri s hsj, ⟨I.mul_mem_right hri, J.mul_mem_left hsj⟩
theorem mul_eq_inf_of_coprime (h : I ⊔ J = ⊤) : I * J = I ⊓ J :=
le_antisymm mul_le_inf $ λ r ⟨hri, hrj⟩,
let ⟨s, hsi, t, htj, hst⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in
mul_one r ▸ hst ▸ (mul_add r s t).symm ▸ ideal.add_mem (I * J) (mul_mem_mul_rev hsi hrj) (mul_mem_mul hri htj)
variables (I)
theorem mul_bot : I * ⊥ = ⊥ :=
submodule.smul_bot I
theorem bot_mul : ⊥ * I = ⊥ :=
submodule.bot_smul I
theorem mul_top : I * ⊤ = I :=
ideal.mul_comm ⊤ I ▸ submodule.top_smul I
theorem top_mul : ⊤ * I = I :=
submodule.top_smul I
variables {I}
theorem mul_mono (hik : I ≤ K) (hjl : J ≤ L) : I * J ≤ K * L :=
submodule.smul_mono hik hjl
theorem mul_mono_left (h : I ≤ J) : I * K ≤ J * K :=
submodule.smul_mono_left h
theorem mul_mono_right (h : J ≤ K) : I * J ≤ I * K :=
submodule.smul_mono_right h
variables (I J K)
theorem mul_sup : I * (J ⊔ K) = I * J ⊔ I * K :=
submodule.smul_sup I J K
theorem sup_mul : (I ⊔ J) * K = I * K ⊔ J * K :=
submodule.sup_smul I J K
variables {I J K}
lemma pow_le_pow {m n : ℕ} (h : m ≤ n) :
I^n ≤ I^m :=
begin
cases nat.exists_eq_add_of_le h with k hk,
rw [hk, pow_add],
exact le_trans (mul_le_inf) (inf_le_left)
end
/-- The radical of an ideal `I` consists of the elements `r` such that `r^n ∈ I` for some `n`. -/
def radical (I : ideal R) : ideal R :=
{ carrier := { r | ∃ n : ℕ, r ^ n ∈ I },
zero := ⟨1, (pow_one (0:R)).symm ▸ I.zero_mem⟩,
add := λ x y ⟨m, hxmi⟩ ⟨n, hyni⟩, ⟨m + n,
(add_pow x y (m + n)).symm ▸ I.sum_mem $
show ∀ c ∈ finset.range (nat.succ (m + n)), x ^ c * y ^ (m + n - c) * (nat.choose (m + n) c) ∈ I,
from λ c hc, or.cases_on (le_total c m)
(λ hcm, I.mul_mem_right $ I.mul_mem_left $ nat.add_comm n m ▸ (nat.add_sub_assoc hcm n).symm ▸
(pow_add y n (m-c)).symm ▸ I.mul_mem_right hyni)
(λ hmc, I.mul_mem_right $ I.mul_mem_right $ nat.add_sub_cancel' hmc ▸
(pow_add x m (c-m)).symm ▸ I.mul_mem_right hxmi)⟩,
smul := λ r s ⟨n, hsni⟩, ⟨n, show (r * s)^n ∈ I,
from (mul_pow r s n).symm ▸ I.mul_mem_left hsni⟩ }
theorem le_radical : I ≤ radical I :=
λ r hri, ⟨1, (pow_one r).symm ▸ hri⟩
variables (R)
theorem radical_top : (radical ⊤ : ideal R) = ⊤ :=
(eq_top_iff_one _).2 ⟨0, submodule.mem_top⟩
variables {R}
theorem radical_mono (H : I ≤ J) : radical I ≤ radical J :=
λ r ⟨n, hrni⟩, ⟨n, H hrni⟩
variables (I)
theorem radical_idem : radical (radical I) = radical I :=
le_antisymm (λ r ⟨n, k, hrnki⟩, ⟨n * k, (pow_mul r n k).symm ▸ hrnki⟩) le_radical
variables {I}
theorem radical_eq_top : radical I = ⊤ ↔ I = ⊤ :=
⟨λ h, (eq_top_iff_one _).2 $ let ⟨n, hn⟩ := (eq_top_iff_one _).1 h in
@one_pow R _ n ▸ hn, λ h, h.symm ▸ radical_top R⟩
theorem is_prime.radical (H : is_prime I) : radical I = I :=
le_antisymm (λ r ⟨n, hrni⟩, H.mem_of_pow_mem n hrni) le_radical
variables (I J)
theorem radical_sup : radical (I ⊔ J) = radical (radical I ⊔ radical J) :=
le_antisymm (radical_mono $ sup_le_sup le_radical le_radical) $
λ r ⟨n, hrnij⟩, let ⟨s, hs, t, ht, hst⟩ := submodule.mem_sup.1 hrnij in
@radical_idem _ _ (I ⊔ J) ▸ ⟨n, hst ▸ ideal.add_mem _
(radical_mono le_sup_left hs) (radical_mono le_sup_right ht)⟩
theorem radical_inf : radical (I ⊓ J) = radical I ⊓ radical J :=
le_antisymm (le_inf (radical_mono inf_le_left) (radical_mono inf_le_right))
(λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ I.mul_mem_right hrm,
(pow_add r m n).symm ▸ J.mul_mem_left hrn⟩)
theorem radical_mul : radical (I * J) = radical I ⊓ radical J :=
le_antisymm (radical_inf I J ▸ radical_mono $ @mul_le_inf _ _ I J)
(λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ mul_mem_mul hrm hrn⟩)
variables {I J}
theorem is_prime.radical_le_iff (hj : is_prime J) :
radical I ≤ J ↔ I ≤ J :=
⟨le_trans le_radical, λ hij r ⟨n, hrni⟩, hj.mem_of_pow_mem n $ hij hrni⟩
theorem radical_eq_Inf (I : ideal R) :
radical I = Inf { J : ideal R | I ≤ J ∧ is_prime J } :=
le_antisymm (le_Inf $ λ J hJ, hJ.2.radical_le_iff.2 hJ.1) $
λ r hr, classical.by_contradiction $ λ hri,
let ⟨m, (hrm : r ∉ radical m), him, hm⟩ := zorn.zorn_partial_order₀ {K : ideal R | r ∉ radical K}
(λ c hc hcc y hyc, ⟨Sup c, λ ⟨n, hrnc⟩, let ⟨y, hyc, hrny⟩ :=
(submodule.mem_Sup_of_directed ⟨y, hyc⟩ hcc.directed_on).1 hrnc in hc hyc ⟨n, hrny⟩,
λ z, le_Sup⟩) I hri in
have ∀ x ∉ m, r ∈ radical (m ⊔ span {x}) := λ x hxm, classical.by_contradiction $ λ hrmx, hxm $
hm (m ⊔ span {x}) hrmx le_sup_left ▸ (le_sup_right : _ ≤ m ⊔ span {x}) (subset_span $ set.mem_singleton _),
have is_prime m, from ⟨by rintro rfl; rw radical_top at hrm; exact hrm trivial,
λ x y hxym, classical.or_iff_not_imp_left.2 $ λ hxm, classical.by_contradiction $ λ hym,
let ⟨n, hrn⟩ := this _ hxm, ⟨p, hpm, q, hq, hpqrn⟩ := submodule.mem_sup.1 hrn, ⟨c, hcxq⟩ := mem_span_singleton'.1 hq in
let ⟨k, hrk⟩ := this _ hym, ⟨f, hfm, g, hg, hfgrk⟩ := submodule.mem_sup.1 hrk, ⟨d, hdyg⟩ := mem_span_singleton'.1 hg in
hrm ⟨n + k, by rw [pow_add, ← hpqrn, ← hcxq, ← hfgrk, ← hdyg, add_mul, mul_add (c*x), mul_assoc c x (d*y), mul_left_comm x, ← mul_assoc];
refine m.add_mem (m.mul_mem_right hpm) (m.add_mem (m.mul_mem_left hfm) (m.mul_mem_left hxym))⟩⟩,
hrm $ this.radical.symm ▸ (Inf_le ⟨him, this⟩ : Inf {J : ideal R | I ≤ J ∧ is_prime J} ≤ m) hr
instance : comm_semiring (ideal R) := submodule.comm_semiring
@[simp] lemma add_eq_sup : I + J = I ⊔ J := rfl
@[simp] lemma zero_eq_bot : (0 : ideal R) = ⊥ := rfl
@[simp] lemma one_eq_top : (1 : ideal R) = ⊤ :=
by erw [submodule.one_eq_map_top, submodule.map_id]
variables (I)
theorem radical_pow (n : ℕ) (H : n > 0) : radical (I^n) = radical I :=
nat.rec_on n (not.elim dec_trivial) (λ n ih H,
or.cases_on (lt_or_eq_of_le $ nat.le_of_lt_succ H)
(λ H, calc radical (I^(n+1))
= radical I ⊓ radical (I^n) : radical_mul _ _
... = radical I ⊓ radical I : by rw ih H
... = radical I : inf_idem)
(λ H, H ▸ (pow_one I).symm ▸ rfl)) H
end mul_and_radical
section map_and_comap
variables {R : Type u} {S : Type v} [comm_ring R] [comm_ring S]
variables (f : R →+* S)
variables {I J : ideal R} {K L : ideal S}
def map (I : ideal R) : ideal S :=
span (f '' I)
/-- `I.comap f` is the preimage of `I` under `f`. -/
def comap (I : ideal S) : ideal R :=
{ carrier := f ⁻¹' I,
zero := by simp only [set.mem_preimage, f.map_zero, I.mem_coe, I.zero_mem],
add := λ x y hx hy, show f (x + y) ∈ I, by { rw f.map_add, exact I.add_mem hx hy },
smul := λ c x hx, show f (c * x) ∈ I, by { rw f.map_mul, exact I.mul_mem_left hx } }
variables {f}
theorem map_mono (h : I ≤ J) : map f I ≤ map f J :=
span_mono $ set.image_subset _ h
theorem mem_map_of_mem {x} (h : x ∈ I) : f x ∈ map f I :=
subset_span ⟨x, h, rfl⟩
theorem map_le_iff_le_comap :
map f I ≤ K ↔ I ≤ comap f K :=
span_le.trans set.image_subset_iff
@[simp] theorem mem_comap {x} : x ∈ comap f K ↔ f x ∈ K := iff.rfl
theorem comap_mono (h : K ≤ L) : comap f K ≤ comap f L :=
set.preimage_mono h
variables (f)
theorem comap_ne_top (hK : K ≠ ⊤) : comap f K ≠ ⊤ :=
(ne_top_iff_one _).2 $ by rw [mem_comap, f.map_one];
exact (ne_top_iff_one _).1 hK
instance is_prime.comap [hK : K.is_prime] : (comap f K).is_prime :=
⟨comap_ne_top _ hK.1, λ x y,
by simp only [mem_comap, f.map_mul]; apply hK.2⟩
variables (I J K L)
theorem map_bot : map f ⊥ = ⊥ :=
le_antisymm (map_le_iff_le_comap.2 bot_le) bot_le
theorem map_top : map f ⊤ = ⊤ :=
(eq_top_iff_one _).2 $ subset_span ⟨1, trivial, f.map_one⟩
theorem comap_top : comap f ⊤ = ⊤ :=
(eq_top_iff_one _).2 trivial
theorem map_sup : map f (I ⊔ J) = map f I ⊔ map f J :=
le_antisymm (map_le_iff_le_comap.2 $ sup_le
(map_le_iff_le_comap.1 le_sup_left)
(map_le_iff_le_comap.1 le_sup_right))
(sup_le (map_mono le_sup_left) (map_mono le_sup_right))
theorem map_mul : map f (I * J) = map f I * map f J :=
le_antisymm (map_le_iff_le_comap.2 $ mul_le.2 $ λ r hri s hsj,
show f (r * s) ∈ _, by rw f.map_mul;
exact mul_mem_mul (mem_map_of_mem hri) (mem_map_of_mem hsj))
(trans_rel_right _ (span_mul_span _ _) $ span_le.2 $
set.bUnion_subset $ λ i ⟨r, hri, hfri⟩,
set.bUnion_subset $ λ j ⟨s, hsj, hfsj⟩,
set.singleton_subset_iff.2 $ hfri ▸ hfsj ▸
by rw [← f.map_mul];
exact mem_map_of_mem (mul_mem_mul hri hsj))
theorem comap_inf : comap f (K ⊓ L) = comap f K ⊓ comap f L := rfl
theorem comap_radical : comap f (radical K) = radical (comap f K) :=
le_antisymm (λ r ⟨n, hfrnk⟩, ⟨n, show f (r ^ n) ∈ K,
from (f.map_pow r n).symm ▸ hfrnk⟩)
(λ r ⟨n, hfrnk⟩, ⟨n, f.map_pow r n ▸ hfrnk⟩)
@[simp] lemma map_quotient_self :
map (quotient.mk_hom I) I = ⊥ :=
eq_bot_iff.2 $ ideal.map_le_iff_le_comap.2 $ λ x hx,
(submodule.mem_bot I.quotient).2 $ ideal.quotient.eq_zero_iff_mem.2 hx
variables {I J K L}
theorem map_inf_le : map f (I ⊓ J) ≤ map f I ⊓ map f J :=
map_le_iff_le_comap.2 $ (comap_inf f (map f I) (map f J)).symm ▸
inf_le_inf (map_le_iff_le_comap.1 $ le_refl _) (map_le_iff_le_comap.1 $ le_refl _)
theorem map_radical_le : map f (radical I) ≤ radical (map f I) :=
map_le_iff_le_comap.2 $ λ r ⟨n, hrni⟩, ⟨n, f.map_pow r n ▸ mem_map_of_mem hrni⟩
theorem le_comap_sup : comap f K ⊔ comap f L ≤ comap f (K ⊔ L) :=
map_le_iff_le_comap.1 $ (map_sup f (comap f K) (comap f L)).symm ▸
sup_le_sup (map_le_iff_le_comap.2 $ le_refl _) (map_le_iff_le_comap.2 $ le_refl _)
theorem le_comap_mul : comap f K * comap f L ≤ comap f (K * L) :=
map_le_iff_le_comap.1 $ (map_mul f (comap f K) (comap f L)).symm ▸
mul_mono (map_le_iff_le_comap.2 $ le_refl _) (map_le_iff_le_comap.2 $ le_refl _)
section surjective
variables (hf : function.surjective f)
include hf
theorem map_comap_of_surjective (I : ideal S) :
map f (comap f I) = I :=
le_antisymm (map_le_iff_le_comap.2 (le_refl _))
(λ s hsi, let ⟨r, hfrs⟩ := hf s in
hfrs ▸ (mem_map_of_mem $ show f r ∈ I, from hfrs.symm ▸ hsi))
theorem mem_image_of_mem_map_of_surjective {I : ideal R} {y}
(H : y ∈ map f I) : y ∈ f '' I :=
submodule.span_induction H (λ _, id) ⟨0, I.zero_mem, f.map_zero⟩
(λ y1 y2 ⟨x1, hx1i, hxy1⟩ ⟨x2, hx2i, hxy2⟩, ⟨x1 + x2, I.add_mem hx1i hx2i, hxy1 ▸ hxy2 ▸ f.map_add _ _⟩)
(λ c y ⟨x, hxi, hxy⟩, let ⟨d, hdc⟩ := hf c in ⟨d • x, I.smul_mem _ hxi, hdc ▸ hxy ▸ f.map_mul _ _⟩)
theorem comap_map_of_surjective (I : ideal R) :
comap f (map f I) = I ⊔ comap f ⊥ :=
le_antisymm (assume r h, let ⟨s, hsi, hfsr⟩ := mem_image_of_mem_map_of_surjective f hf h in
submodule.mem_sup.2 ⟨s, hsi, r - s, (submodule.mem_bot S).2 $ by rw [f.map_sub, hfsr, sub_self],
add_sub_cancel'_right s r⟩)
(sup_le (map_le_iff_le_comap.1 (le_refl _)) (comap_mono bot_le))
/-- Correspondence theorem -/
def order_iso_of_surjective :
((≤) : ideal S → ideal S → Prop) ≃o
((≤) : { p : ideal R // comap f ⊥ ≤ p } → { p : ideal R // comap f ⊥ ≤ p } → Prop) :=
{ to_fun := λ J, ⟨comap f J, comap_mono bot_le⟩,
inv_fun := λ I, map f I.1,
left_inv := λ J, map_comap_of_surjective f hf J,
right_inv := λ I, subtype.eq $ show comap f (map f I.1) = I.1,
from (comap_map_of_surjective f hf I).symm ▸ le_antisymm
(sup_le (le_refl _) I.2) le_sup_left,
ord' := λ I1 I2, ⟨comap_mono, λ H, map_comap_of_surjective f hf I1 ▸
map_comap_of_surjective f hf I2 ▸ map_mono H⟩ }
def le_order_embedding_of_surjective :
((≤) : ideal S → ideal S → Prop) ≼o ((≤) : ideal R → ideal R → Prop) :=
(order_iso_of_surjective f hf).to_order_embedding.trans (subtype.order_embedding _ _)
def lt_order_embedding_of_surjective :
((<) : ideal S → ideal S → Prop) ≼o ((<) : ideal R → ideal R → Prop) :=
(le_order_embedding_of_surjective f hf).lt_embedding_of_le_embedding
end surjective
end map_and_comap
end ideal
namespace ring_hom
variables {R : Type u} {S : Type v} [comm_ring R]
section comm_ring
variables [comm_ring S] (f : R →+* S)
/-- Kernel of a ring homomorphism as an ideal of the domain. -/
def ker : ideal R := ideal.comap f ⊥
/-- An element is in the kernel if and only if it maps to zero.-/
lemma mem_ker {r} : r ∈ ker f ↔ f r = 0 :=
by rw [ker, ideal.mem_comap, submodule.mem_bot]
lemma ker_eq : ((ker f) : set R) = is_add_group_hom.ker f := rfl
lemma inj_iff_ker_eq_bot : function.injective f ↔ ker f = ⊥ :=
by rw [←submodule.ext'_iff, ker_eq]; exact is_add_group_hom.inj_iff_trivial_ker f
lemma ker_eq_bot_iff_eq_zero : ker f = ⊥ ↔ ∀ x, f x = 0 → x = 0 :=
by rw [←submodule.ext'_iff, ker_eq]; exact is_add_group_hom.trivial_ker_iff_eq_zero f
end comm_ring
/-- If the target is not the zero ring, then one is not in the kernel.-/
lemma not_one_mem_ker [nonzero_comm_ring S] (f : R →+* S) : (1:R) ∉ ker f :=
by { rw [mem_ker, f.map_one], exact one_ne_zero }
/-- The kernel of a homomorphism to an integral domain is a prime ideal.-/
lemma ker_is_prime [integral_domain S] (f : R →+* S) :
(ker f).is_prime :=
⟨by { rw [ne.def, ideal.eq_top_iff_one], exact not_one_mem_ker f },
λ x y, by simpa only [mem_ker, f.map_mul] using eq_zero_or_eq_zero_of_mul_eq_zero⟩
end ring_hom
namespace submodule
variables {R : Type u} {M : Type v}
variables [comm_ring R] [add_comm_group M] [module R M]
-- It is even a semialgebra. But those aren't in mathlib yet.
instance : semimodule (ideal R) (submodule R M) :=
{ smul_add := smul_sup,
add_smul := sup_smul,
mul_smul := smul_assoc,
one_smul := by simp,
zero_smul := bot_smul,
smul_zero := smul_bot }
end submodule
|
f42f5a71f1c2dc49f9401a7c0314d32ec41a6c64 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/set/intervals/surj_on.lean | f6c18f4202b32c2123c98ca3d5809a85907c3fd6 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,930 | lean | /-
Copyright (c) 2020 Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Heather Macbeth
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.set.intervals.basic
import Mathlib.data.set.function
import Mathlib.PostPort
universes u_1 u_2
namespace Mathlib
/-!
# Monotone surjective functions are surjective on intervals
A monotone surjective function sends any interval in the domain onto the interval with corresponding
endpoints in the range. This is expressed in this file using `set.surj_on`, and provided for all
permutations of interval endpoints.
-/
theorem surj_on_Ioo_of_monotone_surjective {α : Type u_1} {β : Type u_2} [linear_order α] [partial_order β] {f : α → β} (h_mono : monotone f) (h_surj : function.surjective f) (a : α) (b : α) : set.surj_on f (set.Ioo a b) (set.Ioo (f a) (f b)) := sorry
theorem surj_on_Ico_of_monotone_surjective {α : Type u_1} {β : Type u_2} [linear_order α] [partial_order β] {f : α → β} (h_mono : monotone f) (h_surj : function.surjective f) (a : α) (b : α) : set.surj_on f (set.Ico a b) (set.Ico (f a) (f b)) := sorry
theorem surj_on_Ioc_of_monotone_surjective {α : Type u_1} {β : Type u_2} [linear_order α] [partial_order β] {f : α → β} (h_mono : monotone f) (h_surj : function.surjective f) (a : α) (b : α) : set.surj_on f (set.Ioc a b) (set.Ioc (f a) (f b)) := sorry
-- to see that the hypothesis `a ≤ b` is necessary, consider a constant function
theorem surj_on_Icc_of_monotone_surjective {α : Type u_1} {β : Type u_2} [linear_order α] [partial_order β] {f : α → β} (h_mono : monotone f) (h_surj : function.surjective f) {a : α} {b : α} (hab : a ≤ b) : set.surj_on f (set.Icc a b) (set.Icc (f a) (f b)) := sorry
theorem surj_on_Ioi_of_monotone_surjective {α : Type u_1} {β : Type u_2} [linear_order α] [partial_order β] {f : α → β} (h_mono : monotone f) (h_surj : function.surjective f) (a : α) : set.surj_on f (set.Ioi a) (set.Ioi (f a)) := sorry
theorem surj_on_Iio_of_monotone_surjective {α : Type u_1} {β : Type u_2} [linear_order α] [partial_order β] {f : α → β} (h_mono : monotone f) (h_surj : function.surjective f) (a : α) : set.surj_on f (set.Iio a) (set.Iio (f a)) :=
surj_on_Ioi_of_monotone_surjective (monotone.order_dual h_mono) h_surj a
theorem surj_on_Ici_of_monotone_surjective {α : Type u_1} {β : Type u_2} [linear_order α] [partial_order β] {f : α → β} (h_mono : monotone f) (h_surj : function.surjective f) (a : α) : set.surj_on f (set.Ici a) (set.Ici (f a)) := sorry
theorem surj_on_Iic_of_monotone_surjective {α : Type u_1} {β : Type u_2} [linear_order α] [partial_order β] {f : α → β} (h_mono : monotone f) (h_surj : function.surjective f) (a : α) : set.surj_on f (set.Iic a) (set.Iic (f a)) :=
surj_on_Ici_of_monotone_surjective (monotone.order_dual h_mono) h_surj a
|
d0d9f323a844c7be28b0be5edfc350a63bf110f9 | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/run/list_elab1.lean | 8da8526facfe71c85e08de6aba8e154736d54706 | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,125 | 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
----------------------------------------------------------------------------------------------------
-- Theory list
-- ===========
--
-- Basic properties of lists.
import data.nat
using nat eq_proofs
set_option unifier.expensive true
inductive list (T : Type) : Type :=
| nil {} : list T
| cons : T → list T → list T
theorem list_induction_on {T : Type} {P : list T → Prop} (l : list T) (Hnil : P nil)
(Hind : forall x : T, forall l : list T, forall H : P l, P (cons x l)) : P l :=
list_rec Hnil Hind l
definition concat {T : Type} (s t : list T) : list T :=
list_rec t (fun x : T, fun l : list T, fun u : list T, cons x u) s
theorem concat_nil {T : Type} (t : list T) : concat t nil = t :=
list_induction_on t (refl (concat nil nil))
(take (x : T) (l : list T) (H : concat l nil = l),
H ▸ (refl (concat (cons x l) nil)))
|
73d1e1cdf61dc3bd9737fa14aaf7afde4bacc458 | 8cb37a089cdb4af3af9d8bf1002b417e407a8e9e | /library/init/meta/smt/ematch.lean | 5ba0fa3a1388d296ef2e7525b4ff2e54ee3ab71b | [
"Apache-2.0"
] | permissive | kbuzzard/lean | ae3c3db4bb462d750dbf7419b28bafb3ec983ef7 | ed1788fd674bb8991acffc8fca585ec746711928 | refs/heads/master | 1,620,983,366,617 | 1,618,937,600,000 | 1,618,937,600,000 | 359,886,396 | 1 | 0 | Apache-2.0 | 1,618,936,987,000 | 1,618,936,987,000 | null | UTF-8 | Lean | false | false | 7,383 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.smt.congruence_closure
import init.meta.attribute init.meta.simp_tactic
import init.meta.interactive_base init.meta.derive
open tactic
/-- Heuristic instantiation lemma -/
meta constant hinst_lemma : Type
meta constant hinst_lemmas : Type
/-- `mk_core m e as_simp`, m is used to decide which definitions will be unfolded in patterns.
If as_simp is tt, then this tactic will try to use the left-hand-side of the conclusion
as a pattern. -/
meta constant hinst_lemma.mk_core : transparency → expr → bool → tactic hinst_lemma
meta constant hinst_lemma.mk_from_decl_core : transparency → name → bool → tactic hinst_lemma
meta constant hinst_lemma.pp : hinst_lemma → tactic format
meta constant hinst_lemma.id : hinst_lemma → name
meta instance : has_to_tactic_format hinst_lemma :=
⟨hinst_lemma.pp⟩
meta def hinst_lemma.mk (h : expr) : tactic hinst_lemma :=
hinst_lemma.mk_core reducible h ff
meta def hinst_lemma.mk_from_decl (h : name) : tactic hinst_lemma :=
hinst_lemma.mk_from_decl_core reducible h ff
meta constant hinst_lemmas.mk : hinst_lemmas
meta constant hinst_lemmas.add : hinst_lemmas → hinst_lemma → hinst_lemmas
meta constant hinst_lemmas.fold {α : Type} : hinst_lemmas → α → (hinst_lemma → α → α) → α
meta constant hinst_lemmas.merge : hinst_lemmas → hinst_lemmas → hinst_lemmas
meta def mk_hinst_singleton : hinst_lemma → hinst_lemmas :=
hinst_lemmas.add hinst_lemmas.mk
meta def hinst_lemmas.pp (s : hinst_lemmas) : tactic format :=
let tac := s.fold (return format.nil)
(λ h tac, do
hpp ← h.pp,
r ← tac,
if r.is_nil then return hpp
else return format!"{r},\n{hpp}")
in do
r ← tac,
return $ format.cbrace (format.group r)
meta instance : has_to_tactic_format hinst_lemmas :=
⟨hinst_lemmas.pp⟩
open tactic
private meta def add_lemma (m : transparency) (as_simp : bool) (h : name) (hs : hinst_lemmas) : tactic hinst_lemmas :=
do h ← hinst_lemma.mk_from_decl_core m h as_simp, return $ hs.add h
meta def to_hinst_lemmas_core (m : transparency) : bool → list name → hinst_lemmas → tactic hinst_lemmas
| as_simp [] hs := return hs
| as_simp (n::ns) hs :=
let add n := add_lemma m as_simp n hs >>= to_hinst_lemmas_core as_simp ns
in do
/- First check if n is the name of a function with equational lemmas associated with it -/
eqns ← tactic.get_eqn_lemmas_for tt n,
match eqns with
| [] := do
/- n is not the name of a function definition or it does not have equational lemmas, then check if it is a lemma -/
add n
| _ := do
p ← is_prop_decl n,
if p then add n /- n is a proposition -/
else do
/- Add equational lemmas to resulting hinst_lemmas -/
new_hs ← to_hinst_lemmas_core tt eqns hs,
to_hinst_lemmas_core as_simp ns new_hs
end
meta def mk_hinst_lemma_attr_core (attr_name : name) (as_simp : bool) : command :=
do let t := `(user_attribute hinst_lemmas),
let v := `({name := attr_name,
descr := "hinst_lemma attribute",
after_set := some $ λ n _ _,
to_hinst_lemmas_core reducible as_simp [n] hinst_lemmas.mk >> skip <|>
fail format!"invalid ematch lemma '{n}'",
-- allow unsetting
before_unset := some $ λ _ _, skip,
cache_cfg := {
mk_cache := λ ns, to_hinst_lemmas_core reducible as_simp ns hinst_lemmas.mk,
dependencies := [`reducibility]}} : user_attribute hinst_lemmas),
add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff),
attribute.register attr_name
meta def mk_hinst_lemma_attrs_core (as_simp : bool) : list name → command
| [] := skip
| (n::ns) :=
(mk_hinst_lemma_attr_core n as_simp >> mk_hinst_lemma_attrs_core ns)
<|>
(do type ← infer_type (expr.const n []),
let expected := `(user_attribute),
(is_def_eq type expected
<|> fail format!"failed to create hinst_lemma attribute '{n}', declaration already exists and has different type."),
mk_hinst_lemma_attrs_core ns)
meta def merge_hinst_lemma_attrs (m : transparency) (as_simp : bool) : list name → hinst_lemmas → tactic hinst_lemmas
| [] hs := return hs
| (attr::attrs) hs := do
ns ← attribute.get_instances attr,
new_hs ← to_hinst_lemmas_core m as_simp ns hs,
merge_hinst_lemma_attrs attrs new_hs
/--
Create a new "cached" attribute (attr_name : user_attribute hinst_lemmas).
It also creates "cached" attributes for each attr_names and simp_attr_names if they have not been defined
yet. Moreover, the hinst_lemmas for attr_name will be the union of the lemmas tagged with
attr_name, attrs_name, and simp_attr_names.
For the ones in simp_attr_names, we use the left-hand-side of the conclusion as the pattern.
-/
meta def mk_hinst_lemma_attr_set (attr_name : name) (attr_names : list name) (simp_attr_names : list name) : command :=
do mk_hinst_lemma_attrs_core ff attr_names,
mk_hinst_lemma_attrs_core tt simp_attr_names,
let t := `(user_attribute hinst_lemmas),
let v := `({name := attr_name,
descr := "hinst_lemma attribute set",
after_set := some $ λ n _ _,
to_hinst_lemmas_core reducible ff [n] hinst_lemmas.mk >> skip <|>
fail format!"invalid ematch lemma '{n}'",
-- allow unsetting
before_unset := some $ λ _ _, skip,
cache_cfg := {
mk_cache := λ ns, do {
hs₁ ← to_hinst_lemmas_core reducible ff ns hinst_lemmas.mk,
hs₂ ← merge_hinst_lemma_attrs reducible ff attr_names hs₁,
merge_hinst_lemma_attrs reducible tt simp_attr_names hs₂},
dependencies := [`reducibility] ++ attr_names ++ simp_attr_names}} : user_attribute hinst_lemmas),
add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff),
attribute.register attr_name
meta def get_hinst_lemmas_for_attr (attr_name : name) : tactic hinst_lemmas :=
get_attribute_cache_dyn attr_name
structure ematch_config :=
(max_instances : nat := 10000)
(max_generation : nat := 10)
/- Ematching -/
meta constant ematch_state : Type
meta constant ematch_state.mk : ematch_config → ematch_state
meta constant ematch_state.internalize : ematch_state → expr → tactic ematch_state
namespace tactic
meta constant ematch_core : transparency → cc_state → ematch_state → hinst_lemma → expr → tactic (list (expr × expr) × cc_state × ematch_state)
meta constant ematch_all_core : transparency → cc_state → ematch_state → hinst_lemma → bool → tactic (list (expr × expr) × cc_state × ematch_state)
meta def ematch : cc_state → ematch_state → hinst_lemma → expr → tactic (list (expr × expr) × cc_state × ematch_state) :=
ematch_core reducible
meta def ematch_all : cc_state → ematch_state → hinst_lemma → bool → tactic (list (expr × expr) × cc_state × ematch_state) :=
ematch_all_core reducible
end tactic
|
4288c0e5bdd40cfed42cc41fb2225507b984278e | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebraic_geometry/prime_spectrum/is_open_comap_C.lean | 94a5d44e69992dcb1e08118bf69fb41596048706 | [
"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 | 3,083 | lean | /-
Copyright (c) 2021 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import algebraic_geometry.prime_spectrum.basic
import ring_theory.polynomial.basic
/-!
The morphism `Spec R[x] --> Spec R` induced by the natural inclusion `R --> R[x]` is an open map.
The main result is the first part of the statement of Lemma 00FB in the Stacks Project.
https://stacks.math.columbia.edu/tag/00FB
-/
open ideal polynomial prime_spectrum set
open_locale polynomial
namespace algebraic_geometry
namespace polynomial
variables {R : Type*} [comm_ring R] {f : R[X]}
/-- Given a polynomial `f ∈ R[x]`, `image_of_Df` is the subset of `Spec R` where at least one
of the coefficients of `f` does not vanish. Lemma `image_of_Df_eq_comap_C_compl_zero_locus`
proves that `image_of_Df` is the image of `(zero_locus {f})ᶜ` under the morphism
`comap C : Spec R[x] → Spec R`. -/
def image_of_Df (f) : set (prime_spectrum R) :=
{p : prime_spectrum R | ∃ i : ℕ , (coeff f i) ∉ p.as_ideal}
lemma is_open_image_of_Df : is_open (image_of_Df f) :=
begin
rw [image_of_Df, set_of_exists (λ i (x : prime_spectrum R), coeff f i ∉ x.val)],
exact is_open_Union (λ i, is_open_basic_open),
end
/-- If a point of `Spec R[x]` is not contained in the vanishing set of `f`, then its image in
`Spec R` is contained in the open set where at least one of the coefficients of `f` is non-zero.
This lemma is a reformulation of `exists_coeff_not_mem_C_inverse`. -/
lemma comap_C_mem_image_of_Df {I : prime_spectrum R[X]}
(H : I ∈ (zero_locus {f} : set (prime_spectrum R[X]))ᶜ ) :
prime_spectrum.comap (polynomial.C : R →+* R[X]) I ∈ image_of_Df f :=
exists_coeff_not_mem_C_inverse (mem_compl_zero_locus_iff_not_mem.mp H)
/-- The open set `image_of_Df f` coincides with the image of `basic_open f` under the
morphism `C⁺ : Spec R[x] → Spec R`. -/
lemma image_of_Df_eq_comap_C_compl_zero_locus :
image_of_Df f = prime_spectrum.comap (C : R →+* R[X]) '' (zero_locus {f})ᶜ :=
begin
refine ext (λ x, ⟨λ hx, ⟨⟨map C x.val, (is_prime_map_C_of_is_prime x.property)⟩, ⟨_, _⟩⟩, _⟩),
{ rw [mem_compl_eq, mem_zero_locus, singleton_subset_iff],
cases hx with i hi,
exact λ a, hi (mem_map_C_iff.mp a i) },
{ refine subtype.ext (ext (λ x, ⟨λ h, _, λ h, subset_span (mem_image_of_mem C.1 h)⟩)),
rw ← @coeff_C_zero R x _,
exact mem_map_C_iff.mp h 0 },
{ rintro ⟨xli, complement, rfl⟩,
exact comap_C_mem_image_of_Df complement }
end
/-- The morphism `C⁺ : Spec R[x] → Spec R` is open.
Stacks Project "Lemma 00FB", first part.
https://stacks.math.columbia.edu/tag/00FB
-/
theorem is_open_map_comap_C :
is_open_map (prime_spectrum.comap (C : R →+* R[X])) :=
begin
rintros U ⟨s, z⟩,
rw [← compl_compl U, ← z, ← Union_of_singleton_coe s, zero_locus_Union, compl_Inter, image_Union],
simp_rw [← image_of_Df_eq_comap_C_compl_zero_locus],
exact is_open_Union (λ f, is_open_image_of_Df),
end
end polynomial
end algebraic_geometry
|
7fffe99c46fee9f6571a18a17ac28288bee4177f | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Lean/Elab/Attributes.lean | d1c885129ae73c9bc3eae46704c3d0d693123ee8 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 3,854 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Parser.Attr
import Lean.Attributes
import Lean.MonadEnv
import Lean.Elab.Util
namespace Lean.Elab
structure Attribute where
kind : AttributeKind := AttributeKind.global
name : Name
stx : Syntax := Syntax.missing
deriving Inhabited
instance : ToFormat Attribute where
format attr :=
let kindStr := match attr.kind with
| AttributeKind.global => ""
| AttributeKind.local => "local "
| AttributeKind.scoped => "scoped "
Format.bracket "@[" f!"{kindStr}{attr.name}{toString attr.stx}" "]"
/--
```
attrKind := leading_parser optional («scoped» <|> «local»)
```
-/
def toAttributeKind (attrKindStx : Syntax) : MacroM AttributeKind := do
if attrKindStx[0].isNone then
return AttributeKind.global
else if attrKindStx[0][0].getKind == ``Lean.Parser.Term.scoped then
if (← Macro.getCurrNamespace).isAnonymous then
throw <| Macro.Exception.error (← getRef) "scoped attributes must be used inside namespaces"
return AttributeKind.scoped
else
return AttributeKind.local
def mkAttrKindGlobal : Syntax :=
mkNode ``Lean.Parser.Term.attrKind #[mkNullNode]
def elabAttr [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadMacroAdapter m] [MonadRecDepth m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] [MonadInfoTree m] [MonadLiftT IO m] (attrInstance : Syntax) : m Attribute := do
/- attrInstance := ppGroup $ leading_parser attrKind >> attrParser -/
let attrKind ← liftMacroM <| toAttributeKind attrInstance[0]
let attr := attrInstance[1]
let attr ← liftMacroM <| expandMacros attr
let attrName ← if attr.getKind == ``Parser.Attr.simple then
pure attr[0].getId.eraseMacroScopes
else match attr.getKind with
| .str _ s => pure <| Name.mkSimple s
| _ => throwErrorAt attr "unknown attribute"
let .ok impl := getAttributeImpl (← getEnv) attrName
| throwError "unknown attribute [{attrName}]"
let attrSyntaxNodeKind := attrInstance[1].getKind
-- `Lean.Parser.Attr.simple` is a generic `attribute` parser used in simple attributes.
-- We don't want to create an info tree node from a simple attribute to the generic parser.
let declTarget := if attrSyntaxNodeKind == ``Lean.Parser.Attr.simple then impl.ref else attrSyntaxNodeKind
if (← getEnv).contains declTarget && (← getInfoState).enabled then
pushInfoLeaf <| .ofCommandInfo {
elaborator := declTarget -- not truly an elaborator, but a sensible target for go-to-definition
stx := attrInstance[1][0] -- We want to associate the information to the first atom only
}
/- The `AttrM` does not have sufficient information for expanding macros in `args`.
So, we expand them before here before we invoke the attributer handlers implemented using `AttrM`. -/
return { kind := attrKind, name := attrName, stx := attr }
def elabAttrs [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadMacroAdapter m] [MonadRecDepth m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] [MonadLog m] [MonadInfoTree m] [MonadLiftT IO m] (attrInstances : Array Syntax) : m (Array Attribute) := do
let mut attrs := #[]
for attr in attrInstances do
try
attrs := attrs.push (← withRef attr do elabAttr attr)
catch ex =>
logException ex
return attrs
-- leading_parser "@[" >> sepBy1 attrInstance ", " >> "]"
def elabDeclAttrs [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadMacroAdapter m] [MonadRecDepth m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] [MonadLog m] [MonadInfoTree m] [MonadLiftT IO m] (stx : Syntax) : m (Array Attribute) :=
elabAttrs stx[1].getSepArgs
end Lean.Elab
|
3467b7a5cc047caa0ff38310af8c04f78ef51fbb | 274261f7150b4ed5f1962f172c9357591be8a2b5 | /src/egad.lean | acab75b3084d3959f9901df5acb49f91a1bde4b2 | [] | no_license | rspencer01/lean_representation_theory | 219ea1edf4b9897b2997226b54473e44e1538b50 | 2eef2b4b39d99d7ce71bec7bbc3dcc2f7586fcb5 | refs/heads/master | 1,588,133,157,029 | 1,571,689,957,000 | 1,571,689,957,000 | 175,835,785 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,243 | lean | import data.multiset
import data.finset
import data.list.basic
import .module_filtration
import .quiver
import .lattices
variables {R : Type} [ring R] {M : Module R}
variable (F : filtration (submodule R M))
structure generalised_alperin_diagram :=
(diagram : quiver)
(ac : is_acyclic diagram)
(s : diagram.vertices → { a // a ∈ F.factors })
(bs : function.bijective s)
(delta : downset diagram.vertices → submodule R M)
(id : function.injective delta)
(lat_hom : is_lattice_hom delta)
instance : has_coe (generalised_alperin_diagram F) quiver := ⟨ λ D, generalised_alperin_diagram.diagram D⟩
variable (D : generalised_alperin_diagram F)
instance gad_is_acyclic (D : generalised_alperin_diagram F) : is_acyclic D := D.ac
instance gad_is_pordered : partial_order (D : quiver).vertices := quiver_vertices_partial _
theorem t_1_2 :
∀ (A B : downset (D : quiver).vertices), A ≤ B ↔ D.delta A ≤ D.delta B :=
begin
intros;
split;
intros;
have h₁ : preserves_meet D.delta := D.lat_hom.preserves_meet,
exact homo_preserves_lt_1 D.delta h₁ A B a,
have h₂ : function.injective D.delta := D.id;
exact homo_preserves_lt_2 _ h₂ h₁ _ _ a
end
|
48f0995c0e5e3412f855ab39a24539b0ed00de5a | 4c630d016e43ace8c5f476a5070a471130c8a411 | /ring_theory/associated.lean | a3e282a44a58788283d0e8597263cade466aee15 | [
"Apache-2.0"
] | permissive | ngamt/mathlib | 9a510c391694dc43eec969914e2a0e20b272d172 | 58909bd424209739a2214961eefaa012fb8a18d2 | refs/heads/master | 1,585,942,993,674 | 1,540,739,585,000 | 1,540,916,815,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 20,391 | 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, Jens Wagemaker
Associated and irreducible elements.
-/
import order.galois_connection algebra.group data.equiv.basic data.multiset data.int.gcd
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
open lattice
/-- is unit -/
def is_unit [monoid α] (a : α) : Prop := ∃u:units α, a = u
@[simp] theorem not_is_unit_zero [nonzero_comm_ring α] : ¬ is_unit (0 : α)
| ⟨⟨a, b, hab, hba⟩, rfl⟩ := have 0 * b = 1, from hab, by simpa using this
@[simp] theorem is_unit_one [monoid α] : is_unit (1:α) := ⟨1, rfl⟩
theorem is_unit_of_mul_one [comm_monoid α] (a b : α) (h : a * b = 1) : is_unit a :=
⟨units.mk_of_mul_eq_one a b h, rfl⟩
@[simp] theorem units.is_unit_mul_units [monoid α] (a : α) (u : units α) :
is_unit (a * u) ↔ is_unit a :=
iff.intro
(assume ⟨v, hv⟩,
have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [hv, units.coe_mul],
by rwa [mul_assoc, units.mul_inv, mul_one] at this)
(assume ⟨v, hv⟩, hv.symm ▸ ⟨v * u, (units.coe_mul v u).symm⟩)
theorem is_unit_iff_dvd_one [comm_semiring α] {x : α} : is_unit x ↔ x ∣ 1 :=
⟨by rintro ⟨u, rfl⟩; exact ⟨_, u.mul_inv.symm⟩,
λ ⟨y, h⟩, ⟨⟨x, y, h.symm, by rw [h, mul_comm]⟩, rfl⟩⟩
theorem is_unit_iff_forall_dvd [comm_semiring α] {x : α} :
is_unit x ↔ ∀ y, x ∣ y :=
is_unit_iff_dvd_one.trans ⟨λ h y, dvd.trans h (one_dvd _), λ h, h _⟩
theorem is_unit_of_dvd_unit {α} [comm_semiring α] {x y : α}
(xy : x ∣ y) (hu : is_unit y) : is_unit x :=
is_unit_iff_dvd_one.2 $ dvd_trans xy $ is_unit_iff_dvd_one.1 hu
@[simp] theorem is_unit_nat {n : ℕ} : is_unit n ↔ n = 1 :=
iff.intro
(assume ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end)
(assume h, h.symm ▸ ⟨1, rfl⟩)
lemma is_unit_of_dvd_one [comm_semiring α] : ∀a ∣ 1, is_unit (a:α)
| a ⟨b, eq⟩ := ⟨units.mk_of_mul_eq_one a b eq.symm, rfl⟩
/-- prime element of a semiring -/
def prime [comm_semiring α] (p : α) : Prop :=
p ≠ 0 ∧ ¬ is_unit p ∧ (∀a b, p ∣ a * b → p ∣ a ∨ p ∣ b)
lemma not_prime_zero [integral_domain α] : ¬ prime (0 : α)
| ⟨h, _⟩ := h rfl
lemma exists_mem_multiset_dvd_of_prime [comm_semiring α] {s : multiset α} {p : α} (hp : prime p) :
p ∣ s.prod → ∃a∈s, p ∣ a :=
multiset.induction_on s (assume h, (hp.2.1 $ is_unit_of_dvd_one _ h).elim) $
assume a s ih h,
have p ∣ a * s.prod, by simpa using h,
match hp.2.2 a s.prod this with
| or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩
| or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩
end
/-- `irreducible p` states that `p` is non-unit and only factors into units.
We explicitly avoid stating that `p` is non-zero, this would require a semiring. Assuming only a
monoid allows us to reuse irreducible for associated elements.
-/
@[class] def irreducible [monoid α] (p : α) : Prop :=
¬ is_unit p ∧ ∀a b, p = a * b → is_unit a ∨ is_unit b
@[simp] theorem not_irreducible_one [monoid α] : ¬ irreducible (1 : α) :=
by simp [irreducible]
@[simp] theorem not_irreducible_zero [semiring α] : ¬ irreducible (0 : α)
| ⟨hn0, h⟩ := have is_unit (0:α) ∨ is_unit (0:α), from h 0 0 ((mul_zero 0).symm),
this.elim hn0 hn0
theorem of_irreducible_mul {α} [monoid α] {x y : α} :
irreducible (x * y) → is_unit x ∨ is_unit y
| ⟨_, h⟩ := h _ _ rfl
theorem irreducible_or_factor {α} [monoid α] (x : α) (h : ¬ is_unit x) :
irreducible x ∨ ∃ a b, ¬ is_unit a ∧ ¬ is_unit b ∧ a * b = x :=
begin
haveI := classical.dec,
refine or_iff_not_imp_right.2 (λ H, _),
simp [h, irreducible] at H ⊢,
refine λ a b h, classical.by_contradiction $ λ o, _,
simp [not_or_distrib] at o,
exact H _ o.1 _ o.2 h.symm
end
theorem irreducible_iff_nat_prime : ∀(a : ℕ), irreducible a ↔ nat.prime a
| 0 := by simp [nat.not_prime_zero]
| 1 := by simp [nat.prime, one_lt_two]
| (n + 2) :=
have h₁ : ¬n + 2 = 1, from dec_trivial,
begin
simp [h₁, nat.prime, irreducible, (≥), nat.le_add_left 2 n, (∣)],
refine forall_congr (assume a, forall_congr $ assume b, forall_congr $ assume hab, _),
by_cases a = 1; simp [h],
split,
{ assume hb, simpa [hb] using hab.symm },
{ assume ha, subst ha,
have : n + 2 > 0, from dec_trivial,
refine nat.eq_of_mul_eq_mul_left this _,
rw [← hab, mul_one] }
end
def associated [monoid α] (x y : α) : Prop := ∃u:units α, x * u = y
local infix ` ~ᵤ ` : 50 := associated
namespace associated
@[refl] protected theorem refl [monoid α] (x : α) : x ~ᵤ x := ⟨1, by simp⟩
@[symm] protected theorem symm [monoid α] : ∀{x y : α}, x ~ᵤ y → y ~ᵤ x
| x _ ⟨u, rfl⟩ := ⟨u⁻¹, by rw [mul_assoc, units.mul_inv, mul_one]⟩
@[trans] protected theorem trans [monoid α] : ∀{x y z : α}, x ~ᵤ y → y ~ᵤ z → x ~ᵤ z
| x _ _ ⟨u, rfl⟩ ⟨v, rfl⟩ := ⟨u * v, by rw [units.coe_mul, mul_assoc]⟩
protected def setoid (α : Type*) [monoid α] : setoid α :=
{ r := associated, iseqv := ⟨associated.refl, λa b, associated.symm, λa b c, associated.trans⟩ }
end associated
local attribute [instance] associated.setoid
theorem unit_associated_one [monoid α] {u : units α} : (u : α) ~ᵤ 1 := ⟨u⁻¹, units.mul_inv u⟩
theorem associated_one_iff_is_unit [monoid α] {a : α} : (a : α) ~ᵤ 1 ↔ is_unit a :=
iff.intro
(assume h, let ⟨c, h⟩ := h.symm in h ▸ ⟨c, one_mul _⟩)
(assume ⟨c, h⟩, associated.symm ⟨c, by simp [h]⟩)
theorem associated_zero_iff_eq_zero [comm_semiring α] (a : α) : a ~ᵤ 0 ↔ a = 0 :=
iff.intro
(assume h, let ⟨u, h⟩ := h.symm in by simpa using h.symm)
(assume h, h ▸ associated.refl a)
theorem associated_one_of_mul_eq_one [comm_monoid α] {a : α} (b : α) (hab : a * b = 1) : a ~ᵤ 1 :=
show (units.mk_of_mul_eq_one a b hab : α) ~ᵤ 1, from unit_associated_one
theorem associated_one_of_associated_mul_one [comm_monoid α] {a b : α} :
a * b ~ᵤ 1 → a ~ᵤ 1
| ⟨u, h⟩ := associated_one_of_mul_eq_one (b * u) $ by simpa [mul_assoc] using h
lemma associated_mul_mul [comm_monoid α] {a₁ a₂ b₁ b₂ : α} :
a₁ ~ᵤ b₁ → a₂ ~ᵤ b₂ → (a₁ * a₂) ~ᵤ (b₁ * b₂)
| ⟨c₁, h₁⟩ ⟨c₂, h₂⟩ := ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩
theorem associated_of_dvd_dvd [integral_domain α] {a b : α} (hab : a ∣ b) (hba : b ∣ a) : a ~ᵤ b :=
begin
haveI := classical.dec_eq α,
rcases hab with ⟨c, rfl⟩,
rcases hba with ⟨d, a_eq⟩,
by_cases ha0 : a = 0,
{ simp [*] at * },
have : a * 1 = a * (c * d),
{ simpa [mul_assoc] using a_eq },
have : 1 = (c * d), from eq_of_mul_eq_mul_left ha0 this,
exact ⟨units.mk_of_mul_eq_one c d (this.symm), by rw [units.mk_of_mul_eq_one, units.val_coe]⟩
end
def associates (α : Type*) [monoid α] : Type* :=
quotient (associated.setoid α)
namespace associates
open associated
protected def mk {α : Type*} [monoid α] (a : α) : associates α :=
⟦ a ⟧
theorem mk_eq_mk_iff_associated [monoid α] {a b : α} :
associates.mk a = associates.mk b ↔ a ~ᵤ b :=
iff.intro quotient.exact quot.sound
theorem quotient_mk_eq_mk [monoid α] (a : α) : ⟦ a ⟧ = associates.mk a := rfl
theorem quot_mk_eq_mk [monoid α] (a : α) : quot.mk setoid.r a = associates.mk a := rfl
theorem forall_associated [monoid α] {p : associates α → Prop} :
(∀a, p a) ↔ (∀a, p (associates.mk a)) :=
iff.intro
(assume h a, h _)
(assume h a, quotient.induction_on a h)
instance [monoid α] : has_one (associates α) := ⟨⟦ 1 ⟧⟩
theorem one_eq_mk_one [monoid α] : (1 : associates α) = associates.mk 1 := rfl
instance [monoid α] : has_bot (associates α) := ⟨1⟩
section comm_monoid
variable [comm_monoid α]
instance : has_mul (associates α) :=
⟨λa' b', quotient.lift_on₂ a' b' (λa b, ⟦ a * b ⟧) $
assume a₁ a₂ b₁ b₂ ⟨c₁, h₁⟩ ⟨c₂, h₂⟩,
quotient.sound $ ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩⟩
theorem mk_mul_mk {x y : α} : associates.mk x * associates.mk y = associates.mk (x * y) :=
rfl
instance : comm_monoid (associates α) :=
{ one := 1,
mul := (*),
mul_one := assume a', quotient.induction_on a' $
assume a, show ⟦a * 1⟧ = ⟦ a ⟧, by simp,
one_mul := assume a', quotient.induction_on a' $
assume a, show ⟦1 * a⟧ = ⟦ a ⟧, by simp,
mul_assoc := assume a' b' c', quotient.induction_on₃ a' b' c' $
assume a b c, show ⟦a * b * c⟧ = ⟦a * (b * c)⟧, by rw [mul_assoc],
mul_comm := assume a' b', quotient.induction_on₂ a' b' $
assume a b, show ⟦a * b⟧ = ⟦b * a⟧, by rw [mul_comm] }
instance : preorder (associates α) :=
{ le := λa b, ∃c, a * c = b,
le_refl := assume a, ⟨1, by simp⟩,
le_trans := assume a b c ⟨f₁, h₁⟩ ⟨f₂, h₂⟩, ⟨f₁ * f₂, h₂ ▸ h₁ ▸ (mul_assoc _ _ _).symm⟩}
instance [comm_monoid α] : has_dvd (associates α) := ⟨(≤)⟩
lemma dvd_eq_le [comm_monoid α] : ((∣) : associates α → associates α → Prop) = (≤) := rfl
theorem prod_mk {p : multiset α} : (p.map associates.mk).prod = associates.mk p.prod :=
multiset.induction_on p (by simp; refl) $ assume a s ih, by simp [ih]; refl
theorem rel_associated_iff_map_eq_map {p q : multiset α} :
multiset.rel associated p q ↔ p.map associates.mk = q.map associates.mk :=
by rw [← multiset.rel_eq];
simp [multiset.rel_map_left, multiset.rel_map_right, mk_eq_mk_iff_associated]
theorem mul_eq_one_iff {x y : associates α} : x * y = 1 ↔ (x = 1 ∧ y = 1) :=
iff.intro
(quotient.induction_on₂ x y $ assume a b h,
have a * b ~ᵤ 1, from quotient.exact h,
⟨quotient.sound $ associated_one_of_associated_mul_one this,
quotient.sound $ associated_one_of_associated_mul_one $ by rwa [mul_comm] at this⟩)
(by simp {contextual := tt})
theorem prod_eq_one_iff {p : multiset (associates α)} :
p.prod = 1 ↔ (∀a ∈ p, (a:associates α) = 1) :=
multiset.induction_on p
(by simp)
(by simp [mul_eq_one_iff, or_imp_distrib, forall_and_distrib] {contextual := tt})
theorem coe_unit_eq_one : ∀u:units (associates α), (u : associates α) = 1
| ⟨u, v, huv, hvu⟩ := by rw [mul_eq_one_iff] at huv; exact huv.1
theorem is_unit_iff_eq_one (a : associates α) : is_unit a ↔ a = 1 :=
iff.intro
(assume ⟨u, h⟩, h.symm ▸ coe_unit_eq_one _)
(assume h, h.symm ▸ is_unit_one)
theorem is_unit_mk {a : α} : is_unit (associates.mk a) ↔ is_unit a :=
calc is_unit (associates.mk a) ↔ a ~ᵤ 1 :
by rw [is_unit_iff_eq_one, one_eq_mk_one, mk_eq_mk_iff_associated]
... ↔ is_unit a : associated_one_iff_is_unit
section order
theorem mul_mono {a b c d : associates α} (h₁ : a ≤ b) (h₂ : c ≤ d) :
a * c ≤ b * d :=
let ⟨x, hx⟩ := h₁, ⟨y, hy⟩ := h₂ in
⟨x * y, by simp [hx.symm, hy.symm, mul_comm, mul_assoc, mul_left_comm]⟩
theorem one_le {a : associates α} : 1 ≤ a :=
⟨a, one_mul a⟩
theorem prod_le_prod {p q : multiset (associates α)} (h : p ≤ q) : p.prod ≤ q.prod :=
begin
haveI := classical.dec_eq (associates α),
haveI := classical.dec_eq α,
suffices : p.prod ≤ (p + (q - p)).prod, { rwa [multiset.add_sub_of_le h] at this },
suffices : p.prod * 1 ≤ p.prod * (q - p).prod, { simpa },
exact mul_mono (le_refl p.prod) one_le
end
theorem le_mul_right {a b : associates α} : a ≤ a * b := ⟨b, rfl⟩
theorem le_mul_left {a b : associates α} : a ≤ b * a :=
by rw [mul_comm]; exact le_mul_right
end order
end comm_monoid
instance [has_zero α] [monoid α] : has_zero (associates α) := ⟨⟦ 0 ⟧⟩
instance [has_zero α] [monoid α] : has_top (associates α) := ⟨0⟩
section comm_semiring
variables [comm_semiring α]
@[simp] theorem mk_zero_eq (a : α) : associates.mk a = 0 ↔ a = 0 :=
⟨assume h, (associated_zero_iff_eq_zero a).1 $ quotient.exact h, assume h, h.symm ▸ rfl⟩
@[simp] theorem mul_zero : ∀(a : associates α), a * 0 = 0 :=
by rintros ⟨a⟩; show associates.mk (a * 0) = associates.mk 0; rw [mul_zero]
@[simp] theorem zero_mul : ∀(a : associates α), 0 * a = 0 :=
by rintros ⟨a⟩; show associates.mk (0 * a) = associates.mk 0; rw [zero_mul]
theorem mk_eq_zero_iff_eq_zero {a : α} : associates.mk a = 0 ↔ a = 0 :=
calc associates.mk a = 0 ↔ (a ~ᵤ 0) : mk_eq_mk_iff_associated
... ↔ a = 0 : associated_zero_iff_eq_zero a
theorem dvd_of_mk_le_mk {a b : α} : associates.mk a ≤ associates.mk b → a ∣ b
| ⟨c', hc'⟩ := (quotient.induction_on c' $ assume c hc,
let ⟨d, hd⟩ := (quotient.exact hc).symm in
⟨(↑d⁻¹) * c,
calc b = (a * c) * ↑d⁻¹ : by rw [← hd, mul_assoc, units.mul_inv, mul_one]
... = a * (↑d⁻¹ * c) : by ac_refl⟩) hc'
theorem mk_le_mk_of_dvd {a b : α} : a ∣ b → associates.mk a ≤ associates.mk b :=
assume ⟨c, hc⟩, ⟨associates.mk c, by simp [hc]; refl⟩
theorem mk_le_mk_iff_dvd_iff {a b : α} : associates.mk a ≤ associates.mk b ↔ a ∣ b :=
iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd
def prime (p : associates α) : Prop := p ≠ 0 ∧ p ≠ 1 ∧ (∀a b, p ≤ a * b → p ≤ a ∨ p ≤ b)
lemma exists_mem_multiset_le_of_prime {s : multiset (associates α)} {p : associates α}
(hp : prime p) :
p ≤ s.prod → ∃a∈s, p ≤ a :=
multiset.induction_on s (assume ⟨d, eq⟩, (hp.2.1 (mul_eq_one_iff.1 eq).1).elim) $
assume a s ih h,
have p ≤ a * s.prod, by simpa using h,
match hp.2.2 a s.prod this with
| or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩
| or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩
end
lemma prime_mk (p : α) : prime (associates.mk p) ↔ _root_.prime p :=
begin
rw [associates.prime, _root_.prime, forall_associated],
transitivity,
{ apply and_congr, refl,
apply and_congr, refl,
apply forall_congr, assume a,
exact forall_associated },
apply and_congr,
{ rw [(≠), mk_zero_eq] },
apply and_congr,
{ rw [(≠), ← is_unit_iff_eq_one, is_unit_mk], },
apply forall_congr, assume a,
apply forall_congr, assume b,
rw [mk_mul_mk, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]
end
end comm_semiring
section integral_domain
variable [integral_domain α]
instance : partial_order (associates α) :=
{ le_antisymm := assume a' b',
quotient.induction_on₂ a' b' $ assume a b ⟨f₁', h₁⟩ ⟨f₂', h₂⟩,
(quotient.induction_on₂ f₁' f₂' $ assume f₁ f₂ h₁ h₂,
let ⟨c₁, h₁⟩ := quotient.exact h₁, ⟨c₂, h₂⟩ := quotient.exact h₂ in
quotient.sound $ associated_of_dvd_dvd
(h₁ ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _)
(h₂ ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _)) h₁ h₂
.. associates.preorder }
instance : lattice.order_bot (associates α) :=
{ bot := 1,
bot_le := assume a, one_le,
.. associates.partial_order }
instance : lattice.order_top (associates α) :=
{ top := 0,
le_top := assume a, ⟨0, mul_zero a⟩,
.. associates.partial_order }
theorem zero_ne_one : (0 : associates α) ≠ 1 :=
assume h,
have (0 : α) ~ᵤ 1, from quotient.exact h,
have (0 : α) = 1, from ((associated_zero_iff_eq_zero 1).1 this.symm).symm,
zero_ne_one this
theorem mul_eq_zero_iff {x y : associates α} : x * y = 0 ↔ x = 0 ∨ y = 0 :=
iff.intro
(quotient.induction_on₂ x y $ assume a b h,
have a * b = 0, from (associated_zero_iff_eq_zero _).1 (quotient.exact h),
have a = 0 ∨ b = 0, from mul_eq_zero_iff_eq_zero_or_eq_zero.1 this,
this.imp (assume h, h.symm ▸ rfl) (assume h, h.symm ▸ rfl))
(by simp [or_imp_distrib] {contextual := tt})
theorem prod_eq_zero_iff {s : multiset (associates α)} :
s.prod = 0 ↔ (0 : associates α) ∈ s :=
multiset.induction_on s (by simp; exact zero_ne_one.symm) $
assume a s, by simp [mul_eq_zero_iff, @eq_comm _ 0 a] {contextual := tt}
theorem irreducible_mk_iff (a : α) : irreducible (associates.mk a) ↔ irreducible a :=
begin
simp [irreducible, is_unit_mk],
apply and_congr (iff.refl _),
split,
{ assume h x y eq,
have : is_unit (associates.mk x) ∨ is_unit (associates.mk y),
from h _ _ (by rw [eq]; refl),
simpa [is_unit_mk] },
{ refine assume h x y, quotient.induction_on₂ x y (assume x y eq, _),
rcases quotient.exact eq.symm with ⟨u, eq⟩,
have : a = x * (y * u), by rwa [mul_assoc, eq_comm] at eq,
show is_unit (associates.mk x) ∨ is_unit (associates.mk y),
simpa [is_unit_mk] using h _ _ this }
end
lemma eq_of_mul_eq_mul_left [integral_domain α] :
∀(a b c : associates α), a ≠ 0 → a * b = a * c → b = c :=
begin
rintros ⟨a⟩ ⟨b⟩ ⟨c⟩ ha h,
rcases quotient.exact' h with ⟨u, hu⟩,
have hu : a * (b * ↑u) = a * c, { rwa [← mul_assoc] },
exact quotient.sound' ⟨u, eq_of_mul_eq_mul_left (mt (mk_zero_eq a).2 ha) hu⟩
end
lemma le_of_mul_le_mul_left [integral_domain α] (a b c : associates α) (ha : a ≠ 0) :
a * b ≤ a * c → b ≤ c
| ⟨d, hd⟩ := ⟨d, eq_of_mul_eq_mul_left a _ _ ha $ by rwa ← mul_assoc⟩
lemma one_or_eq_of_le_of_prime [integral_domain α] :
∀(p m : associates α), prime p → m ≤ p → (m = 1 ∨ m = p)
| _ m ⟨hp0, hp1, h⟩ ⟨d, rfl⟩ :=
match h m d (le_refl _) with
| or.inl h := classical.by_cases (assume : m = 0, by simp [this]) $
assume : m ≠ 0,
have m * d ≤ m * 1, by simpa using h,
have d ≤ 1, from associates.le_of_mul_le_mul_left m d 1 ‹m ≠ 0› this,
have d = 1, from lattice.bot_unique this,
by simp [this]
| or.inr h := classical.by_cases (assume : d = 0, by simp [this] at hp0; contradiction) $
assume : d ≠ 0,
have d * m ≤ d * 1, by simpa [mul_comm] using h,
or.inl $ lattice.bot_unique $ associates.le_of_mul_le_mul_left d m 1 ‹d ≠ 0› this
end
end integral_domain
section normalization_domain
variable [normalization_domain α]
protected def out : associates α → α :=
begin
refine quotient.lift (λa, a * ↑(norm_unit a)) _,
letI := classical.dec_eq α,
rintros a _ ⟨u, rfl⟩,
by_cases a = 0, { simp [h] },
calc a * ↑(norm_unit a) = a * ↑(u * norm_unit a * u⁻¹) :
by rw [mul_comm u, mul_assoc, mul_inv_self, mul_one]
... = a * ↑u * ↑(norm_unit (a * ↑u)) :
by simp [h, norm_unit_mul, units.coe_mul, units.coe_inv, mul_assoc]
end
lemma out_mk (a : α) : (associates.mk a).out = a * ↑(norm_unit a) :=
rfl
@[simp] lemma out_one : (1 : associates α).out = 1 :=
calc (1 : associates α).out = 1 * ↑(norm_unit (1 : α)) : out_mk _
... = 1 : by simp
lemma out_mul (a b : associates α) : (a * b).out = a.out * b.out :=
begin
refine quotient.induction_on₂ a b (assume a b, _),
simp [associates.quotient_mk_eq_mk, out_mk, mk_mul_mk],
letI := classical.dec_eq α,
by_cases a = 0; by_cases b = 0; simp [*, mul_assoc, mul_comm, mul_left_comm]
end
lemma dvd_out_iff (a : α) (b : associates α) : a ∣ b.out ↔ associates.mk a ≤ b :=
quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff]
lemma out_dvd_iff (a : α) (b : associates α) : b.out ∣ a ↔ b ≤ associates.mk a :=
quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff]
@[simp] lemma out_top : (⊤ : associates α).out = 0 :=
calc (⊤ : associates α).out = 0 * ↑(norm_unit (0:α)) : out_mk _
... = 0 : by simp
@[simp] lemma norm_unit_out (a : associates α) : norm_unit a.out = 1 :=
quotient.induction_on a $ assume a,
by rw [associates.quotient_mk_eq_mk, associates.out_mk, norm_unit_mul_norm_unit]
end normalization_domain
end associates
def associates_int_equiv_nat : (associates ℤ) ≃ ℕ :=
begin
refine ⟨λz, z.out.nat_abs, λn, associates.mk n, _, _⟩,
{ refine (assume a, quotient.induction_on a $ assume a,
associates.mk_eq_mk_iff_associated.2 $ associated.symm $ ⟨norm_unit a, _⟩),
simp [associates.out_mk, associates.quotient_mk_eq_mk, associated,
int.coe_nat_abs_eq_mul_norm_unit.symm] },
{ assume n, simp [associates.out_mk, int.coe_nat_abs_eq_mul_norm_unit.symm] }
end
|
ae932f1cff2f0c284763b26db746068de948ef72 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/elab5.lean | 6781c764fb77b84ced4d6eec2707bdcb3bc3c490 | [
"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 | 60 | lean | constant s : sum nat bool
#check @eq.refl (sum nat bool) s
|
82a38a181067cd7e7f9eba8515e4e25ea1fd618d | 8f209eb34c0c4b9b6be5e518ebfc767a38bed79c | /code/src/internal/R_red_removable.lean | 402307efe034cf36b720d5ade9aed2dca6152430 | [] | no_license | hediet/masters-thesis | 13e3bcacb6227f25f7ec4691fb78cb0363f2dfb5 | dc40c14cc4ed073673615412f36b4e386ee7aac9 | refs/heads/master | 1,680,591,056,302 | 1,617,710,887,000 | 1,617,710,887,000 | 311,762,038 | 4 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,510 | lean | import tactic
import data.finset
import ..definitions
import .internal_definitions
import .tactics
import .utils
import .phi.utils
import .Ant.main
import .Gdt.main
import .U
import .A
import .R
variable [GuardModule]
open GuardModule
lemma R_red_redundant { ant: Ant bool } (ant_disjoint: ant.disjoint_rhss):
ant.is_redundant_set (R ant).red.to_finset :=
begin
induction_ant_disjoint ant from ant_disjoint,
case Ant.rhs {
unfold Ant.is_redundant_set R,
cases ant_a;
simp [Ant.critical_rhs_sets, Ant.inactive_rhss],
},
case Ant.branch {
unfold Ant.is_redundant_set R,
unfold Ant.is_redundant_set R at ant_ih_tr1,
unfold Ant.is_redundant_set R at ant_ih_tr2,
unfold RhsPartition.red,
split, {
simp [Ant.inactive_rhss, finset.union_subset_union ant_ih_tr1.1 ant_ih_tr2.1],
replace ant_ih_tr1 := ant_ih_tr1.1,
replace ant_ih_tr2 := ant_ih_tr2.1,
rw subset_inter_subset_subset R_red_subset_rhss at ant_ih_tr1,
rw subset_inter_subset_subset R_red_subset_rhss at ant_ih_tr2,
apply subset_inter_subset,
exact finset.union_subset_union ant_ih_tr1 ant_ih_tr2,
},
assume e,
assume h,
rw Ant.critical_rhs_sets at h,
replace ant_ih_tr1 := ant_ih_tr1.2,
replace ant_ih_tr2 := ant_ih_tr2.2,
simp at h,
cases h, {
specialize ant_ih_tr1 e h,
cases ant_ih_tr1 with x ant_ih_tr1,
cases ant_ih_tr1 with H ant_ih_tr1,
have : x ∉ (R ant_tr2).red.to_finset :=
begin
by_contradiction,
have h1 := finset.subset_iff.1 (Ant.critical_rhs_set_elements h) H,
have h2 := finset.subset_iff.1 (R_red_subset_rhss) a,
have := finset.disjoint_iff_ne.1 ant_disjoint _ h1 _ h2,
simp at this,
exact this,
end,
use x,
simp [*],
},
{
specialize ant_ih_tr2 e h,
cases ant_ih_tr2 with x ant_ih_tr2,
cases ant_ih_tr2 with H ant_ih_tr2,
have : x ∉ (R ant_tr1).red.to_finset :=
begin
by_contradiction,
have h1 := finset.subset_iff.1 (Ant.critical_rhs_set_elements h) H,
have h2 := finset.subset_iff.1 (R_red_subset_rhss) a,
have := finset.disjoint_iff_ne.1 ant_disjoint _ h2 _ h1,
simp at this,
exact this,
end,
use x,
simp [*],
}
},
case Ant.diverge {
unfold Ant.is_redundant_set,
unfold Ant.is_redundant_set at ant_ih,
split, {
R_diverge_cases,
{
inline R_ant_tr,
unfold RhsPartition.red at *,
simp only [Ant.inactive_rhss, Ant.rhss_diverge],
have : rs.to_finset ⊆ (r :: rs).to_finset := by simp [finset.subset_insert],
have := finset.inter_subset_inter this (finset.subset.refl _),
exact finset.subset.trans this ant_ih.1,
},
{
exact ant_ih.1,
},
},
assume e,
assume h,
unfold Ant.critical_rhs_sets at h,
R_diverge_cases, {
inline ant_a,
simp only [bool.coe_sort_ff, if_false, finset.mem_union, finset.mem_singleton] at h,
rw R_ant_tr at *,
unfold RhsPartition.red at *,
cases h, {
have := ant_ih.2 e h,
cases this with x this,
cases this with H this,
use x,
finish,
}, {
use r,
rw h,
have : r ∈ (R ant_tr).red.to_finset := by simp *,
have := finset.subset_iff.1 R_red_subset_rhss this,
split, { exact this, },
apply R_red_l_not_mem_ls ant_disjoint,
simp *,
}
},
{
cases ant_a,
case bool.tt {
simp only [if_true, bool.coe_sort_tt, finset.union_empty] at h,
exact ant_ih.2 e h,
},
simp only [bool.coe_sort_ff, if_false, finset.mem_union, finset.mem_singleton] at h,
cases h, { exact ant_ih.2 e h, },
rw h,
cases R_diverge_cases, {
contradiction,
},
cases R_diverge_cases, {
cases c: (R ant_tr).acc with acc accs, { finish, },
use acc,
have acc_mem : acc ∈ (R ant_tr).acc.to_finset := by simp [c],
simp [finset.subset_iff.1 R_acc_subset_rhss acc_mem, R_acc_l_not_mem_red ant_disjoint c],
},
cases R_diverge_cases, {
cases c: (R ant_tr).inacc with inacc inaccs, { finish, },
use inacc,
have inacc_mem : inacc ∈ (R ant_tr).inacc.to_finset := by simp [c],
simp [finset.subset_iff.1 R_inacc_subset_rhss inacc_mem, R_inacc_l_not_mem_red ant_disjoint c],
},
{
have := Ant.rhss_non_empty ant_tr,
cases this with l ls,
rw R_diverge_cases,
use l,
simp *,
}
},
},
end
lemma can_prove_empty_implies_inactive (can_prove_empty: CorrectCanProveEmpty) (ant: Ant Φ) (env: Env):
(ant.map (can_prove_empty.val)) ⟶ (ant.mark_inactive_rhss env) :=
begin
have : ∀ ty: Φ, (can_prove_empty.val ty) → !ty.eval env := begin
unfold_coes,
simp only [bnot_eq_true_eq_eq_ff],
assume ty h,
have := can_prove_empty.property,
finish [correct_can_prove_empty, Φ.is_empty, correct_can_prove_empty],
end,
induction ant,
case Ant.rhs {
apply Ant.implies.rhs,
exact this _,
},
case Ant.branch {
simp only [Ant.implies.branch, Ant.map, Ant.mark_inactive_rhss.branch, *],
},
case Ant.diverge {
rw Ant.mark_inactive_rhss_of_diverge,
apply Ant.implies.diverge ant_ih (this _),
},
end
lemma A_mark_inactive_rhss (gdt: Gdt) (env: Env): (A gdt).mark_inactive_rhss env = gdt.mark_inactive_rhss env :=
begin
have : bor ff = id := by refl,
have : bor tt = λ x, tt := by refl,
induction gdt generalizing env,
case Gdt.rhs { refl, },
case Gdt.branch {
unfold A,
rw Ant.mark_inactive_rhss_branch,
rw Ant.mark_inactive_rhss_of_map_ty_and _ _ _,
rw [gdt_ih_tr1, gdt_ih_tr2],
rw U_semantic,
unfold Gdt.mark_inactive_rhss,
simp only [true_and, eq_self_iff_true, ne.def, bnot_bnot],
cases (gdt_tr1.eval env).is_match;
simp [*, Gdt.mark_inactive_rhss_map_tt],
},
case Gdt.grd {
cases gdt_grd,
case Grd.tgrd {
unfold A,
cases c: tgrd_eval gdt_grd env,
case option.none {
rw [Ant.mark_inactive_rhss_of_map_tgrd_in_none c, Gdt.mark_inactive_rhss_of_tgrd_none c],
rw ←Gdt.mark_inactive_rhss_map_tt _ env,
rw ←gdt_ih env,
simp [Ant.mark_inactive_rhss],
},
case option.some {
rw Ant.mark_inactive_rhss_of_map_tgrd_in_some c,
rw Gdt.mark_inactive_rhss_of_tgrd_some c,
exact gdt_ih val,
},
},
case Grd.bang {
unfold A,
rw Ant.mark_inactive_rhss_of_diverge,
rw Ant.mark_inactive_rhss_of_map_ty_and,
rw gdt_ih env,
unfold Gdt.mark_inactive_rhss,
cases c: is_bottom gdt_grd env;
simp [c, *, Gdt.mark_inactive_rhss_map_tt],
},
},
end
lemma is_redundant_set_monotonous' { a b: Ant bool } (h: a ⟶ b):
a.inactive_rhss ⊆ b.inactive_rhss ∧ b.critical_rhs_sets ⊆ a.critical_rhs_sets :=
begin
induction a generalizing b;
cases h with h b_a,
-- case rhs:
{
cases a_a; cases b_a;
finish [Ant.inactive_rhss, Ant.implies.rhs],
},
-- case branch:
{
specialize a_ih_tr1 h_h1,
specialize a_ih_tr2 h_h2,
simp [ *, finset.union_subset_union, Ant.inactive_rhss, Ant.critical_rhs_sets ],
},
-- case grd:
{
specialize a_ih h_h1,
split, { simp [Ant.inactive_rhss, a_ih], },
cases a_a; cases h_b;
finish [
Ant.critical_rhs_sets,
Ant.implies_same_rhss h_h1,
finset.union_subset_union,
a_ih.2,
subset_right_union
],
},
end
lemma is_redundant_set_monotonous { a b: Ant bool } (rhss: finset Rhs) (h: a ⟶ b):
a.is_redundant_set rhss → b.is_redundant_set rhss :=
begin
unfold Ant.is_redundant_set,
have := is_redundant_set_monotonous' h,
assume p,
split,
{
rw ←Ant.implies_same_rhss h,
exact finset.subset.trans p.1 this.1,
},
assume e,
assume q,
exact p.right e (this.2 q),
end
lemma sets_1 { α: Type } [decidable_eq α] { l1 l2 l3 l4: finset α }
(h1: l4 ∩ (l1 ∪ l2) ⊆ l1 ∪ l3)
(h2: disjoint l1 l2)
: l4 ∩ l2 ⊆ l3 :=
begin
rw finset.subset_iff,
simp,
assume x h3 h4,
rw finset.subset_iff at h1,
specialize @h1 x,
simp at h1,
simp [finset.disjoint_iff_inter_eq_empty, finset.subset.antisymm_iff, finset.subset_iff] at h2,
specialize @h2 x,
tauto,
end
lemma sets_2 { α: Type } [decidable_eq α] { l1 l2 l3 l4: finset α }
(h1: l4 ∩ (l1 ∪ l2) ⊆ l3 ∪ l2)
(h2: disjoint l1 l2)
: l4 ∩ l1 ⊆ l3 :=
begin
rw finset.subset_iff,
simp,
assume x h3 h4,
rw finset.subset_iff at h1,
specialize @h1 x,
simp at h1,
simp [finset.disjoint_iff_inter_eq_empty, finset.subset.antisymm_iff, finset.subset_iff] at h2,
specialize @h2 x,
tauto,
end
lemma redundant_rhss_removable
(gdt: Gdt) (gdt_disjoint: gdt.disjoint_rhss)
(env: Env)
(rhss: finset Rhs) (rhss_def: (gdt.mark_inactive_rhss env).is_redundant_set rhss):
Gdt.eval_option (gdt.remove_rhss rhss) env = gdt.eval env :=
begin
induction gdt with rhs generalizing env,
case Gdt.rhs {
simp [Gdt.eval],
unfold Gdt.mark_inactive_rhss Ant.is_redundant_set at rhss_def,
simp [Ant.inactive_rhss, Ant.critical_rhs_sets, Ant.rhss] at rhss_def,
unfold Gdt.remove_rhss,
have : ¬rhs ∈ rhss := finset.disjoint_singleton.mp rhss_def,
simp [this, Gdt.eval_option],
},
case Gdt.branch {
simp [Gdt.mark_inactive_rhss, -Result.is_match_neq_no_match] at rhss_def,
unfold Gdt.remove_rhss,
unfold Gdt.disjoint_rhss at gdt_disjoint,
cases c: (gdt_tr1.eval env).is_match,
case bool.ff {
rw c at rhss_def,
simp at c,
simp only [Ant.inactive_rhss, Ant.is_redundant_set, Ant.critical_rhs_sets, bool.coe_sort_ff, Gdt.mark_inactive_rhss.rhss,
Ant.rhss_branch, if_false, finset.mem_union, Gdt.mark_inactive_rhss_no_match c, finset.not_mem_empty, false_or,
Gdt.mark_all_rhss_inactive.critical_rhs_sets, Gdt.mark_all_rhss_inactive.inactive_rhss,
Gdt.mark_all_rhss_inactive.rhss] at rhss_def,
have : (gdt_tr1.mark_inactive_rhss env).is_redundant_set rhss :=
by simp [Gdt.mark_inactive_rhss_no_match c, Gdt.mark_all_rhss_inactive_is_reduntant_set],
specialize gdt_ih_tr1 gdt_disjoint.1 env this,
have : (gdt_tr2.mark_inactive_rhss env).is_redundant_set rhss :=
begin
have := sets_1 rhss_def.1 gdt_disjoint.2.2,
unfold Ant.is_redundant_set,
split, { simp [*], },
exact rhss_def.2,
end,
specialize gdt_ih_tr2 gdt_disjoint.2.1 env this,
rw ←Gdt.eval_option at gdt_ih_tr2,
rw Gdt.branch_option_replace_right_env _ (or.intro_left _ gdt_ih_tr2),
rw ←Gdt.eval_option at gdt_ih_tr1,
rw Gdt.branch_option_replace_left_env gdt_ih_tr1,
simp,
},
case bool.tt {
rw c at rhss_def,
simp only [Result.is_match_tt_neq_no_match, ne.def] at c,
simp only [Ant.inactive_rhss, Ant.is_redundant_set, Ant.critical_rhs_sets, exists_prop, Gdt.mark_all_rhss_inactive.rhss,
if_true, bool.coe_sort_tt, Gdt.mark_inactive_rhss.rhss, Ant.rhss_branch, finset.union_empty,
Gdt.mark_all_rhss_inactive.critical_rhs_sets, Gdt.mark_all_rhss_inactive.inactive_rhss] at rhss_def,
have : (gdt_tr1.mark_inactive_rhss env).is_redundant_set rhss :=
begin
unfold Ant.is_redundant_set,
simp,
have := sets_2 rhss_def.1 gdt_disjoint.2.2,
split, { simp [*], },
exact rhss_def.2,
end,
specialize gdt_ih_tr1 gdt_disjoint.1 env this,
rw ←Gdt.eval_option at c,
rw ←Gdt.eval_option at gdt_ih_tr1,
rw Gdt.branch_option_replace_left_env gdt_ih_tr1,
rw Gdt.branch_option_replace_right_env (some gdt_tr2) (or.intro_right _ c),
simp,
},
},
case Gdt.grd {
unfold Gdt.disjoint_rhss at gdt_disjoint,
cases gdt_grd with gdt_grd var,
case Grd.tgrd {
cases c: tgrd_eval gdt_grd env with env',
case option.some {
simp only [Gdt.eval_tgrd_of_some c],
unfold Ant.is_redundant_set at rhss_def,
simp only [Gdt.mark_inactive_rhss, Gdt.mark_inactive_rhss._match_1, c] at rhss_def,
have : (gdt_tr.mark_inactive_rhss env').is_redundant_set rhss :=
begin
unfold Ant.is_redundant_set,
exact rhss_def,
end,
specialize gdt_ih gdt_disjoint env' this,
unfold Gdt.remove_rhss,
rw Gdt.eval_option_of_tgrd_eval_some c,
exact gdt_ih,
},
case option.none {
simp only [Gdt.eval_tgrd_of_none c],
unfold Gdt.remove_rhss,
exact Gdt.eval_option_of_tgrd_eval_none c,
},
},
case Grd.bang {
cases c: is_bottom var env,
case bool.tt {
simp [Gdt.eval_bang_of_bottom c],
simp only [Ant.is_redundant_set, Ant.inactive_rhss, Ant.critical_rhs_sets, Gdt.mark_inactive_rhss, c,
Gdt.mark_all_rhss_inactive.rhss, if_true, Ant.rhss_diverge, finset.empty_union, bool.coe_sort_ff,
bool.coe_sort_tt, forall_eq, Gdt.mark_all_rhss_inactive.critical_rhs_sets, if_false, finset.mem_singleton,
Gdt.mark_all_rhss_inactive.inactive_rhss] at rhss_def,
unfold Gdt.remove_rhss,
apply Gdt.eval_option_of_is_bottom_tt c (Gdt.remove_rhss_neq_none rhss_def.2),
},
case bool.ff {
simp [Ant.is_redundant_set, Gdt.rhss, Gdt.mark_inactive_rhss, c, Ant.inactive_rhss, Ant.critical_rhs_sets] at rhss_def,
have : (gdt_tr.mark_inactive_rhss env).is_redundant_set rhss, {
simp [Ant.is_redundant_set, Gdt.rhss, Gdt.mark_inactive_rhss, c, Ant.inactive_rhss, Ant.critical_rhs_sets],
exact rhss_def,
},
specialize gdt_ih gdt_disjoint env this,
unfold Gdt.remove_rhss,
simp [Gdt.eval_bang_of_not_bottom c],
rw Gdt.eval_option_of_is_bottom_ff c,
exact gdt_ih,
},
},
},
end
theorem R_red_removable
(can_prove_empty: CorrectCanProveEmpty)
{ gdt: Gdt } (gdt_disjoint: gdt.disjoint_rhss)
{ Agdt: Ant Φ }
(ant_def: Agdt.mark_inactive_rhss = (A gdt).mark_inactive_rhss):
Gdt.eval_option (gdt.remove_rhss (R (Agdt.map can_prove_empty.val)).red.to_finset) = gdt.eval :=
begin
ext env:1,
-- `Agdt` semantically equals `A gdt`, which represents `gdt` by annotating it with refinement types.
-- `Agdt` and `A gdt` don't need to be syntactically equal though!
-- In fact, `𝒜 gdt` and `A gdt` are semantically equal, but not syntactically.
-- `can_prove_empty` approximates emptiness for a single refinement type.
-- `ant_empt` approximates emptiness of the refinement types in `Agdt` for every `env`.
-- It also approximates inactive rhss of `gdt` in context of `env` (ant_empt_imp_gdt).
let ant_empt := Agdt.map can_prove_empty.val,
have ant_empt_imp_gdt := calc
ant_empt ⟶ Agdt.mark_inactive_rhss env : can_prove_empty_implies_inactive can_prove_empty Agdt env
... ⟶ (A gdt).mark_inactive_rhss env : by simp [Ant.implies_refl, ant_def]
... ⟶ gdt.mark_inactive_rhss env : by simp [Ant.implies_refl, A_mark_inactive_rhss gdt env],
-- Since `gdt` has disjoint rhss, `ant_empt` has disjoint rhss too.
have ant_empt_disjoint : ant_empt.disjoint_rhss
:= by simp [Ant.disjoint_rhss_of_gdt_disjoint_rhss gdt_disjoint,
Ant.disjoint_rhss_iff_of_mark_inactive_rhss_eq (function.funext_iff.1 ant_def env)],
-- The set of rhss `R_red` is redundant in `ant_empt` (red_in_ant_empt).
-- This means that these rhss are inactive
-- and not all rhss of possibly active diverge nodes are redundant.
let R_red := (R ant_empt).red.to_finset,
have red_in_ant_empt: ant_empt.is_redundant_set R_red := R_red_redundant ant_empt_disjoint,
-- Since `redundant_in` is monotonous and `ant_empt` approximates inactive rhss on `gdt`,
-- `R_red` is also redundant in `gdt` (red_in_gdt).
have red_in_gdt: (gdt.mark_inactive_rhss env).is_redundant_set R_red
:= is_redundant_set_monotonous _ ant_empt_imp_gdt red_in_ant_empt,
-- Since `R_red` is a redundant set, it can be removed from `gdt` without
-- changing the semantics. Note that `R_red` is independent of env.
show Gdt.eval_option (Gdt.remove_rhss R_red gdt) env = gdt.eval env,
from redundant_rhss_removable gdt gdt_disjoint env _ red_in_gdt,
end
|
66486494d10da7ecd87d642ad4de67f64bd06c15 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/pnat/xgcd.lean | 2027de1c747b54f498d7f98805f36086f10ff179 | [
"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,617 | lean | /-
Copyright (c) 2019 Neil Strickland. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Neil Strickland
-/
import tactic.ring
import data.pnat.prime
/-!
# Euclidean algorithm for ℕ
This file sets up a version of the Euclidean algorithm that only works with natural numbers.
Given `0 < a, b`, it computes the unique `(w, x, y, z, d)` such that the following identities hold:
* `a = (w + x) d`
* `b = (y + z) d`
* `w * z = x * y + 1`
`d` is then the gcd of `a` and `b`, and `a' := a / d = w + x` and `b' := b / d = y + z` are coprime.
This story is closely related to the structure of SL₂(ℕ) (as a free monoid on two generators) and
the theory of continued fractions.
## Main declarations
* `xgcd_type`: Helper type in defining the gcd. Encapsulates `(wp, x, y, zp, ap, bp)`. where `wp`
`zp`, `ap`, `bp` are the variables getting changed through the algorithm.
* `is_special`: States `wp * zp = x * y + 1`
* `is_reduced`: States `ap = a ∧ bp = b`
## Notes
See `nat.xgcd` for a very similar algorithm allowing values in `ℤ`.
-/
open nat
namespace pnat
/-- A term of xgcd_type is a system of six naturals. They should
be thought of as representing the matrix
[[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]]
together with the vector [a, b] = [ap + 1, bp + 1].
-/
@[derive inhabited]
structure xgcd_type :=
(wp x y zp ap bp : ℕ)
namespace xgcd_type
variable (u : xgcd_type)
instance : has_sizeof xgcd_type := ⟨λ u, u.bp⟩
/-- The has_repr instance converts terms to strings in a way that
reflects the matrix/vector interpretation as above. -/
instance : has_repr xgcd_type :=
⟨λ u, "[[[" ++ (repr (u.wp + 1)) ++ ", " ++ (repr u.x) ++
"], [" ++ (repr u.y) ++ ", " ++ (repr (u.zp + 1)) ++ "]], [" ++
(repr (u.ap + 1)) ++ ", " ++ (repr (u.bp + 1)) ++ "]]"⟩
def mk' (w : ℕ+) (x : ℕ) (y : ℕ) (z : ℕ+) (a : ℕ+) (b : ℕ+) : xgcd_type :=
mk w.val.pred x y z.val.pred a.val.pred b.val.pred
def w : ℕ+ := succ_pnat u.wp
def z : ℕ+ := succ_pnat u.zp
def a : ℕ+ := succ_pnat u.ap
def b : ℕ+ := succ_pnat u.bp
def r : ℕ := (u.ap + 1) % (u.bp + 1)
def q : ℕ := (u.ap + 1) / (u.bp + 1)
def qp : ℕ := u.q - 1
/-- The map v gives the product of the matrix
[[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]]
and the vector [a, b] = [ap + 1, bp + 1]. The map
vp gives [sp, tp] such that v = [sp + 1, tp + 1].
-/
def vp : ℕ × ℕ :=
⟨ u.wp + u.x + u.ap + u.wp * u.ap + u.x * u.bp,
u.y + u.zp + u.bp + u.y * u.ap + u.zp * u.bp ⟩
def v : ℕ × ℕ := ⟨u.w * u.a + u.x * u.b, u.y * u.a + u.z * u.b⟩
def succ₂ (t : ℕ × ℕ) : ℕ × ℕ := ⟨t.1.succ, t.2.succ⟩
theorem v_eq_succ_vp : u.v = succ₂ u.vp :=
by { ext; dsimp [v, vp, w, z, a, b, succ₂];
repeat { rw [nat.succ_eq_add_one] }; ring }
/-- is_special holds if the matrix has determinant one. -/
def is_special : Prop := u.wp + u.zp + u.wp * u.zp = u.x * u.y
def is_special' : Prop := u.w * u.z = succ_pnat (u.x * u.y)
theorem is_special_iff : u.is_special ↔ u.is_special' :=
begin
dsimp [is_special, is_special'],
split; intro h,
{ apply eq, dsimp [w, z, succ_pnat], rw [← h],
repeat { rw [nat.succ_eq_add_one] }, ring },
{ apply nat.succ.inj,
replace h := congr_arg (coe : ℕ+ → ℕ) h,
rw [mul_coe, w, z] at h,
repeat { rw [succ_pnat_coe, nat.succ_eq_add_one] at h },
repeat { rw [nat.succ_eq_add_one] }, rw [← h], ring }
end
/-- is_reduced holds if the two entries in the vector are the
same. The reduction algorithm will produce a system with this
property, whose product vector is the same as for the original
system. -/
def is_reduced : Prop := u.ap = u.bp
def is_reduced' : Prop := u.a = u.b
theorem is_reduced_iff : u.is_reduced ↔ u.is_reduced' := succ_pnat_inj.symm
def flip : xgcd_type :=
{ wp := u.zp, x := u.y, y := u.x, zp := u.wp, ap := u.bp, bp := u.ap }
@[simp] theorem flip_w : (flip u).w = u.z := rfl
@[simp] theorem flip_x : (flip u).x = u.y := rfl
@[simp] theorem flip_y : (flip u).y = u.x := rfl
@[simp] theorem flip_z : (flip u).z = u.w := rfl
@[simp] theorem flip_a : (flip u).a = u.b := rfl
@[simp] theorem flip_b : (flip u).b = u.a := rfl
theorem flip_is_reduced : (flip u).is_reduced ↔ u.is_reduced :=
by { dsimp [is_reduced, flip], split; intro h; exact h.symm }
theorem flip_is_special : (flip u).is_special ↔ u.is_special :=
by { dsimp [is_special, flip], rw[mul_comm u.x, mul_comm u.zp, add_comm u.zp] }
theorem flip_v : (flip u).v = (u.v).swap :=
by { dsimp [v], ext, { simp only, ring }, { simp only, ring } }
/-- Properties of division with remainder for a / b. -/
theorem rq_eq : u.r + (u.bp + 1) * u.q = u.ap + 1 :=
nat.mod_add_div (u.ap + 1) (u.bp + 1)
theorem qp_eq (hr : u.r = 0) : u.q = u.qp + 1 :=
begin
by_cases hq : u.q = 0,
{ let h := u.rq_eq, rw [hr, hq, mul_zero, add_zero] at h, cases h },
{ exact (nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hq)).symm }
end
/-- The following function provides the starting point for
our algorithm. We will apply an iterative reduction process
to it, which will produce a system satisfying is_reduced.
The gcd can be read off from this final system.
-/
def start (a b : ℕ+) : xgcd_type := ⟨0, 0, 0, 0, a - 1, b - 1⟩
theorem start_is_special (a b : ℕ+) : (start a b).is_special :=
by { dsimp [start, is_special], refl }
theorem start_v (a b : ℕ+) : (start a b).v = ⟨a, b⟩ :=
begin
dsimp [start, v, xgcd_type.a, xgcd_type.b, w, z],
rw [one_mul, one_mul, zero_mul, zero_mul, zero_add, add_zero],
rw [← nat.pred_eq_sub_one, ← nat.pred_eq_sub_one],
rw [nat.succ_pred_eq_of_pos a.pos, nat.succ_pred_eq_of_pos b.pos]
end
def finish : xgcd_type :=
xgcd_type.mk u.wp ((u.wp + 1) * u.qp + u.x) u.y (u.y * u.qp + u.zp) u.bp u.bp
theorem finish_is_reduced : u.finish.is_reduced :=
by { dsimp [is_reduced], refl }
theorem finish_is_special (hs : u.is_special) : u.finish.is_special :=
begin
dsimp [is_special, finish] at hs ⊢,
rw [add_mul _ _ u.y, add_comm _ (u.x * u.y), ← hs],
ring
end
theorem finish_v (hr : u.r = 0) : u.finish.v = u.v :=
begin
let ha : u.r + u.b * u.q = u.a := u.rq_eq,
rw [hr, zero_add] at ha,
ext,
{ change (u.wp + 1) * u.b + ((u.wp + 1) * u.qp + u.x) * u.b = u.w * u.a + u.x * u.b,
have : u.wp + 1 = u.w := rfl, rw [this, ← ha, u.qp_eq hr], ring },
{ change u.y * u.b + (u.y * u.qp + u.z) * u.b = u.y * u.a + u.z * u.b,
rw [← ha, u.qp_eq hr], ring }
end
/-- This is the main reduction step, which is used when u.r ≠ 0, or
equivalently b does not divide a. -/
def step : xgcd_type :=
xgcd_type.mk (u.y * u.q + u.zp) u.y ((u.wp + 1) * u.q + u.x) u.wp u.bp (u.r - 1)
/-- We will apply the above step recursively. The following result
is used to ensure that the process terminates. -/
theorem step_wf (hr : u.r ≠ 0) : sizeof u.step < sizeof u :=
begin
change u.r - 1 < u.bp,
have h₀ : (u.r - 1) + 1 = u.r := nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hr),
have h₁ : u.r < u.bp + 1 := nat.mod_lt (u.ap + 1) u.bp.succ_pos,
rw[← h₀] at h₁,
exact lt_of_succ_lt_succ h₁,
end
theorem step_is_special (hs : u.is_special) : u.step.is_special :=
begin
dsimp [is_special, step] at hs ⊢,
rw [mul_add, mul_comm u.y u.x, ← hs],
ring
end
/-- The reduction step does not change the product vector. -/
theorem step_v (hr : u.r ≠ 0) : u.step.v = (u.v).swap :=
begin
let ha : u.r + u.b * u.q = u.a := u.rq_eq,
let hr : (u.r - 1) + 1 = u.r :=
(add_comm _ 1).trans (add_tsub_cancel_of_le (nat.pos_of_ne_zero hr)),
ext,
{ change ((u.y * u.q + u.z) * u.b + u.y * (u.r - 1 + 1) : ℕ) = u.y * u.a + u.z * u.b,
rw [← ha, hr], ring },
{ change ((u.w * u.q + u.x) * u.b + u.w * (u.r - 1 + 1) : ℕ) = u.w * u.a + u.x * u.b,
rw [← ha, hr], ring }
end
/-- We can now define the full reduction function, which applies
step as long as possible, and then applies finish. Note that the
"have" statement puts a fact in the local context, and the
equation compiler uses this fact to help construct the full
definition in terms of well-founded recursion. The same fact
needs to be introduced in all the inductive proofs of properties
given below. -/
def reduce : xgcd_type → xgcd_type
| u := dite (u.r = 0)
(λ h, u.finish)
(λ h, have sizeof u.step < sizeof u, from u.step_wf h,
flip (reduce u.step))
theorem reduce_a {u : xgcd_type} (h : u.r = 0) :
u.reduce = u.finish := by { rw [reduce], simp only, rw [if_pos h] }
theorem reduce_b {u : xgcd_type} (h : u.r ≠ 0) :
u.reduce = u.step.reduce.flip := by { rw [reduce], simp only, rw [if_neg h, step] }
theorem reduce_reduced : ∀ (u : xgcd_type), u.reduce.is_reduced
| u := dite (u.r = 0) (λ h, by { rw [reduce_a h], exact u.finish_is_reduced })
(λ h, have sizeof u.step < sizeof u, from u.step_wf h,
by { rw [reduce_b h, flip_is_reduced], apply reduce_reduced })
theorem reduce_reduced' (u : xgcd_type) : u.reduce.is_reduced' :=
(is_reduced_iff _).mp u.reduce_reduced
theorem reduce_special : ∀ (u : xgcd_type), u.is_special → u.reduce.is_special
| u := dite (u.r = 0)
(λ h hs, by { rw [reduce_a h], exact u.finish_is_special hs })
(λ h hs, have sizeof u.step < sizeof u, from u.step_wf h,
by { rw [reduce_b h],
exact (flip_is_special _).mpr (reduce_special _ (u.step_is_special hs)) })
theorem reduce_special' (u : xgcd_type) (hs : u.is_special) : u.reduce.is_special' :=
(is_special_iff _).mp (u.reduce_special hs)
theorem reduce_v : ∀ (u : xgcd_type), u.reduce.v = u.v
| u := dite (u.r = 0)
(λ h, by {rw[reduce_a h, finish_v u h]})
(λ h, have sizeof u.step < sizeof u, from u.step_wf h,
by { rw[reduce_b h, flip_v, reduce_v (step u), step_v u h, prod.swap_swap] })
end xgcd_type
section gcd
variables (a b : ℕ+)
def xgcd : xgcd_type := (xgcd_type.start a b).reduce
def gcd_d : ℕ+ := (xgcd a b).a
def gcd_w : ℕ+ := (xgcd a b).w
def gcd_x : ℕ := (xgcd a b).x
def gcd_y : ℕ := (xgcd a b).y
def gcd_z : ℕ+ := (xgcd a b).z
def gcd_a' : ℕ+ := succ_pnat ((xgcd a b).wp + (xgcd a b).x)
def gcd_b' : ℕ+ := succ_pnat ((xgcd a b).y + (xgcd a b).zp)
theorem gcd_a'_coe : ((gcd_a' a b) : ℕ) = (gcd_w a b) + (gcd_x a b) :=
by { dsimp [gcd_a', gcd_x, gcd_w, xgcd_type.w],
rw [nat.succ_eq_add_one, nat.succ_eq_add_one, add_right_comm] }
theorem gcd_b'_coe : ((gcd_b' a b) : ℕ) = (gcd_y a b) + (gcd_z a b) :=
by { dsimp [gcd_b', gcd_y, gcd_z, xgcd_type.z],
rw [nat.succ_eq_add_one, nat.succ_eq_add_one, add_assoc] }
theorem gcd_props :
let d := gcd_d a b,
w := gcd_w a b, x := gcd_x a b, y := gcd_y a b, z := gcd_z a b,
a' := gcd_a' a b, b' := gcd_b' a b in
(w * z = succ_pnat (x * y) ∧
(a = a' * d) ∧ (b = b' * d) ∧
z * a' = succ_pnat (x * b') ∧ w * b' = succ_pnat (y * a') ∧
(z * a : ℕ) = x * b + d ∧ (w * b : ℕ) = y * a + d
) :=
begin
intros,
let u := (xgcd_type.start a b),
let ur := u.reduce,
have ha : d = ur.a := rfl,
have hb : d = ur.b := u.reduce_reduced',
have ha' : (a' : ℕ) = w + x := gcd_a'_coe a b,
have hb' : (b' : ℕ) = y + z := gcd_b'_coe a b,
have hdet : w * z = succ_pnat (x * y) := u.reduce_special' rfl,
split, exact hdet,
have hdet' : ((w * z) : ℕ) = x * y + 1 :=
by { rw [← mul_coe, hdet, succ_pnat_coe] },
have huv : u.v = ⟨a, b⟩ := (xgcd_type.start_v a b),
let hv : prod.mk (w * d + x * ur.b : ℕ) (y * d + z * ur.b : ℕ) = ⟨a, b⟩ :=
u.reduce_v.trans (xgcd_type.start_v a b),
rw [← hb, ← add_mul, ← add_mul, ← ha', ← hb'] at hv,
have ha'' : (a : ℕ) = a' * d := (congr_arg prod.fst hv).symm,
have hb'' : (b : ℕ) = b' * d := (congr_arg prod.snd hv).symm,
split, exact eq ha'', split, exact eq hb'',
have hza' : (z * a' : ℕ) = x * b' + 1,
by { rw [ha', hb', mul_add, mul_add, mul_comm (z : ℕ), hdet'], ring },
have hwb' : (w * b' : ℕ) = y * a' + 1,
by { rw [ha', hb', mul_add, mul_add, hdet'], ring },
split,
{ apply eq, rw [succ_pnat_coe, nat.succ_eq_add_one, mul_coe, hza'] },
split,
{ apply eq, rw [succ_pnat_coe, nat.succ_eq_add_one, mul_coe, hwb'] },
rw [ha'', hb''], repeat { rw [← mul_assoc] }, rw [hza', hwb'],
split; ring,
end
theorem gcd_eq : gcd_d a b = gcd a b :=
begin
rcases gcd_props a b with ⟨h₀, h₁, h₂, h₃, h₄, h₅, h₆⟩,
apply dvd_antisymm,
{ apply dvd_gcd,
exact dvd.intro (gcd_a' a b) (h₁.trans (mul_comm _ _)).symm,
exact dvd.intro (gcd_b' a b) (h₂.trans (mul_comm _ _)).symm},
{ have h₇ : (gcd a b : ℕ) ∣ (gcd_z a b) * a :=
(nat.gcd_dvd_left a b).trans (dvd_mul_left _ _),
have h₈ : (gcd a b : ℕ) ∣ (gcd_x a b) * b :=
(nat.gcd_dvd_right a b).trans (dvd_mul_left _ _),
rw[h₅] at h₇, rw dvd_iff,
exact (nat.dvd_add_iff_right h₈).mpr h₇,}
end
theorem gcd_det_eq :
(gcd_w a b) * (gcd_z a b) = succ_pnat ((gcd_x a b) * (gcd_y a b)) :=
(gcd_props a b).1
theorem gcd_a_eq : a = (gcd_a' a b) * (gcd a b) :=
(gcd_eq a b) ▸ (gcd_props a b).2.1
theorem gcd_b_eq : b = (gcd_b' a b) * (gcd a b) :=
(gcd_eq a b) ▸ (gcd_props a b).2.2.1
theorem gcd_rel_left' :
(gcd_z a b) * (gcd_a' a b) = succ_pnat ((gcd_x a b) * (gcd_b' a b)) :=
(gcd_props a b).2.2.2.1
theorem gcd_rel_right' :
(gcd_w a b) * (gcd_b' a b) = succ_pnat ((gcd_y a b) * (gcd_a' a b)) :=
(gcd_props a b).2.2.2.2.1
theorem gcd_rel_left :
((gcd_z a b) * a : ℕ) = (gcd_x a b) * b + (gcd a b) :=
(gcd_eq a b) ▸ (gcd_props a b).2.2.2.2.2.1
theorem gcd_rel_right :
((gcd_w a b) * b : ℕ) = (gcd_y a b) * a + (gcd a b) :=
(gcd_eq a b) ▸ (gcd_props a b).2.2.2.2.2.2
end gcd
end pnat
|
0c15c14e8c9df3624ca8e1b56ee3083884f8392e | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/tactic/mk_iff_of_inductive_prop.lean | 593e5e4bc368ab8856f144d06e91815351c0a694 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 6,928 | 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
Generation function for iff rules for inductives, like for `list.chain`:
∀{α : Type*} (R : α → α → Prop) (a : α) (l : list α),
chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l'
-/
import meta.coinductive_predicates
namespace tactic
open tactic expr
meta def mk_iff (e₀ : expr) (e₁ : expr) : expr := `(%%e₀ ↔ %%e₁)
meta def select : ℕ → ℕ → tactic unit
| 0 0 := skip
| 0 (n + 1) := left >> skip
| (m + 1) (n + 1) := right >> select m n
| (n + 1) 0 := failure
/-- `compact_relation bs as_ps`: Produce a relation of the form:
R as := ∃ bs, Λ_i a_i = p_i[bs]
This relation is user visible, so we compact it by removing each `b_j` where a `p_i = b_j`, and
hence `a_i = b_j`. We need to take care when there are `p_i` and `p_j` with `p_i = p_j = b_k`.
TODO: this is copied from Lean's `coinductive_predicates.lean`, export it there.
-/
private meta def compact_relation :
list expr → list (expr × expr) → list (option expr) × list (expr × expr)
| [] ps := ([], ps)
| (b :: bs) ps :=
match ps.span (λap:expr × expr, ¬ ap.2 =ₐ b) with
| (_, []) := let (bs, ps) := compact_relation bs ps in (b::bs, ps)
| (ps₁, list.cons (a, _) ps₂) :=
let
i := a.instantiate_local b.local_uniq_name,
(bs, ps) := compact_relation (bs.map i) ((ps₁ ++ ps₂).map (λ⟨a, p⟩, (a, i p)))
in (none :: bs, ps)
end
meta def constr_to_prop (univs : list level) (g : list expr) (idxs : list expr) (c : name) :
tactic ((list (option expr) × (expr ⊕ ℕ)) × expr) := do
e ← get_env,
decl ← get_decl c,
some type' ← return $ decl.instantiate_type_univ_params univs,
type ← drop_pis g type',
(args, res) ← mk_local_pis type,
let idxs_inst := res.get_app_args.drop g.length,
let (bs, eqs) := compact_relation args (idxs.zip idxs_inst),
let bs' := bs.filter_map id,
eqs ← eqs.mmap (λ⟨idx, inst⟩, do
let ty := idx.local_type,
inst_ty ← infer_type inst,
sort u ← infer_type ty,
(is_def_eq ty inst_ty >> return ((const `eq [u] : expr) ty idx inst)) <|>
return ((const `heq [u] : expr) ty idx inst_ty inst)),
(n, r) ← match bs', eqs with
| [], [] := return (sum.inr 0, mk_true)
| _, [] := do
let t : expr := bs'.ilast.local_type,
sort l ← infer_type t,
if l = level.zero then do
r ← mk_exists_lst bs'.init t,
return (sum.inl bs'.ilast, r)
else do
r ← mk_exists_lst bs' mk_true,
return (sum.inr 0, r)
| _, _ := do
r ← mk_exists_lst bs' (mk_and_lst eqs),
return (sum.inr eqs.length, r)
end,
return ((bs, n), r)
private meta def to_cases (s : list $ list (option expr) × (expr ⊕ ℕ)) : tactic unit := do
h ← intro1,
i ← induction h,
focus ((s.zip i).enum.map $ λ⟨p, (shape, t), _, vars, _⟩, do
let si := (shape.zip vars).filter_map (λ⟨c, v⟩, c >>= λ _, some v),
select p (s.length - 1),
match t with
| sum.inl e := do
si.init.mmap' existsi,
some v ← return $ vars.nth (shape.length - 1),
exact v
| sum.inr n := do
si.mmap' existsi,
iterate_exactly (n - 1) (split >> constructor >> skip) >> constructor >> skip
end,
done),
done
private def list_option_merge {α : Type*} {β : Type*} : list (option α) → list β → list (option β)
| [] _ := []
| (none :: xs) ys := none :: list_option_merge xs ys
| (some a :: xs) (y :: ys) := some y :: list_option_merge xs ys
| (some a :: xs) [] := []
private meta def to_inductive
(cs : list name) (gs : list expr) (s : list (list (option expr) × (expr ⊕ ℕ))) (h : expr) :
tactic unit :=
match s.length with
| 0 := induction h >> skip
| (n + 1) := do
r ← elim_gen_sum n h,
focus ((cs.zip (r.zip s)).map $ λ⟨constr_name, h, bs, e⟩, do
let n := (bs.filter_map id).length,
match e with
| sum.inl e := elim_gen_prod (n - 1) h [] >> skip
| sum.inr 0 := do
(hs, h) ← elim_gen_prod n h [],
clear h
| sum.inr (e + 1) := do
(hs, h) ← elim_gen_prod n h [],
(es, eq) ← elim_gen_prod e h [],
let es := es ++ [eq],
/- `es.mmap' subst`: fails when we have dependent equalities (heq). `subst will change the
dependent hypotheses, so that the uniq local names in `es` are wrong afterwards. Instead
we revert them and pull them out one by one -/
revert_lst es,
es.mmap' (λ_, intro1 >>= subst)
end,
ctxt ← local_context,
let gs := ctxt.take gs.length,
let hs := (ctxt.reverse.take n).reverse,
let m := gs.map some ++ list_option_merge bs hs,
args ← m.mmap (λa, match a with some v := return v | none := mk_mvar end),
c ← mk_const constr_name,
exact (c.mk_app args),
done),
done
end
/-- `mk_iff_of_inductive_prop i r` makes a iff rule for the inductively defined proposition `i`.
The new rule `r` has the shape `∀ps is, i as ↔ ⋁_j, ∃cs, is = cs`, where `ps` are the type
parameters, `is` are the indices, `j` ranges over all possible constructors, the `cs` are the
parameters for each constructors, the equalities `is = cs` are the instantiations for each
constructor for each of the indices to the inductive type `i`.
In each case, we remove constructor parameters (i.e. `cs`) when the corresponding equality would
be just `c = i` for some index `i`.
For example: `mk_iff_of_inductive_prop` on `list.chain` produces:
∀{α : Type*} (R : α → α → Prop) (a : α) (l : list α),
chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l'
-/
meta def mk_iff_of_inductive_prop (i : name) (r : name) : tactic unit := do
e ← get_env,
guard (e.is_inductive i),
let constrs := e.constructors_of i,
let params := e.inductive_num_params i,
let indices := e.inductive_num_indices i,
let rec := match e.recursor_of i with some rec := rec | none := i.append `rec end,
decl ← get_decl i,
let type := decl.type,
let univ_names := decl.univ_params,
let univs := univ_names.map level.param,
/- we use these names for our universe parameters, maybe we should construct a copy of them using uniq_name -/
(g, `(Prop)) ← mk_local_pis type | fail "Inductive type is not a proposition",
let lhs := (const i univs).mk_app g,
shape_rhss ← constrs.mmap (constr_to_prop univs (g.take params) (g.drop params)),
let shape := shape_rhss.map prod.fst,
let rhss := shape_rhss.map prod.snd,
add_theorem_by r univ_names ((mk_iff lhs (mk_or_lst rhss)).pis g) (do
gs ← intro_lst (g.map local_pp_name),
split,
focus [to_cases shape, intro1 >>= to_inductive constrs (gs.take params) shape]),
skip
end tactic
|
65104507460f586b753beff11e991e2e803cb5eb | 8cb37a089cdb4af3af9d8bf1002b417e407a8e9e | /library/init/function.lean | c7c2c729b3cfbb4844a45a6d90b0845915b4f19d | [
"Apache-2.0"
] | permissive | kbuzzard/lean | ae3c3db4bb462d750dbf7419b28bafb3ec983ef7 | ed1788fd674bb8991acffc8fca585ec746711928 | refs/heads/master | 1,620,983,366,617 | 1,618,937,600,000 | 1,618,937,600,000 | 359,886,396 | 1 | 0 | Apache-2.0 | 1,618,936,987,000 | 1,618,936,987,000 | null | UTF-8 | Lean | false | false | 6,645 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura, Jeremy Avigad, Haitao Zhang
-/
prelude
import init.data.prod init.funext init.logic
/-!
# General operations on functions
-/
universes u₁ u₂ u₃ u₄
namespace function
variables {α : Sort u₁} {β : Sort u₂} {φ : Sort u₃} {δ : Sort u₄} {ζ : Sort u₁}
/-- Composition of functions: `(f ∘ g) x = f (g x)`. -/
@[inline, reducible] def comp (f : β → φ) (g : α → β) : α → φ :=
λ x, f (g x)
/-- Composition of dependent functions: `(f ∘' g) x = f (g x)`, where type of `g x` depends on `x`
and type of `f (g x)` depends on `x` and `g x`. -/
@[inline, reducible] def dcomp {β : α → Sort u₂} {φ : Π {x : α}, β x → Sort u₃}
(f : Π {x : α} (y : β x), φ y) (g : Π x, β x) : Π x, φ (g x) :=
λ x, f (g x)
infixr ` ∘ ` := function.comp
infixr ` ∘' `:80 := function.dcomp
@[reducible] def comp_right (f : β → β → β) (g : α → β) : β → α → β :=
λ b a, f b (g a)
@[reducible] def comp_left (f : β → β → β) (g : α → β) : α → β → β :=
λ a b, f (g a) b
/-- Given functions `f : β → β → φ` and `g : α → β`, produce a function `α → α → φ` that evaluates
`g` on each argument, then applies `f` to the results. Can be used, e.g., to transfer a relation
from `β` to `α`. -/
@[reducible] def on_fun (f : β → β → φ) (g : α → β) : α → α → φ :=
λ x y, f (g x) (g y)
@[reducible] def combine (f : α → β → φ) (op : φ → δ → ζ) (g : α → β → δ)
: α → β → ζ :=
λ x y, op (f x y) (g x y)
/-- Constant `λ _, a`. -/
@[reducible] def const (β : Sort u₂) (a : α) : β → α :=
λ x, a
@[reducible] def swap {φ : α → β → Sort u₃} (f : Π x y, φ x y) : Π y x, φ x y :=
λ y x, f x y
@[reducible] def app {β : α → Sort u₂} (f : Π x, β x) (x : α) : β x :=
f x
infixl ` on `:2 := on_fun
notation f ` -[` op `]- ` g := combine f op g
lemma left_id (f : α → β) : id ∘ f = f := rfl
lemma right_id (f : α → β) : f ∘ id = f := rfl
@[simp] lemma comp_app (f : β → φ) (g : α → β) (a : α) : (f ∘ g) a = f (g a) := rfl
lemma comp.assoc (f : φ → δ) (g : β → φ) (h : α → β) : (f ∘ g) ∘ h = f ∘ (g ∘ h) := rfl
@[simp] lemma comp.left_id (f : α → β) : id ∘ f = f := rfl
@[simp] lemma comp.right_id (f : α → β) : f ∘ id = f := rfl
lemma comp_const_right (f : β → φ) (b : β) : f ∘ (const α b) = const α (f b) := rfl
/-- A function `f : α → β` is called injective if `f x = f y` implies `x = y`. -/
@[reducible] def injective (f : α → β) : Prop := ∀ ⦃a₁ a₂⦄, f a₁ = f a₂ → a₁ = a₂
lemma injective.comp {g : β → φ} {f : α → β} (hg : injective g) (hf : injective f) :
injective (g ∘ f) :=
assume a₁ a₂, assume h, hf (hg h)
/-- A function `f : α → β` is calles surjective if every `b : β` is equal to `f a`
for some `a : α`. -/
@[reducible] def surjective (f : α → β) : Prop := ∀ b, ∃ a, f a = b
lemma surjective.comp {g : β → φ} {f : α → β} (hg : surjective g) (hf : surjective f) :
surjective (g ∘ f) :=
λ (c : φ), exists.elim (hg c) (λ b hb, exists.elim (hf b) (λ a ha,
exists.intro a (show g (f a) = c, from (eq.trans (congr_arg g ha) hb))))
/-- A function is called bijective if it is both injective and surjective. -/
def bijective (f : α → β) := injective f ∧ surjective f
lemma bijective.comp {g : β → φ} {f : α → β} : bijective g → bijective f → bijective (g ∘ f)
| ⟨h_ginj, h_gsurj⟩ ⟨h_finj, h_fsurj⟩ := ⟨h_ginj.comp h_finj, h_gsurj.comp h_fsurj⟩
/-- `left_inverse g f` means that g is a left inverse to f. That is, `g ∘ f = id`. -/
def left_inverse (g : β → α) (f : α → β) : Prop := ∀ x, g (f x) = x
/-- `has_left_inverse f` means that `f` has an unspecified left inverse. -/
def has_left_inverse (f : α → β) : Prop := ∃ finv : β → α, left_inverse finv f
/-- `right_inverse g f` means that g is a right inverse to f. That is, `f ∘ g = id`. -/
def right_inverse (g : β → α) (f : α → β) : Prop := left_inverse f g
/-- `has_right_inverse f` means that `f` has an unspecified right inverse. -/
def has_right_inverse (f : α → β) : Prop := ∃ finv : β → α, right_inverse finv f
lemma left_inverse.injective {g : β → α} {f : α → β} : left_inverse g f → injective f :=
assume h a b faeqfb,
calc a = g (f a) : (h a).symm
... = g (f b) : congr_arg g faeqfb
... = b : h b
lemma has_left_inverse.injective {f : α → β} : has_left_inverse f → injective f :=
assume h, exists.elim h (λ finv inv, inv.injective)
lemma right_inverse_of_injective_of_left_inverse {f : α → β} {g : β → α}
(injf : injective f) (lfg : left_inverse f g) :
right_inverse f g :=
assume x,
have h : f (g (f x)) = f x, from lfg (f x),
injf h
lemma right_inverse.surjective {f : α → β} {g : β → α} (h : right_inverse g f) : surjective f :=
assume y, ⟨g y, h y⟩
lemma has_right_inverse.surjective {f : α → β} : has_right_inverse f → surjective f
| ⟨finv, inv⟩ := inv.surjective
lemma left_inverse_of_surjective_of_right_inverse {f : α → β} {g : β → α}
(surjf : surjective f) (rfg : right_inverse f g) :
left_inverse f g :=
assume y, exists.elim (surjf y) (λ x hx, calc
f (g y) = f (g (f x)) : hx ▸ rfl
... = f x : eq.symm (rfg x) ▸ rfl
... = y : hx)
lemma injective_id : injective (@id α) := assume a₁ a₂ h, h
lemma surjective_id : surjective (@id α) := assume a, ⟨a, rfl⟩
lemma bijective_id : bijective (@id α) := ⟨injective_id, surjective_id⟩
end function
namespace function
variables {α : Type u₁} {β : Type u₂} {φ : Type u₃}
/-- Interpret a function on `α × β` as a function with two arguments. -/
@[inline] def curry : (α × β → φ) → α → β → φ :=
λ f a b, f (a, b)
/-- Interpret a function with two arguments as a function on `α × β` -/
@[inline] def uncurry : (α → β → φ) → α × β → φ :=
λ f a, f a.1 a.2
@[simp] lemma curry_uncurry (f : α → β → φ) : curry (uncurry f) = f :=
rfl
@[simp] lemma uncurry_curry (f : α × β → φ) : uncurry (curry f) = f :=
funext (λ ⟨a, b⟩, rfl)
protected lemma left_inverse.id {g : β → α} {f : α → β} (h : left_inverse g f) : g ∘ f = id :=
funext h
protected lemma right_inverse.id {g : β → α} {f : α → β} (h : right_inverse g f) : f ∘ g = id :=
funext h
end function
|
c49d51c37569c6cfc67b9024a355e69d57f81bc8 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/seq/seq.lean | 2a18d6727f3ace722550cf166fcc00da74c4d42d | [
"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 | 28,466 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.list.basic
import data.stream.init
import data.lazy_list
import data.seq.computation
universes u v w
/-
coinductive seq (α : Type u) : Type u
| nil : seq α
| cons : α → seq α → seq α
-/
/--
A stream `s : option α` is a sequence if `s.nth n = none` implies `s.nth (n + 1) = none`.
-/
def stream.is_seq {α : Type u} (s : stream (option α)) : Prop :=
∀ {n : ℕ}, s n = none → s (n + 1) = none
/-- `seq α` is the type of possibly infinite lists (referred here as sequences).
It is encoded as an infinite stream of options such that if `f n = none`, then
`f m = none` for all `m ≥ n`. -/
def seq (α : Type u) : Type u := { f : stream (option α) // f.is_seq }
/-- `seq1 α` is the type of nonempty sequences. -/
def seq1 (α) := α × seq α
namespace seq
variables {α : Type u} {β : Type v} {γ : Type w}
/-- The empty sequence -/
def nil : seq α := ⟨stream.const none, λn h, rfl⟩
instance : inhabited (seq α) := ⟨nil⟩
/-- Prepend an element to a sequence -/
def cons (a : α) : seq α → seq α
| ⟨f, al⟩ := ⟨some a :: f, λn h, by {cases n with n, contradiction, exact al h}⟩
/-- Get the nth element of a sequence (if it exists) -/
def nth : seq α → ℕ → option α := subtype.val
/-- A sequence has terminated at position `n` if the value at position `n` equals `none`. -/
def terminated_at (s : seq α) (n : ℕ) : Prop := s.nth n = none
/-- It is decidable whether a sequence terminates at a given position. -/
instance terminated_at_decidable (s : seq α) (n : ℕ) : decidable (s.terminated_at n) :=
decidable_of_iff' (s.nth n).is_none $ by unfold terminated_at; cases s.nth n; simp
/-- A sequence terminates if there is some position `n` at which it has terminated. -/
def terminates (s : seq α) : Prop := ∃ (n : ℕ), s.terminated_at n
/-- Functorial action of the functor `option (α × _)` -/
@[simp] def omap (f : β → γ) : option (α × β) → option (α × γ)
| none := none
| (some (a, b)) := some (a, f b)
/-- Get the first element of a sequence -/
def head (s : seq α) : option α := nth s 0
/-- Get the tail of a sequence (or `nil` if the sequence is `nil`) -/
def tail : seq α → seq α
| ⟨f, al⟩ := ⟨f.tail, λ n, al⟩
protected def mem (a : α) (s : seq α) := some a ∈ s.1
instance : has_mem α (seq α) :=
⟨seq.mem⟩
theorem le_stable (s : seq α) {m n} (h : m ≤ n) :
s.nth m = none → s.nth n = none :=
by {cases s with f al, induction h with n h IH, exacts [id, λ h2, al (IH h2)]}
/-- If a sequence terminated at position `n`, it also terminated at `m ≥ n `. -/
lemma terminated_stable (s : seq α) {m n : ℕ} (m_le_n : m ≤ n)
(terminated_at_m : s.terminated_at m) :
s.terminated_at n :=
le_stable s m_le_n terminated_at_m
/--
If `s.nth n = some aₙ` for some value `aₙ`, then there is also some value `aₘ` such
that `s.nth = some aₘ` for `m ≤ n`.
-/
lemma ge_stable (s : seq α) {aₙ : α} {n m : ℕ} (m_le_n : m ≤ n)
(s_nth_eq_some : s.nth n = some aₙ) :
∃ (aₘ : α), s.nth m = some aₘ :=
have s.nth n ≠ none, by simp [s_nth_eq_some],
have s.nth m ≠ none, from mt (s.le_stable m_le_n) this,
option.ne_none_iff_exists'.mp this
theorem not_mem_nil (a : α) : a ∉ @nil α :=
λ ⟨n, (h : some a = none)⟩, by injection h
theorem mem_cons (a : α) : ∀ (s : seq α), a ∈ cons a s
| ⟨f, al⟩ := stream.mem_cons (some a) _
theorem mem_cons_of_mem (y : α) {a : α} : ∀ {s : seq α}, a ∈ s → a ∈ cons y s
| ⟨f, al⟩ := stream.mem_cons_of_mem (some y)
theorem eq_or_mem_of_mem_cons {a b : α} : ∀ {s : seq α}, a ∈ cons b s → a = b ∨ a ∈ s
| ⟨f, al⟩ h := (stream.eq_or_mem_of_mem_cons h).imp_left (λh, by injection h)
@[simp] theorem mem_cons_iff {a b : α} {s : seq α} : a ∈ cons b s ↔ a = b ∨ a ∈ s :=
⟨eq_or_mem_of_mem_cons, λo, by cases o with e m;
[{rw e, apply mem_cons}, exact mem_cons_of_mem _ m]⟩
/-- Destructor for a sequence, resulting in either `none` (for `nil`) or
`some (a, s)` (for `cons a s`). -/
def destruct (s : seq α) : option (seq1 α) :=
(λa', (a', s.tail)) <$> nth s 0
theorem destruct_eq_nil {s : seq α} : destruct s = none → s = nil :=
begin
dsimp [destruct],
induction f0 : nth s 0; intro h,
{ apply subtype.eq,
funext n,
induction n with n IH, exacts [f0, s.2 IH] },
{ contradiction }
end
theorem destruct_eq_cons {s : seq α} {a s'} : destruct s = some (a, s') → s = cons a s' :=
begin
dsimp [destruct],
induction f0 : nth s 0 with a'; intro h,
{ contradiction },
{ cases s with f al,
injections with _ h1 h2,
rw ←h2, apply subtype.eq, dsimp [tail, cons],
rw h1 at f0, rw ←f0,
exact (stream.eta f).symm }
end
@[simp] theorem destruct_nil : destruct (nil : seq α) = none := rfl
@[simp] theorem destruct_cons (a : α) : ∀ s, destruct (cons a s) = some (a, s)
| ⟨f, al⟩ := begin
unfold cons destruct functor.map,
apply congr_arg (λ s, some (a, s)),
apply subtype.eq, dsimp [tail], rw [stream.tail_cons]
end
theorem head_eq_destruct (s : seq α) : head s = prod.fst <$> destruct s :=
by unfold destruct head; cases nth s 0; refl
@[simp] theorem head_nil : head (nil : seq α) = none := rfl
@[simp] theorem head_cons (a : α) (s) : head (cons a s) = some a :=
by rw [head_eq_destruct, destruct_cons]; refl
@[simp] theorem tail_nil : tail (nil : seq α) = nil := rfl
@[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s :=
by cases s with f al; apply subtype.eq; dsimp [tail, cons]; rw [stream.tail_cons]
def cases_on {C : seq α → Sort v} (s : seq α)
(h1 : C nil) (h2 : ∀ x s, C (cons x s)) : C s := begin
induction H : destruct s with v v,
{ rw destruct_eq_nil H, apply h1 },
{ cases v with a s', rw destruct_eq_cons H, apply h2 }
end
theorem mem_rec_on {C : seq α → Prop} {a s} (M : a ∈ s)
(h1 : ∀ b s', (a = b ∨ C s') → C (cons b s')) : C s :=
begin
cases M with k e, unfold stream.nth at e,
induction k with k IH generalizing s,
{ have TH : s = cons a (tail s),
{ apply destruct_eq_cons,
unfold destruct nth functor.map, rw ←e, refl },
rw TH, apply h1 _ _ (or.inl rfl) },
revert e, apply s.cases_on _ (λ b s', _); intro e,
{ injection e },
{ have h_eq : (cons b s').val (nat.succ k) = s'.val k, { cases s'; refl },
rw [h_eq] at e,
apply h1 _ _ (or.inr (IH e)) }
end
def corec.F (f : β → option (α × β)) : option β → option α × option β
| none := (none, none)
| (some b) := match f b with none := (none, none) | some (a, b') := (some a, some b') end
/-- Corecursor for `seq α` as a coinductive type. Iterates `f` to produce new elements
of the sequence until `none` is obtained. -/
def corec (f : β → option (α × β)) (b : β) : seq α :=
begin
refine ⟨stream.corec' (corec.F f) (some b), λn h, _⟩,
rw stream.corec'_eq,
change stream.corec' (corec.F f) (corec.F f (some b)).2 n = none,
revert h, generalize : some b = o, revert o,
induction n with n IH; intro o,
{ change (corec.F f o).1 = none → (corec.F f (corec.F f o).2).1 = none,
cases o with b; intro h, { refl },
dsimp [corec.F] at h, dsimp [corec.F],
cases f b with s, { refl },
{ cases s with a b', contradiction } },
{ rw [stream.corec'_eq (corec.F f) (corec.F f o).2,
stream.corec'_eq (corec.F f) o],
exact IH (corec.F f o).2 }
end
@[simp] theorem corec_eq (f : β → option (α × β)) (b : β) :
destruct (corec f b) = omap (corec f) (f b) :=
begin
dsimp [corec, destruct, nth],
change stream.corec' (corec.F f) (some b) 0 with (corec.F f (some b)).1,
dsimp [corec.F],
induction h : f b with s, { refl },
cases s with a b', dsimp [corec.F],
apply congr_arg (λ b', some (a, b')),
apply subtype.eq,
dsimp [corec, tail],
rw [stream.corec'_eq, stream.tail_cons],
dsimp [corec.F], rw h, refl
end
/-- Embed a list as a sequence -/
def of_list (l : list α) : seq α :=
⟨list.nth l, λn h, begin
induction l with a l IH generalizing n, refl,
dsimp [list.nth], cases n with n; dsimp [list.nth] at h,
{ contradiction },
{ apply IH _ h }
end⟩
instance coe_list : has_coe (list α) (seq α) := ⟨of_list⟩
section bisim
variable (R : seq α → seq α → Prop)
local infix ` ~ `:50 := R
def bisim_o : option (seq1 α) → option (seq1 α) → Prop
| none none := true
| (some (a, s)) (some (a', s')) := a = a' ∧ R s s'
| _ _ := false
attribute [simp] bisim_o
def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → bisim_o R (destruct s₁) (destruct s₂)
-- If two streams are bisimilar, then they are equal
theorem eq_of_bisim (bisim : is_bisimulation R) {s₁ s₂} (r : s₁ ~ s₂) : s₁ = s₂ :=
begin
apply subtype.eq,
apply stream.eq_of_bisim (λx y, ∃ s s' : seq α, s.1 = x ∧ s'.1 = y ∧ R s s'),
dsimp [stream.is_bisimulation],
intros t₁ t₂ e,
exact match t₁, t₂, e with ._, ._, ⟨s, s', rfl, rfl, r⟩ :=
suffices head s = head s' ∧ R (tail s) (tail s'), from
and.imp id (λr, ⟨tail s, tail s',
by cases s; refl, by cases s'; refl, r⟩) this,
begin
have := bisim r, revert r this,
apply cases_on s _ _; intros; apply cases_on s' _ _; intros; intros r this,
{ constructor, refl, assumption },
{ rw [destruct_nil, destruct_cons] at this,
exact false.elim this },
{ rw [destruct_nil, destruct_cons] at this,
exact false.elim this },
{ rw [destruct_cons, destruct_cons] at this,
rw [head_cons, head_cons, tail_cons, tail_cons],
cases this with h1 h2,
constructor, rw h1, exact h2 }
end
end,
exact ⟨s₁, s₂, rfl, rfl, r⟩
end
end bisim
theorem coinduction : ∀ {s₁ s₂ : seq α}, head s₁ = head s₂ →
(∀ (β : Type u) (fr : seq α → β),
fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂
| ⟨f₁, a₁⟩ ⟨f₂, a₂⟩ hh ht :=
subtype.eq (stream.coinduction hh (λ β fr, ht β (λs, fr s.1)))
theorem coinduction2 (s) (f g : seq α → seq β)
(H : ∀ s, bisim_o (λ (s1 s2 : seq β), ∃ (s : seq α), s1 = f s ∧ s2 = g s)
(destruct (f s)) (destruct (g s)))
: f s = g s :=
begin
refine eq_of_bisim (λ s1 s2, ∃ s, s1 = f s ∧ s2 = g s) _ ⟨s, rfl, rfl⟩,
intros s1 s2 h, rcases h with ⟨s, h1, h2⟩,
rw [h1, h2], apply H
end
/-- Embed an infinite stream as a sequence -/
def of_stream (s : stream α) : seq α :=
⟨s.map some, λn h, by contradiction⟩
instance coe_stream : has_coe (stream α) (seq α) := ⟨of_stream⟩
/-- Embed a `lazy_list α` as a sequence. Note that even though this
is non-meta, it will produce infinite sequences if used with
cyclic `lazy_list`s created by meta constructions. -/
def of_lazy_list : lazy_list α → seq α :=
corec (λl, match l with
| lazy_list.nil := none
| lazy_list.cons a l' := some (a, l' ())
end)
instance coe_lazy_list : has_coe (lazy_list α) (seq α) := ⟨of_lazy_list⟩
/-- Translate a sequence into a `lazy_list`. Since `lazy_list` and `list`
are isomorphic as non-meta types, this function is necessarily meta. -/
meta def to_lazy_list : seq α → lazy_list α | s :=
match destruct s with
| none := lazy_list.nil
| some (a, s') := lazy_list.cons a (to_lazy_list s')
end
/-- Translate a sequence to a list. This function will run forever if
run on an infinite sequence. -/
meta def force_to_list (s : seq α) : list α := (to_lazy_list s).to_list
/-- The sequence of natural numbers some 0, some 1, ... -/
def nats : seq ℕ := stream.nats
@[simp]
lemma nats_nth (n : ℕ) : nats.nth n = some n := rfl
/-- Append two sequences. If `s₁` is infinite, then `s₁ ++ s₂ = s₁`,
otherwise it puts `s₂` at the location of the `nil` in `s₁`. -/
def append (s₁ s₂ : seq α) : seq α :=
@corec α (seq α × seq α) (λ⟨s₁, s₂⟩,
match destruct s₁ with
| none := omap (λs₂, (nil, s₂)) (destruct s₂)
| some (a, s₁') := some (a, s₁', s₂)
end) (s₁, s₂)
/-- Map a function over a sequence. -/
def map (f : α → β) : seq α → seq β | ⟨s, al⟩ :=
⟨s.map (option.map f),
λn, begin
dsimp [stream.map, stream.nth],
induction e : s n; intro,
{ rw al e, assumption }, { contradiction }
end⟩
/-- Flatten a sequence of sequences. (It is required that the
sequences be nonempty to ensure productivity; in the case
of an infinite sequence of `nil`, the first element is never
generated.) -/
def join : seq (seq1 α) → seq α :=
corec (λS, match destruct S with
| none := none
| some ((a, s), S') := some (a, match destruct s with
| none := S'
| some s' := cons s' S'
end)
end)
/-- Remove the first `n` elements from the sequence. -/
def drop (s : seq α) : ℕ → seq α
| 0 := s
| (n+1) := tail (drop n)
attribute [simp] drop
/-- Take the first `n` elements of the sequence (producing a list) -/
def take : ℕ → seq α → list α
| 0 s := []
| (n+1) s := match destruct s with
| none := []
| some (x, r) := list.cons x (take n r)
end
/-- Split a sequence at `n`, producing a finite initial segment
and an infinite tail. -/
def split_at : ℕ → seq α → list α × seq α
| 0 s := ([], s)
| (n+1) s := match destruct s with
| none := ([], nil)
| some (x, s') := let (l, r) := split_at n s' in (list.cons x l, r)
end
section zip_with
/-- Combine two sequences with a function -/
def zip_with (f : α → β → γ) : seq α → seq β → seq γ
| ⟨f₁, a₁⟩ ⟨f₂, a₂⟩ := ⟨λn,
match f₁ n, f₂ n with
| some a, some b := some (f a b)
| _, _ := none
end,
λn, begin
induction h1 : f₁ n,
{ intro H, simp only [(a₁ h1)], refl },
induction h2 : f₂ n; dsimp [seq.zip_with._match_1]; intro H,
{ rw (a₂ h2), cases f₁ (n + 1); refl },
{ rw [h1, h2] at H, contradiction }
end⟩
variables {s : seq α} {s' : seq β} {n : ℕ}
lemma zip_with_nth_some {a : α} {b : β} (s_nth_eq_some : s.nth n = some a)
(s_nth_eq_some' : s'.nth n = some b) (f : α → β → γ) :
(zip_with f s s').nth n = some (f a b) :=
begin
cases s with st,
have : st n = some a, from s_nth_eq_some,
cases s' with st',
have : st' n = some b, from s_nth_eq_some',
simp only [zip_with, seq.nth, *]
end
lemma zip_with_nth_none (s_nth_eq_none : s.nth n = none) (f : α → β → γ) :
(zip_with f s s').nth n = none :=
begin
cases s with st,
have : st n = none, from s_nth_eq_none,
cases s' with st',
cases st'_nth_eq : st' n;
simp only [zip_with, seq.nth, *]
end
lemma zip_with_nth_none' (s'_nth_eq_none : s'.nth n = none) (f : α → β → γ) :
(zip_with f s s').nth n = none :=
begin
cases s' with st',
have : st' n = none, from s'_nth_eq_none,
cases s with st,
cases st_nth_eq : st n;
simp only [zip_with, seq.nth, *]
end
end zip_with
/-- Pair two sequences into a sequence of pairs -/
def zip : seq α → seq β → seq (α × β) := zip_with prod.mk
/-- Separate a sequence of pairs into two sequences -/
def unzip (s : seq (α × β)) : seq α × seq β := (map prod.fst s, map prod.snd s)
/-- Convert a sequence which is known to terminate into a list -/
def to_list (s : seq α) (h : ∃ n, ¬ (nth s n).is_some) : list α :=
take (nat.find h) s
/-- Convert a sequence which is known not to terminate into a stream -/
def to_stream (s : seq α) (h : ∀ n, (nth s n).is_some) : stream α :=
λn, option.get (h n)
/-- Convert a sequence into either a list or a stream depending on whether
it is finite or infinite. (Without decidability of the infiniteness predicate,
this is not constructively possible.) -/
def to_list_or_stream (s : seq α) [decidable (∃ n, ¬ (nth s n).is_some)] :
list α ⊕ stream α :=
if h : ∃ n, ¬ (nth s n).is_some
then sum.inl (to_list s h)
else sum.inr (to_stream s (λn, decidable.by_contradiction (λ hn, h ⟨n, hn⟩)))
@[simp] theorem nil_append (s : seq α) : append nil s = s :=
begin
apply coinduction2, intro s,
dsimp [append], rw [corec_eq],
dsimp [append], apply cases_on s _ _,
{ trivial },
{ intros x s,
rw [destruct_cons], dsimp,
exact ⟨rfl, s, rfl, rfl⟩ }
end
@[simp] theorem cons_append (a : α) (s t) : append (cons a s) t = cons a (append s t) :=
destruct_eq_cons $ begin
dsimp [append], rw [corec_eq],
dsimp [append], rw [destruct_cons],
dsimp [append], refl
end
@[simp] theorem append_nil (s : seq α) : append s nil = s :=
begin
apply coinduction2 s, intro s,
apply cases_on s _ _,
{ trivial },
{ intros x s,
rw [cons_append, destruct_cons, destruct_cons], dsimp,
exact ⟨rfl, s, rfl, rfl⟩ }
end
@[simp] theorem append_assoc (s t u : seq α) :
append (append s t) u = append s (append t u) :=
begin
apply eq_of_bisim (λs1 s2, ∃ s t u,
s1 = append (append s t) u ∧ s2 = append s (append t u)),
{ intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, t, u, rfl, rfl⟩ := begin
apply cases_on s; simp,
{ apply cases_on t; simp,
{ apply cases_on u; simp,
{ intros x u, refine ⟨nil, nil, u, _, _⟩; simp } },
{ intros x t, refine ⟨nil, t, u, _, _⟩; simp } },
{ intros x s, exact ⟨s, t, u, rfl, rfl⟩ }
end end },
{ exact ⟨s, t, u, rfl, rfl⟩ }
end
@[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl
@[simp] theorem map_cons (f : α → β) (a) : ∀ s, map f (cons a s) = cons (f a) (map f s)
| ⟨s, al⟩ := by apply subtype.eq; dsimp [cons, map]; rw stream.map_cons; refl
@[simp] theorem map_id : ∀ (s : seq α), map id s = s
| ⟨s, al⟩ := begin
apply subtype.eq; dsimp [map],
rw [option.map_id, stream.map_id]; refl
end
@[simp] theorem map_tail (f : α → β) : ∀ s, map f (tail s) = tail (map f s)
| ⟨s, al⟩ := by apply subtype.eq; dsimp [tail, map]; rw stream.map_tail; refl
theorem map_comp (f : α → β) (g : β → γ) : ∀ (s : seq α), map (g ∘ f) s = map g (map f s)
| ⟨s, al⟩ := begin
apply subtype.eq; dsimp [map],
rw stream.map_map,
apply congr_arg (λ f : _ → option γ, stream.map f s),
ext ⟨⟩; refl
end
@[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) :=
begin
apply eq_of_bisim (λs1 s2, ∃ s t,
s1 = map f (append s t) ∧ s2 = append (map f s) (map f t)) _ ⟨s, t, rfl, rfl⟩,
intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, t, rfl, rfl⟩ := begin
apply cases_on s; simp,
{ apply cases_on t; simp,
{ intros x t, refine ⟨nil, t, _, _⟩; simp } },
{ intros x s, refine ⟨s, t, rfl, rfl⟩ }
end end
end
@[simp] theorem map_nth (f : α → β) : ∀ s n, nth (map f s) n = (nth s n).map f
| ⟨s, al⟩ n := rfl
instance : functor seq := {map := @map}
instance : is_lawful_functor seq :=
{ id_map := @map_id, comp_map := @map_comp }
@[simp] theorem join_nil : join nil = (nil : seq α) := destruct_eq_nil rfl
@[simp] theorem join_cons_nil (a : α) (S) :
join (cons (a, nil) S) = cons a (join S) :=
destruct_eq_cons $ by simp [join]
@[simp] theorem join_cons_cons (a b : α) (s S) :
join (cons (a, cons b s) S) = cons a (join (cons (b, s) S)) :=
destruct_eq_cons $ by simp [join]
@[simp, priority 990] theorem join_cons (a : α) (s S) :
join (cons (a, s) S) = cons a (append s (join S)) :=
begin
apply eq_of_bisim (λs1 s2, s1 = s2 ∨
∃ a s S, s1 = join (cons (a, s) S) ∧
s2 = cons a (append s (join S))) _ (or.inr ⟨a, s, S, rfl, rfl⟩),
intros s1 s2 h,
exact match s1, s2, h with
| _, _, (or.inl $ eq.refl s) := begin
apply cases_on s, { trivial },
{ intros x s, rw [destruct_cons], exact ⟨rfl, or.inl rfl⟩ }
end
| ._, ._, (or.inr ⟨a, s, S, rfl, rfl⟩) := begin
apply cases_on s,
{ simp },
{ intros x s, simp, refine or.inr ⟨x, s, S, rfl, rfl⟩ }
end
end
end
@[simp] theorem join_append (S T : seq (seq1 α)) :
join (append S T) = append (join S) (join T) :=
begin
apply eq_of_bisim (λs1 s2, ∃ s S T,
s1 = append s (join (append S T)) ∧
s2 = append s (append (join S) (join T))),
{ intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, T, rfl, rfl⟩ := begin
apply cases_on s; simp,
{ apply cases_on S; simp,
{ apply cases_on T, { simp },
{ intros s T, cases s with a s; simp,
refine ⟨s, nil, T, _, _⟩; simp } },
{ intros s S, cases s with a s; simp,
exact ⟨s, S, T, rfl, rfl⟩ } },
{ intros x s, exact ⟨s, S, T, rfl, rfl⟩ }
end end },
{ refine ⟨nil, S, T, _, _⟩; simp }
end
@[simp] theorem of_list_nil : of_list [] = (nil : seq α) := rfl
@[simp] theorem of_list_cons (a : α) (l) :
of_list (a :: l) = cons a (of_list l) :=
begin
apply subtype.eq, simp [of_list, cons],
ext ⟨⟩; simp [list.nth, stream.cons]
end
@[simp] theorem of_stream_cons (a : α) (s) :
of_stream (a :: s) = cons a (of_stream s) :=
by apply subtype.eq; simp [of_stream, cons]; rw stream.map_cons
@[simp] theorem of_list_append (l l' : list α) :
of_list (l ++ l') = append (of_list l) (of_list l') :=
by induction l; simp [*]
@[simp] theorem of_stream_append (l : list α) (s : stream α) :
of_stream (l ++ₛ s) = append (of_list l) (of_stream s) :=
by induction l; simp [*, stream.nil_append_stream, stream.cons_append_stream]
/-- Convert a sequence into a list, embedded in a computation to allow for
the possibility of infinite sequences (in which case the computation
never returns anything). -/
def to_list' {α} (s : seq α) : computation (list α) :=
@computation.corec (list α) (list α × seq α) (λ⟨l, s⟩,
match destruct s with
| none := sum.inl l.reverse
| some (a, s') := sum.inr (a::l, s')
end) ([], s)
theorem dropn_add (s : seq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n
| 0 := rfl
| (n+1) := congr_arg tail (dropn_add n)
theorem dropn_tail (s : seq α) (n) : drop (tail s) n = drop s (n + 1) :=
by rw add_comm; symmetry; apply dropn_add
theorem nth_tail : ∀ (s : seq α) n, nth (tail s) n = nth s (n + 1)
| ⟨f, al⟩ n := rfl
@[ext]
protected lemma ext (s s': seq α) (hyp : ∀ (n : ℕ), s.nth n = s'.nth n) : s = s' :=
begin
let ext := (λ (s s' : seq α), ∀ n, s.nth n = s'.nth n),
apply seq.eq_of_bisim ext _ hyp,
-- we have to show that ext is a bisimulation
clear hyp s s',
assume s s' (hyp : ext s s'),
unfold seq.destruct,
rw (hyp 0),
cases (s'.nth 0),
{ simp [seq.bisim_o] }, -- option.none
{ -- option.some
suffices : ext s.tail s'.tail, by simpa,
assume n,
simp only [seq.nth_tail _ n, (hyp $ n + 1)] }
end
@[simp] theorem head_dropn (s : seq α) (n) : head (drop s n) = nth s n :=
begin
induction n with n IH generalizing s, { refl },
rw [nat.succ_eq_add_one, ←nth_tail, ←dropn_tail], apply IH
end
theorem mem_map (f : α → β) {a : α} : ∀ {s : seq α}, a ∈ s → f a ∈ map f s
| ⟨g, al⟩ := stream.mem_map (option.map f)
theorem exists_of_mem_map {f} {b : β} : ∀ {s : seq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b
| ⟨g, al⟩ h := let ⟨o, om, oe⟩ := stream.exists_of_mem_map h in
by cases o with a; injection oe with h'; exact ⟨a, om, h'⟩
theorem of_mem_append {s₁ s₂ : seq α} {a : α} (h : a ∈ append s₁ s₂) : a ∈ s₁ ∨ a ∈ s₂ :=
begin
have := h, revert this,
generalize e : append s₁ s₂ = ss, intro h, revert s₁,
apply mem_rec_on h _,
intros b s' o s₁,
apply s₁.cases_on _ (λ c t₁, _); intros m e;
have := congr_arg destruct e,
{ apply or.inr, simpa using m },
{ cases (show a = c ∨ a ∈ append t₁ s₂, by simpa using m) with e' m,
{ rw e', exact or.inl (mem_cons _ _) },
{ cases (show c = b ∧ append t₁ s₂ = s', by simpa) with i1 i2,
cases o with e' IH,
{ simp [i1, e'] },
{ exact or.imp_left (mem_cons_of_mem _) (IH m i2) } } }
end
theorem mem_append_left {s₁ s₂ : seq α} {a : α} (h : a ∈ s₁) : a ∈ append s₁ s₂ :=
by apply mem_rec_on h; intros; simp [*]
end seq
namespace seq1
variables {α : Type u} {β : Type v} {γ : Type w}
open seq
/-- Convert a `seq1` to a sequence. -/
def to_seq : seq1 α → seq α
| (a, s) := cons a s
instance coe_seq : has_coe (seq1 α) (seq α) := ⟨to_seq⟩
/-- Map a function on a `seq1` -/
def map (f : α → β) : seq1 α → seq1 β
| (a, s) := (f a, seq.map f s)
theorem map_id : ∀ (s : seq1 α), map id s = s | ⟨a, s⟩ := by simp [map]
/-- Flatten a nonempty sequence of nonempty sequences -/
def join : seq1 (seq1 α) → seq1 α
| ((a, s), S) := match destruct s with
| none := (a, seq.join S)
| some s' := (a, seq.join (cons s' S))
end
@[simp] theorem join_nil (a : α) (S) : join ((a, nil), S) = (a, seq.join S) := rfl
@[simp] theorem join_cons (a b : α) (s S) :
join ((a, cons b s), S) = (a, seq.join (cons (b, s) S)) :=
by dsimp [join]; rw [destruct_cons]; refl
/-- The `return` operator for the `seq1` monad,
which produces a singleton sequence. -/
def ret (a : α) : seq1 α := (a, nil)
instance [inhabited α] : inhabited (seq1 α) := ⟨ret (default _)⟩
/-- The `bind` operator for the `seq1` monad,
which maps `f` on each element of `s` and appends the results together.
(Not all of `s` may be evaluated, because the first few elements of `s`
may already produce an infinite result.) -/
def bind (s : seq1 α) (f : α → seq1 β) : seq1 β :=
join (map f s)
@[simp] theorem join_map_ret (s : seq α) : seq.join (seq.map ret s) = s :=
by apply coinduction2 s; intro s; apply cases_on s; simp [ret]
@[simp] theorem bind_ret (f : α → β) : ∀ s, bind s (ret ∘ f) = map f s
| ⟨a, s⟩ := begin
dsimp [bind, map], change (λx, ret (f x)) with (ret ∘ f),
rw [map_comp], simp [function.comp, ret]
end
@[simp] theorem ret_bind (a : α) (f : α → seq1 β) : bind (ret a) f = f a :=
begin
simp [ret, bind, map],
cases f a with a s,
apply cases_on s; intros; simp
end
@[simp] theorem map_join' (f : α → β) (S) :
seq.map f (seq.join S) = seq.join (seq.map (map f) S) :=
begin
apply eq_of_bisim (λs1 s2,
∃ s S, s1 = append s (seq.map f (seq.join S)) ∧
s2 = append s (seq.join (seq.map (map f) S))),
{ intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, rfl, rfl⟩ := begin
apply cases_on s; simp,
{ apply cases_on S; simp,
{ intros x S, cases x with a s; simp [map],
exact ⟨_, _, rfl, rfl⟩ } },
{ intros x s, refine ⟨s, S, rfl, rfl⟩ }
end end },
{ refine ⟨nil, S, _, _⟩; simp }
end
@[simp] theorem map_join (f : α → β) : ∀ S, map f (join S) = join (map (map f) S)
| ((a, s), S) := by apply cases_on s; intros; simp [map]
@[simp] theorem join_join (SS : seq (seq1 (seq1 α))) :
seq.join (seq.join SS) = seq.join (seq.map join SS) :=
begin
apply eq_of_bisim (λs1 s2,
∃ s SS, s1 = seq.append s (seq.join (seq.join SS)) ∧
s2 = seq.append s (seq.join (seq.map join SS))),
{ intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, SS, rfl, rfl⟩ := begin
apply cases_on s; simp,
{ apply cases_on SS; simp,
{ intros S SS, cases S with s S; cases s with x s; simp [map],
apply cases_on s; simp,
{ exact ⟨_, _, rfl, rfl⟩ },
{ intros x s,
refine ⟨cons x (append s (seq.join S)), SS, _, _⟩; simp } } },
{ intros x s, exact ⟨s, SS, rfl, rfl⟩ }
end end },
{ refine ⟨nil, SS, _, _⟩; simp }
end
@[simp] theorem bind_assoc (s : seq1 α) (f : α → seq1 β) (g : β → seq1 γ) :
bind (bind s f) g = bind s (λ (x : α), bind (f x) g) :=
begin
cases s with a s,
simp [bind, map],
rw [←map_comp],
change (λ x, join (map g (f x))) with (join ∘ ((map g) ∘ f)),
rw [map_comp _ join],
generalize : seq.map (map g ∘ f) s = SS,
rcases map g (f a) with ⟨⟨a, s⟩, S⟩,
apply cases_on s; intros; apply cases_on S; intros; simp,
{ cases x with x t, apply cases_on t; intros; simp },
{ cases x_1 with y t; simp }
end
instance : monad seq1 :=
{ map := @map,
pure := @ret,
bind := @bind }
instance : is_lawful_monad seq1 :=
{ id_map := @map_id,
bind_pure_comp_eq_map := @bind_ret,
pure_bind := @ret_bind,
bind_assoc := @bind_assoc }
end seq1
|
9e46e39cae5efe2159bfb8f4ddbed272bc0f8e2f | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/number_theory/cyclotomic/discriminant.lean | 61de05a851897f11884af156d4e6cc6546aaf24f | [
"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,512 | lean | /-
Copyright (c) 2022 Riccardo Brasca. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Riccardo Brasca
-/
import number_theory.cyclotomic.primitive_roots
import ring_theory.discriminant
/-!
# Discriminant of cyclotomic fields
We compute the discriminant of a `p ^ n`-th cyclotomic extension.
## Main results
* `is_cyclotomic_extension.discr_odd_prime` : if `p` is an odd prime such that
`is_cyclotomic_extension {p} K L` and `irreducible (cyclotomic p K)`, then
`discr K (hζ.power_basis K).basis = (-1) ^ ((p - 1) / 2) * p ^ (p - 2)` for any
`hζ : is_primitive_root ζ p`.
-/
universes u v
open algebra polynomial nat is_primitive_root power_basis
open_locale polynomial cyclotomic
namespace is_primitive_root
variables {n : ℕ+} {K : Type u} [field K] [char_zero K] {ζ : K}
variables [is_cyclotomic_extension {n} ℚ K]
/-- The discriminant of the power basis given by a primitive root of unity `ζ` is the same as the
discriminant of the power basis given by `ζ - 1`. -/
lemma discr_zeta_eq_discr_zeta_sub_one (hζ : is_primitive_root ζ n) :
discr ℚ (hζ.power_basis ℚ).basis = discr ℚ (hζ.sub_one_power_basis ℚ).basis :=
begin
haveI : number_field K := number_field.mk,
have H₁ : (aeval (hζ.power_basis ℚ).gen) (X - 1 : ℤ[X]) = (hζ.sub_one_power_basis ℚ).gen :=
by simp,
have H₂ : (aeval (hζ.sub_one_power_basis ℚ).gen) (X + 1 : ℤ[X]) = (hζ.power_basis ℚ).gen :=
by simp,
refine discr_eq_discr_of_to_matrix_coeff_is_integral _
(λ i j, to_matrix_is_integral H₁ _ _ _ _)
(λ i j, to_matrix_is_integral H₂ _ _ _ _),
{ exact hζ.is_integral n.pos },
{ refine minpoly.gcd_domain_eq_field_fractions' _ (hζ.is_integral n.pos) },
{ exact is_integral_sub (hζ.is_integral n.pos) is_integral_one },
{ refine minpoly.gcd_domain_eq_field_fractions' _ _,
exact is_integral_sub (hζ.is_integral n.pos) is_integral_one }
end
end is_primitive_root
namespace is_cyclotomic_extension
variables {p : ℕ+} {k : ℕ} {K : Type u} {L : Type v} {ζ : L} [field K] [field L]
variables [algebra K L]
/-- If `p` is a prime and `is_cyclotomic_extension {p ^ (k + 1)} K L`, then the discriminant of
`hζ.power_basis K` is `(-1) ^ ((p ^ (k + 1).totient) / 2) * p ^ (p ^ k * ((p - 1) * (k + 1) - 1))`
if `irreducible (cyclotomic (p ^ (k + 1)) K))`, and `p ^ (k + 1) ≠ 2`. -/
lemma discr_prime_pow_ne_two [is_cyclotomic_extension {p ^ (k + 1)} K L] [hp : fact (p : ℕ).prime]
(hζ : is_primitive_root ζ ↑(p ^ (k + 1))) (hirr : irreducible (cyclotomic (↑(p ^ (k + 1)) : ℕ) K))
(hk : p ^ (k + 1) ≠ 2) :
discr K (hζ.power_basis K).basis =
(-1) ^ (((p ^ (k + 1) : ℕ).totient) / 2) * p ^ ((p : ℕ) ^ k * ((p - 1) * (k + 1) - 1)) :=
begin
haveI hne := is_cyclotomic_extension.ne_zero' (p ^ (k + 1)) K L,
have hp2 : p = 2 → 1 ≤ k,
{ intro hp,
refine one_le_iff_ne_zero.2 (λ h, _),
rw [h, hp, zero_add, pow_one] at hk,
exact hk rfl },
rw [discr_power_basis_eq_norm, finrank _ hirr, hζ.power_basis_gen _,
← hζ.minpoly_eq_cyclotomic_of_irreducible hirr, pnat.pow_coe, totient_prime_pow hp.out
(succ_pos k)],
congr' 1,
{ by_cases hptwo : p = 2,
{ obtain ⟨k₁, hk₁⟩ := nat.exists_eq_succ_of_ne_zero (one_le_iff_ne_zero.1 (hp2 hptwo)),
rw [hk₁, succ_sub_one, hptwo, pnat.coe_bit0, pnat.one_coe, succ_sub_succ_eq_sub, tsub_zero,
mul_one, pow_succ, mul_assoc, nat.mul_div_cancel_left _ zero_lt_two,
nat.mul_div_cancel_left _ zero_lt_two],
by_cases hk₁zero : k₁ = 0,
{ simp [hk₁zero] },
obtain ⟨k₂, rfl⟩ := nat.exists_eq_succ_of_ne_zero hk₁zero,
rw [pow_succ, mul_assoc, pow_mul (-1 : K), pow_mul (-1 : K), neg_one_sq, one_pow, one_pow] },
{ simp only [succ_sub_succ_eq_sub, tsub_zero],
replace hptwo : ↑p ≠ 2,
{ intro h,
rw [← pnat.one_coe, ← pnat.coe_bit0, pnat.coe_inj] at h,
exact hptwo h },
obtain ⟨a, ha⟩ := even_sub_one_of_prime_ne_two hp.out hptwo,
rw [mul_comm ((p : ℕ) ^ k), mul_assoc, ha],
nth_rewrite 0 [← mul_one a],
nth_rewrite 4 [← mul_one a],
rw [← nat.mul_succ, mul_comm a, mul_assoc, mul_assoc 2, nat.mul_div_cancel_left _
zero_lt_two, nat.mul_div_cancel_left _ zero_lt_two, ← mul_assoc, mul_comm
(a * (p : ℕ) ^ k), pow_mul, ← ha],
congr' 1,
refine odd.neg_one_pow (nat.even.sub_odd (nat.succ_le_iff.2 (mul_pos (tsub_pos_iff_lt.2
hp.out.one_lt) (pow_pos hp.out.pos _))) (even.mul_right (nat.even_sub_one_of_prime_ne_two
hp.out hptwo) _) odd_one) } },
{ have H := congr_arg derivative (cyclotomic_prime_pow_mul_X_pow_sub_one K p k),
rw [derivative_mul, derivative_sub, derivative_one, sub_zero, derivative_pow,
derivative_X, mul_one, derivative_sub, derivative_one, sub_zero, derivative_pow,
derivative_X, mul_one, ← pnat.pow_coe, hζ.minpoly_eq_cyclotomic_of_irreducible hirr] at H,
replace H := congr_arg (λ P, aeval ζ P) H,
simp only [aeval_add, aeval_mul, minpoly.aeval, zero_mul, add_zero, aeval_nat_cast,
_root_.map_sub, aeval_one, aeval_X_pow] at H,
replace H := congr_arg (algebra.norm K) H,
have hnorm : (norm K) (ζ ^ (p : ℕ) ^ k - 1) = p ^ ((p : ℕ) ^ k),
{ by_cases hp : p = 2,
{ exact hζ.pow_sub_one_norm_prime_pow_of_one_le hirr rfl.le (hp2 hp) },
{ exact hζ.pow_sub_one_norm_prime_ne_two hirr rfl.le hp } },
rw [monoid_hom.map_mul, hnorm, monoid_hom.map_mul, ← map_nat_cast (algebra_map K L),
algebra.norm_algebra_map, finrank _ hirr, pnat.pow_coe, totient_prime_pow hp.out (succ_pos k),
nat.sub_one, nat.pred_succ, ← hζ.minpoly_eq_cyclotomic_of_irreducible hirr, map_pow,
hζ.norm_eq_one hk hirr, one_pow, mul_one, cast_pow, ← coe_coe, ← pow_mul, ← mul_assoc,
mul_comm (k + 1), mul_assoc] at H,
{ have := mul_pos (succ_pos k) (tsub_pos_iff_lt.2 hp.out.one_lt),
rw [← succ_pred_eq_of_pos this, mul_succ, pow_add _ _ ((p : ℕ) ^ k)] at H,
replace H := (mul_left_inj' (λ h, _)).1 H,
{ simpa only [← pnat.pow_coe, H, mul_comm _ (k + 1)] },
{ replace h := pow_eq_zero h,
rw [coe_coe] at h,
simpa using hne.1 } },
all_goals { apply_instance } },
all_goals { apply_instance }
end
/-- If `p` is a prime and `is_cyclotomic_extension {p ^ (k + 1)} K L`, then the discriminant of
`hζ.power_basis K` is `(-1) ^ (p ^ k * (p - 1) / 2) * p ^ (p ^ k * ((p - 1) * (k + 1) - 1))`
if `irreducible (cyclotomic (p ^ (k + 1)) K))`, and `p ^ (k + 1) ≠ 2`. -/
lemma discr_prime_pow_ne_two' [is_cyclotomic_extension {p ^ (k + 1)} K L] [hp : fact (p : ℕ).prime]
(hζ : is_primitive_root ζ ↑(p ^ (k + 1))) (hirr : irreducible (cyclotomic (↑(p ^ (k + 1)) : ℕ) K))
(hk : p ^ (k + 1) ≠ 2) :
discr K (hζ.power_basis K).basis =
(-1) ^ (((p : ℕ) ^ k * (p - 1)) / 2) * p ^ ((p : ℕ) ^ k * ((p - 1) * (k + 1) - 1)) :=
by simpa [totient_prime_pow hp.out (succ_pos k)] using discr_prime_pow_ne_two hζ hirr hk
/-- If `p` is a prime and `is_cyclotomic_extension {p ^ k} K L`, then the discriminant of
`hζ.power_basis K` is `(-1) ^ ((p ^ k).totient / 2) * p ^ (p ^ (k - 1) * ((p - 1) * k - 1))`
if `irreducible (cyclotomic (p ^ k) K))`. Beware that in the cases `p ^ k = 1` and `p ^ k = 2`
the formula uses `1 / 2 = 0` and `0 - 1 = 0`. It is useful only to have a uniform result.
See also `is_cyclotomic_extension.discr_prime_pow_eq_unit_mul_pow`. -/
lemma discr_prime_pow [hcycl : is_cyclotomic_extension {p ^ k} K L] [hp : fact (p : ℕ).prime]
(hζ : is_primitive_root ζ ↑(p ^ k)) (hirr : irreducible (cyclotomic (↑(p ^ k) : ℕ) K)) :
discr K (hζ.power_basis K).basis =
(-1) ^ (((p ^ k : ℕ).totient) / 2) * p ^ ((p : ℕ) ^ (k - 1) * ((p - 1) * k - 1)) :=
begin
unfreezingI { cases k },
{ simp only [coe_basis, pow_zero, power_basis_gen, totient_one, mul_zero, mul_one, show 1 / 2 = 0,
by refl, discr, trace_matrix],
have hζone : ζ = 1 := by simpa using hζ,
rw [hζ.power_basis_dim _, hζone, ← (algebra_map K L).map_one,
minpoly.eq_X_sub_C_of_algebra_map_inj _ (algebra_map K L).injective, nat_degree_X_sub_C],
simp only [trace_matrix, map_one, one_pow, matrix.det_unique, trace_form_apply, mul_one],
rw [← (algebra_map K L).map_one, trace_algebra_map, finrank _ hirr],
{ simp },
{ apply_instance },
{ exact hcycl } },
{ by_cases hk : p ^ (k + 1) = 2,
{ have hp : p = 2,
{ rw [← pnat.coe_inj, pnat.coe_bit0, pnat.one_coe, pnat.pow_coe, ← pow_one 2] at hk,
replace hk := eq_of_prime_pow_eq (prime_iff.1 hp.out) (prime_iff.1 nat.prime_two)
(succ_pos _) hk,
rwa [show 2 = ((2 : ℕ+) : ℕ), by simp, pnat.coe_inj] at hk },
rw [hp, ← pnat.coe_inj, pnat.pow_coe, pnat.coe_bit0, pnat.one_coe] at hk,
nth_rewrite 1 [← pow_one 2] at hk,
replace hk := nat.pow_right_injective rfl.le hk,
rw [add_left_eq_self] at hk,
simp only [hp, hk, pow_one, pnat.coe_bit0, pnat.one_coe] at hζ,
simp only [hp, hk, show 1 / 2 = 0, by refl, coe_basis, pow_one, power_basis_gen,
pnat.coe_bit0, pnat.one_coe, totient_two, pow_zero, mul_one, mul_zero],
rw [power_basis_dim, hζ.eq_neg_one_of_two_right, show (-1 : L) = algebra_map K L (-1),
by simp, minpoly.eq_X_sub_C_of_algebra_map_inj _ (algebra_map K L).injective,
nat_degree_X_sub_C],
simp only [discr, trace_matrix, matrix.det_unique, fin.default_eq_zero, fin.coe_zero,
pow_zero, trace_form_apply, mul_one],
rw [← (algebra_map K L).map_one, trace_algebra_map, finrank _ hirr, hp, hk],
{ simp },
{ apply_instance },
{ exact hcycl } },
{ exact discr_prime_pow_ne_two hζ hirr hk } }
end
/-- If `p` is a prime and `is_cyclotomic_extension {p ^ k} K L`, then there are `u : ℤˣ` and
`n : ℕ` such that the discriminant of `hζ.power_basis K` is `u * p ^ n`. Often this is enough and
less cumbersome to use than `is_cyclotomic_extension.discr_prime_pow`. -/
lemma discr_prime_pow_eq_unit_mul_pow [is_cyclotomic_extension {p ^ k} K L]
[hp : fact (p : ℕ).prime] (hζ : is_primitive_root ζ ↑(p ^ k))
(hirr : irreducible (cyclotomic (↑(p ^ k) : ℕ) K)) :
∃ (u : ℤˣ) (n : ℕ), discr K (hζ.power_basis K).basis = u * p ^ n :=
begin
rw [discr_prime_pow hζ hirr],
by_cases heven : even (((p ^ k : ℕ).totient) / 2),
{ refine ⟨1, (p : ℕ) ^ (k - 1) * ((p - 1) * k - 1), by simp [heven.neg_one_pow]⟩ },
{ exact ⟨-1, (p : ℕ) ^ (k - 1) * ((p - 1) * k - 1),
by simp [(odd_iff_not_even.2 heven).neg_one_pow]⟩ },
end
/-- If `p` is an odd prime and `is_cyclotomic_extension {p} K L`, then
`discr K (hζ.power_basis K).basis = (-1) ^ ((p - 1) / 2) * p ^ (p - 2)` if
`irreducible (cyclotomic p K)`. -/
lemma discr_odd_prime [is_cyclotomic_extension {p} K L] [hp : fact (p : ℕ).prime]
(hζ : is_primitive_root ζ p) (hirr : irreducible (cyclotomic p K)) (hodd : p ≠ 2) :
discr K (hζ.power_basis K).basis = (-1) ^ (((p : ℕ) - 1) / 2) * p ^ ((p : ℕ) - 2) :=
begin
haveI : is_cyclotomic_extension {p ^ (0 + 1)} K L,
{ rw [zero_add, pow_one],
apply_instance },
have hζ' : is_primitive_root ζ ↑(p ^ (0 + 1)) := by simpa using hζ,
convert discr_prime_pow_ne_two hζ' (by simpa [hirr]) (by simp [hodd]),
{ rw [zero_add, pow_one, totient_prime hp.out] },
{ rw [pow_zero, one_mul, zero_add, mul_one, nat.sub_sub] }
end
end is_cyclotomic_extension
|
3128e742593e0ada82da932c4aa40a6bda01e368 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/1024.lean | 17da7756b5f749409053e031aef61e5db60c44a4 | [
"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 | 894 | lean | inductive Vector (α : Type u): Nat → Type u where
| nil : Vector α 0
| cons (head : α) (tail : Vector α n) : Vector α (n+1)
namespace Vector
def nth : ∀{n}, Vector α n → Fin n → α
| n+1, cons x xs, ⟨ 0, _⟩ => x
| n+1, cons x xs, ⟨k+1, h⟩ => xs.nth ⟨k, sorry⟩
def snoc : ∀{n : Nat} (xs : Vector α n) (x : α), Vector α (n+1)
| _, nil, x' => cons x' nil
| _, cons x xs, x' => cons x (snoc xs x')
theorem nth_snoc_eq (k: Fin (n+1))(v : Vector α n)
(h: k.val = n):
(v.snoc x).nth k = x := by
cases k; rename_i k hk
induction v generalizing k <;> subst h
· simp only [nth]
· simp! [*]
theorem nth_snoc_eq_works (k: Fin (n+1))(v : Vector α n)
(h: k.val = n):
(v.snoc x).nth k = x := by
cases k; rename_i k hk
induction v generalizing k <;> subst h
· simp only [nth]
· simp[*,nth]
end Vector
|
c06f4409df83ca34a567a4254246d2b83ac126ba | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/nat/totient.lean | dbc8360f7cbcbbd546d419d7507f975b59b8a670 | [
"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 | 12,457 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import algebra.big_operators.basic
import data.nat.prime
import data.zmod.basic
import ring_theory.multiplicity
import data.nat.periodic
import algebra.char_p.two
/-!
# Euler's totient function
This file defines [Euler's totient function](https://en.wikipedia.org/wiki/Euler's_totient_function)
`nat.totient n` which counts the number of naturals less than `n` that are coprime with `n`.
We prove the divisor sum formula, namely that `n` equals `φ` summed over the divisors of `n`. See
`sum_totient`. We also prove two lemmas to help compute totients, namely `totient_mul` and
`totient_prime_pow`.
-/
open finset
open_locale big_operators
namespace nat
/-- Euler's totient function. This counts the number of naturals strictly less than `n` which are
coprime with `n`. -/
def totient (n : ℕ) : ℕ := ((range n).filter n.coprime).card
localized "notation `φ` := nat.totient" in nat
@[simp] theorem totient_zero : φ 0 = 0 := rfl
@[simp] theorem totient_one : φ 1 = 1 :=
by simp [totient]
lemma totient_eq_card_coprime (n : ℕ) : φ n = ((range n).filter n.coprime).card := rfl
lemma totient_le (n : ℕ) : φ n ≤ n :=
calc totient n ≤ (range n).card : card_filter_le _ _
... = n : card_range _
lemma totient_lt (n : ℕ) (hn : 1 < n) : φ n < n :=
calc totient n ≤ ((range n).filter (≠ 0)).card :
begin
apply card_le_of_subset (monotone_filter_right _ _),
intros n1 hn1 hn1',
simpa only [hn1', coprime_zero_right, hn.ne'] using hn1,
end
... = n - 1 : by simp only [filter_ne' (range n) 0, card_erase_of_mem, n.pred_eq_sub_one,
card_range, pos_of_gt hn, mem_range]
... < n : nat.sub_lt (pos_of_gt hn) zero_lt_one
lemma totient_pos : ∀ {n : ℕ}, 0 < n → 0 < φ n
| 0 := dec_trivial
| 1 := by simp [totient]
| (n+2) := λ h, card_pos.2 ⟨1, mem_filter.2 ⟨mem_range.2 dec_trivial, coprime_one_right _⟩⟩
lemma filter_coprime_Ico_eq_totient (a n : ℕ) :
((Ico n (n+a)).filter (coprime a)).card = totient a :=
begin
rw [totient, filter_Ico_card_eq_of_periodic, count_eq_card_filter_range],
exact periodic_coprime a,
end
lemma Ico_filter_coprime_le {a : ℕ} (k n : ℕ) (a_pos : 0 < a) :
((Ico k (k + n)).filter (coprime a)).card ≤ totient a * (n / a + 1) :=
begin
conv_lhs { rw ←nat.mod_add_div n a },
induction n / a with i ih,
{ rw ←filter_coprime_Ico_eq_totient a k,
simp only [add_zero, mul_one, mul_zero, le_of_lt (mod_lt n a_pos)],
mono,
refine monotone_filter_left a.coprime _,
simp only [finset.le_eq_subset],
exact Ico_subset_Ico rfl.le (add_le_add_left (le_of_lt (mod_lt n a_pos)) k), },
simp only [mul_succ],
simp_rw ←add_assoc at ih ⊢,
calc (filter a.coprime (Ico k (k + n % a + a * i + a))).card
= (filter a.coprime (Ico k (k + n % a + a * i)
∪ Ico (k + n % a + a * i) (k + n % a + a * i + a))).card :
begin
congr,
rw Ico_union_Ico_eq_Ico,
rw add_assoc,
exact le_self_add,
exact le_self_add,
end
... ≤ (filter a.coprime (Ico k (k + n % a + a * i))).card + a.totient :
begin
rw [filter_union, ←filter_coprime_Ico_eq_totient a (k + n % a + a * i)],
apply card_union_le,
end
... ≤ a.totient * i + a.totient + a.totient : add_le_add_right ih (totient a),
end
open zmod
/-- Note this takes an explicit `fintype ((zmod n)ˣ)` argument to avoid trouble with instance
diamonds. -/
@[simp] lemma _root_.zmod.card_units_eq_totient (n : ℕ) [fact (0 < n)] [fintype ((zmod n)ˣ)] :
fintype.card ((zmod n)ˣ) = φ n :=
calc fintype.card ((zmod n)ˣ) = fintype.card {x : zmod n // x.val.coprime n} :
fintype.card_congr zmod.units_equiv_coprime
... = φ n :
begin
apply finset.card_congr (λ (a : {x : zmod n // x.val.coprime n}) _, a.1.val),
{ intro a, simp [(a : zmod n).val_lt, a.prop.symm] {contextual := tt} },
{ intros _ _ _ _ h, rw subtype.ext_iff_val, apply val_injective, exact h, },
{ intros b hb,
rw [finset.mem_filter, finset.mem_range] at hb,
refine ⟨⟨b, _⟩, finset.mem_univ _, _⟩,
{ let u := unit_of_coprime b hb.2.symm,
exact val_coe_unit_coprime u },
{ show zmod.val (b : zmod n) = b,
rw [val_nat_cast, nat.mod_eq_of_lt hb.1], } }
end
lemma totient_even {n : ℕ} (hn : 2 < n) : even n.totient :=
begin
haveI : fact (1 < n) := ⟨one_lt_two.trans hn⟩,
suffices : 2 = order_of (-1 : (zmod n)ˣ),
{ rw [← zmod.card_units_eq_totient, even_iff_two_dvd, this], exact order_of_dvd_card_univ },
rw [←order_of_units, units.coe_neg_one, order_of_neg_one, ring_char.eq (zmod n) n, if_neg hn.ne'],
end
lemma totient_mul {m n : ℕ} (h : m.coprime n) : φ (m * n) = φ m * φ n :=
if hmn0 : m * n = 0
then by cases nat.mul_eq_zero.1 hmn0 with h h;
simp only [totient_zero, mul_zero, zero_mul, h]
else
begin
haveI : fact (0 < (m * n)) := ⟨nat.pos_of_ne_zero hmn0⟩,
haveI : fact (0 < m) := ⟨nat.pos_of_ne_zero $ left_ne_zero_of_mul hmn0⟩,
haveI : fact (0 < n) := ⟨nat.pos_of_ne_zero $ right_ne_zero_of_mul hmn0⟩,
rw [← zmod.card_units_eq_totient, ← zmod.card_units_eq_totient,
← zmod.card_units_eq_totient, fintype.card_congr
(units.map_equiv (zmod.chinese_remainder h).to_mul_equiv).to_equiv,
fintype.card_congr (@mul_equiv.prod_units (zmod m) (zmod n) _ _).to_equiv,
fintype.card_prod]
end
lemma sum_totient (n : ℕ) : ∑ m in (range n.succ).filter (∣ n), φ m = n :=
if hn0 : n = 0 then by simp [hn0]
else
calc ∑ m in (range n.succ).filter (∣ n), φ m
= ∑ d in (range n.succ).filter (∣ n), ((range (n / d)).filter (λ m, gcd (n / d) m = 1)).card :
eq.symm $ sum_bij (λ d _, n / d)
(λ d hd, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _,
by conv {to_rhs, rw ← nat.mul_div_cancel' (mem_filter.1 hd).2}; simp⟩)
(λ _ _, rfl)
(λ a b ha hb h,
have ha : a * (n / a) = n, from nat.mul_div_cancel' (mem_filter.1 ha).2,
have 0 < (n / a), from nat.pos_of_ne_zero (λ h, by simp [*, lt_irrefl] at *),
by rw [← nat.mul_left_inj this, ha, h, nat.mul_div_cancel' (mem_filter.1 hb).2])
(λ b hb,
have hb : b < n.succ ∧ b ∣ n, by simpa [-range_succ] using hb,
have hbn : (n / b) ∣ n, from ⟨b, by rw nat.div_mul_cancel hb.2⟩,
have hnb0 : (n / b) ≠ 0, from λ h, by simpa [h, ne.symm hn0] using nat.div_mul_cancel hbn,
⟨n / b, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, hbn⟩,
by rw [← nat.mul_left_inj (nat.pos_of_ne_zero hnb0),
nat.mul_div_cancel' hb.2, nat.div_mul_cancel hbn]⟩)
... = ∑ d in (range n.succ).filter (∣ n), ((range n).filter (λ m, gcd n m = d)).card :
sum_congr rfl (λ d hd,
have hd : d ∣ n, from (mem_filter.1 hd).2,
have hd0 : 0 < d, from nat.pos_of_ne_zero (λ h, hn0 (eq_zero_of_zero_dvd $ h ▸ hd)),
card_congr (λ m hm, d * m)
(λ m hm, have hm : m < n / d ∧ gcd (n / d) m = 1, by simpa using hm,
mem_filter.2 ⟨mem_range.2 $ nat.mul_div_cancel' hd ▸
(mul_lt_mul_left hd0).2 hm.1,
by rw [← nat.mul_div_cancel' hd, gcd_mul_left, hm.2, mul_one]⟩)
(λ a b ha hb h, (nat.mul_right_inj hd0).1 h)
(λ b hb, have hb : b < n ∧ gcd n b = d, by simpa using hb,
⟨b / d, mem_filter.2 ⟨mem_range.2
((mul_lt_mul_left (show 0 < d, from hb.2 ▸ hb.2.symm ▸ hd0)).1
(by rw [← hb.2, nat.mul_div_cancel' (gcd_dvd_left _ _),
nat.mul_div_cancel' (gcd_dvd_right _ _)]; exact hb.1)),
hb.2 ▸ coprime_div_gcd_div_gcd (hb.2.symm ▸ hd0)⟩,
hb.2 ▸ nat.mul_div_cancel' (gcd_dvd_right _ _)⟩))
... = ((filter (∣ n) (range n.succ)).bUnion (λ d, (range n).filter (λ m, gcd n m = d))).card :
(card_bUnion (by intros; apply disjoint_filter.2; cc)).symm
... = (range n).card :
congr_arg card (finset.ext (λ m, ⟨by simp,
λ hm, have h : m < n, from mem_range.1 hm,
mem_bUnion.2 ⟨gcd n m, mem_filter.2
⟨mem_range.2 (lt_succ_of_le (le_of_dvd (lt_of_le_of_lt (zero_le _) h)
(gcd_dvd_left _ _))), gcd_dvd_left _ _⟩, mem_filter.2 ⟨hm, rfl⟩⟩⟩))
... = n : card_range _
/-- When `p` is prime, then the totient of `p ^ (n + 1)` is `p ^ n * (p - 1)` -/
lemma totient_prime_pow_succ {p : ℕ} (hp : p.prime) (n : ℕ) :
φ (p ^ (n + 1)) = p ^ n * (p - 1) :=
calc φ (p ^ (n + 1))
= ((range (p ^ (n + 1))).filter (coprime (p ^ (n + 1)))).card :
totient_eq_card_coprime _
... = (range (p ^ (n + 1)) \ ((range (p ^ n)).image (* p))).card :
congr_arg card begin
rw [sdiff_eq_filter],
apply filter_congr,
simp only [mem_range, mem_filter, coprime_pow_left_iff n.succ_pos,
mem_image, not_exists, hp.coprime_iff_not_dvd],
intros a ha,
split,
{ rintros hap b _ rfl,
exact hap (dvd_mul_left _ _) },
{ rintros h ⟨b, rfl⟩,
rw [pow_succ] at ha,
exact h b (lt_of_mul_lt_mul_left ha (zero_le _)) (mul_comm _ _) }
end
... = _ :
have h1 : set.inj_on (* p) (range (p ^ n)),
from λ x _ y _, (nat.mul_left_inj hp.pos).1,
have h2 : (range (p ^ n)).image (* p) ⊆ range (p ^ (n + 1)),
from λ a, begin
simp only [mem_image, mem_range, exists_imp_distrib],
rintros b h rfl,
rw [pow_succ'],
exact (mul_lt_mul_right hp.pos).2 h
end,
begin
rw [card_sdiff h2, card_image_of_inj_on h1, card_range,
card_range, ← one_mul (p ^ n), pow_succ, ← tsub_mul,
one_mul, mul_comm]
end
/-- When `p` is prime, then the totient of `p ^ n` is `p ^ (n - 1) * (p - 1)` -/
lemma totient_prime_pow {p : ℕ} (hp : p.prime) {n : ℕ} (hn : 0 < n) :
φ (p ^ n) = p ^ (n - 1) * (p - 1) :=
by rcases exists_eq_succ_of_ne_zero (pos_iff_ne_zero.1 hn) with ⟨m, rfl⟩;
exact totient_prime_pow_succ hp _
lemma totient_prime {p : ℕ} (hp : p.prime) : φ p = p - 1 :=
by rw [← pow_one p, totient_prime_pow hp]; simp
lemma totient_mul_of_prime_of_dvd {p n : ℕ} (hp : p.prime) (h : p ∣ n) :
(p * n).totient = p * n.totient :=
begin
by_cases hzero : n = 0,
{ simp [hzero] },
{ have hfin := (multiplicity.finite_nat_iff.2 ⟨hp.ne_one, zero_lt_iff.2 hzero⟩),
have h0 : 0 < (multiplicity p n).get hfin := multiplicity.pos_of_dvd hfin h,
obtain ⟨m, hm, hndiv⟩ := multiplicity.exists_eq_pow_mul_and_not_dvd hfin,
rw [hm, ← mul_assoc, ← pow_succ, nat.totient_mul (coprime_comm.mp (hp.coprime_pow_of_not_dvd
hndiv)), nat.totient_mul (coprime_comm.mp (hp.coprime_pow_of_not_dvd hndiv)), ← mul_assoc],
congr,
rw [ ← succ_pred_eq_of_pos h0, totient_prime_pow_succ hp, totient_prime_pow_succ hp,
succ_pred_eq_of_pos h0, ← mul_assoc p, ← pow_succ, ← succ_pred_eq_of_pos h0, nat.pred_succ] }
end
lemma totient_eq_iff_prime {p : ℕ} (hp : 0 < p) : p.totient = p - 1 ↔ p.prime :=
begin
refine ⟨λ h, _, totient_prime⟩,
replace hp : 1 < p,
{ apply lt_of_le_of_ne,
{ rwa succ_le_iff },
{ rintro rfl,
rw [totient_one, tsub_self] at h,
exact one_ne_zero h } },
rw [totient_eq_card_coprime, range_eq_Ico, ←Ico_insert_succ_left hp.le, finset.filter_insert,
if_neg (not_coprime_of_dvd_of_dvd hp (dvd_refl p) (dvd_zero p)), ←nat.card_Ico 1 p] at h,
refine p.prime_of_coprime hp (λ n hn hnz, finset.filter_card_eq h n $ finset.mem_Ico.mpr ⟨_, hn⟩),
rwa [succ_le_iff, pos_iff_ne_zero],
end
lemma card_units_zmod_lt_sub_one {p : ℕ} (hp : 1 < p) [fintype ((zmod p)ˣ)] :
fintype.card ((zmod p)ˣ) ≤ p - 1 :=
begin
haveI : fact (0 < p) := ⟨zero_lt_one.trans hp⟩,
rw zmod.card_units_eq_totient p,
exact nat.le_pred_of_lt (nat.totient_lt p hp),
end
lemma prime_iff_card_units (p : ℕ) [fintype ((zmod p)ˣ)] :
p.prime ↔ fintype.card ((zmod p)ˣ) = p - 1 :=
begin
by_cases hp : p = 0,
{ substI hp,
simp only [zmod, not_prime_zero, false_iff, zero_tsub],
-- the substI created an non-defeq but subsingleton instance diamond; resolve it
suffices : fintype.card ℤˣ ≠ 0, { convert this },
simp },
haveI : fact (0 < p) := ⟨nat.pos_of_ne_zero hp⟩,
rw [zmod.card_units_eq_totient, nat.totient_eq_iff_prime (fact.out (0 < p))],
end
@[simp] lemma totient_two : φ 2 = 1 :=
(totient_prime prime_two).trans (by norm_num)
end nat
|
b76640197dca58fa51ff826ba2d1bf0c328856a7 | 4a3109c7bb55b7ea698278061cbb921b8db93b7f | /mm0-lean/x86/assembly.lean | ba2c21986b761996e95c2555588a150471d7e032 | [
"CC0-1.0"
] | permissive | LongJohnCoder/mm0 | d233200cd7baae9c521cacfbbe162b2ff3bd993f | 0c556a21af92d552e859fd42794f57398c3964cf | refs/heads/master | 1,600,930,472,594 | 1,574,627,400,000 | 1,574,627,400,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,078 | lean | import x86.lemmas
namespace x86
inductive arg : Type
| imm : qword → arg
| reg : regnum → arg
| mem : option scale_index → base → ℤ → arg
| label : ℕ → arg
| loc : ℕ → ℤ → arg
inductive directive
| label : ℕ → directive
| loc : ℕ → arg → directive
inductive asm1
| unop : unop → wsize → arg → asm1
| binop : binop → wsize → arg → arg → asm1
| mul : wsize → arg → asm1
| div : wsize → arg → asm1
| lea : wsize → arg → arg → asm1
| movsx : wsize → arg → arg → wsize → asm1
| movzx : wsize → arg → arg → wsize → asm1
| xchg : wsize → arg → regnum → asm1
| cmpxchg : wsize → arg → regnum → asm1
| xadd : wsize → arg → regnum → asm1
| cmov : cond_code → wsize → arg → arg → asm1
| setcc : cond_code → bool → arg → asm1
| jump : arg → asm1
| jcc : cond_code → ℕ → asm1
| call : arg → asm1
| ret : qword → asm1
| push : arg → asm1
| pop : arg → asm1
| leave : asm1
| cmc
| clc
| stc
| syscall
| exact : ast → asm1
inductive asm
| nil : asm
| cons : asm1 → asm → asm
| dir : directive → asm
| seq : asm → asm → asm
| block : asm → asm
def arg.offset : arg → ℤ → option arg
| (arg.mem si b v) w := some $ arg.mem si b (v + w)
| (arg.loc i v) w := some $ arg.loc i (v + w)
| _ _ := none
inductive assemble_imm_rm (locs : list arg) : arg → imm_rm → Prop
| imm (q) : assemble_imm_rm (arg.imm q) (imm_rm.imm q)
| reg (r) : assemble_imm_rm (arg.reg r) (imm_rm.rm (RM.reg r))
| mem (si b q) : assemble_imm_rm
(arg.mem si b (bitvec.to_int q)) (imm_rm.rm (RM.mem si b q))
| loc (i off a rm) :
(locs.nth i).bind (λ a, a.offset off) = some a →
assemble_imm_rm a rm → assemble_imm_rm (arg.loc i off) rm
def assemble_imm (locs : list arg) (a : arg) (q : qword) : Prop :=
assemble_imm_rm locs a (imm_rm.imm q)
def assemble_RM (locs : list arg) (a : arg) (rm : RM) : Prop :=
assemble_imm_rm locs a (imm_rm.rm rm)
def assemble_ds (locs : list arg) (d s : arg) : dest_src → Prop
| (dest_src.Rm_i rm q) := assemble_RM locs d rm ∧ assemble_imm locs s q
| (dest_src.Rm_r rm r) := assemble_RM locs d rm ∧ assemble_RM locs s (RM.reg r)
| (dest_src.R_rm r rm) := assemble_RM locs d (RM.reg r) ∧ assemble_RM locs s rm
inductive assemble1 (locs : list arg) (labs : list qword)
(rip : qword) : asm1 → ast → Prop
| unop (op sz a rm) :
assemble_RM locs a rm →
assemble1 (asm1.unop op sz a) (ast.unop op sz rm)
| binop (op sz d s ds) :
assemble_ds locs d s ds →
assemble1 (asm1.binop op sz d s) (ast.binop op sz ds)
| mul (sz a rm) :
assemble_RM locs a rm →
assemble1 (asm1.mul sz a) (ast.mul sz rm)
| div (sz a rm) :
assemble_RM locs a rm →
assemble1 (asm1.div sz a) (ast.div sz rm)
| lea (sz d s ds) :
assemble_ds locs d s ds →
assemble1 (asm1.lea sz d s) (ast.lea sz ds)
| movsx (sz d s sz2 ds) :
assemble_ds locs d s ds →
assemble1 (asm1.movsx sz d s sz2) (ast.movsx sz ds sz2)
| xchg (sz a rm r) :
assemble_RM locs a rm →
assemble1 (asm1.xchg sz a r) (ast.xchg sz rm r)
| cmpxchg (sz a rm r) :
assemble_RM locs a rm →
assemble1 (asm1.cmpxchg sz a r) (ast.cmpxchg sz rm r)
| xadd (sz a rm r) :
assemble_RM locs a rm →
assemble1 (asm1.xadd sz a r) (ast.xadd sz rm r)
| cmov (c sz d s ds) :
assemble_ds locs d s ds →
assemble1 (asm1.cmov c sz d s) (ast.cmov c sz ds)
| setcc (c b a rm) :
assemble_RM locs a rm →
assemble1 (asm1.setcc c b a) (ast.setcc c b rm)
| jump (a rm) :
assemble_RM locs a rm →
assemble1 (asm1.jump a) (ast.jump rm)
| jcc (c i q) :
labs.nth i = some q →
assemble1 (asm1.jcc c i) (ast.jcc c (rip - q))
| call (a rm) :
assemble_imm_rm locs a rm →
assemble1 (asm1.call a) (ast.call rm)
| ret (q) : assemble1 (asm1.ret q) (ast.ret q)
| push (a rm) :
assemble_imm_rm locs a rm →
assemble1 (asm1.push a) (ast.push rm)
| pop (a rm) :
assemble_RM locs a rm →
assemble1 (asm1.pop a) (ast.pop rm)
| leave : assemble1 asm1.leave ast.leave
| cmc : assemble1 asm1.cmc ast.cmc
| clc : assemble1 asm1.clc ast.clc
| stc : assemble1 asm1.stc ast.stc
| syscall : assemble1 asm1.syscall ast.syscall
| exact (a) : assemble1 (asm1.exact a) a
inductive assemble (locs : list arg) :
list qword → qword → asm → list byte → qword → Prop
| nil (labs rip) : assemble labs rip asm.nil [] rip
| asm1 (labs rip a ast as l l₂ rip') :
assemble1 locs labs rip a ast →
decode ast l →
assemble labs (rip + ↑l.length) as l₂ rip' →
assemble labs rip (asm.cons a as) (l ++ l₂) rip'
| label (labs rip i) :
list.nth labs i = some rip →
assemble labs rip (asm.dir (directive.label i)) [] rip
| loc (labs i arg rip) :
locs.nth i = some arg →
assemble labs rip (asm.dir (directive.loc i arg)) [] rip
| seq (labs rip as1 as2 l1 l2 rip1 rip2) :
assemble labs rip as1 l1 rip1 →
assemble labs rip1 as2 l2 rip2 →
assemble labs rip (asm.seq as1 as2) (l1 ++ l2) rip2
| block (labs rip rip1 as l rip') :
assemble (rip1 :: labs) rip as l rip' →
assemble labs rip (asm.block as) l rip'
end x86 |
761c6fa4867dbf779f3f99705490e6f22caa5731 | a19a4fce1e5677f4d20cbfdf60c04b6386ab8210 | /hott/init/types.hlean | f01da8acf3eb23d4c75f558258a662f636ab8f3b | [
"Apache-2.0"
] | permissive | nthomas103/lean | 9c341a316e7d9faa00546462f90a8aa402e17eac | 04eaf184a92606a56e54d0d6c8d59437557263fc | refs/heads/master | 1,586,061,106,806 | 1,454,640,115,000 | 1,454,641,279,000 | 51,127,143 | 0 | 0 | null | 1,454,648,683,000 | 1,454,648,683,000 | null | UTF-8 | Lean | false | false | 4,894 | hlean | /-
Copyright (c) 2014-2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn, Jakob von Raumer
-/
prelude
import init.num init.wf
open iff
-- Empty type
-- ----------
protected definition empty.has_decidable_eq [instance] : decidable_eq empty :=
take (a b : empty), decidable.inl (!empty.elim a)
-- Unit type
-- ---------
namespace unit
notation `⋆` := star
end unit
-- Sigma type
-- ----------
notation `Σ` binders `, ` r:(scoped P, sigma P) := r
abbreviation dpair [constructor] := @sigma.mk
namespace sigma
notation `⟨`:max t:(foldr `, ` (e r, mk e r)) `⟩`:0 := t --input ⟨ ⟩ as \< \>
namespace ops
postfix `.1`:(max+1) := pr1
postfix `.2`:(max+1) := pr2
abbreviation pr₁ := @pr1
abbreviation pr₂ := @pr2
end ops
end sigma
-- Sum type
-- --------
namespace sum
namespace low_precedence_plus
reserve infixr ` + `:25 -- conflicts with notation for addition
infixr ` + ` := sum
end low_precedence_plus
variables {a b c d : Type}
definition sum_of_sum_of_imp_of_imp (H₁ : a ⊎ b) (H₂ : a → c) (H₃ : b → d) : c ⊎ d :=
sum.rec_on H₁
(assume Ha : a, sum.inl (H₂ Ha))
(assume Hb : b, sum.inr (H₃ Hb))
definition sum_of_sum_of_imp_left (H₁ : a ⊎ c) (H : a → b) : b ⊎ c :=
sum.rec_on H₁
(assume H₂ : a, sum.inl (H H₂))
(assume H₂ : c, sum.inr H₂)
definition sum_of_sum_of_imp_right (H₁ : c ⊎ a) (H : a → b) : c ⊎ b :=
sum.rec_on H₁
(assume H₂ : c, sum.inl H₂)
(assume H₂ : a, sum.inr (H H₂))
end sum
-- Product type
-- ------------
namespace prod
-- notation for n-ary tuples
notation `(` h `, ` t:(foldl `,` (e r, prod.mk r e) h) `)` := t
namespace ops
postfix `.1`:(max+1) := pr1
postfix `.2`:(max+1) := pr2
abbreviation pr₁ := @pr1
abbreviation pr₂ := @pr2
end ops
namespace low_precedence_times
reserve infixr ` * `:30 -- conflicts with notation for multiplication
infixr ` * ` := prod
end low_precedence_times
open prod.ops
definition flip [unfold 3] {A B : Type} (a : A × B) : B × A := pair (pr2 a) (pr1 a)
open well_founded
section
variables {A B : Type}
variable (Ra : A → A → Type)
variable (Rb : B → B → Type)
-- Lexicographical order based on Ra and Rb
inductive lex : A × B → A × B → Type :=
| left : ∀{a₁ b₁} a₂ b₂, Ra a₁ a₂ → lex (a₁, b₁) (a₂, b₂)
| right : ∀a {b₁ b₂}, Rb b₁ b₂ → lex (a, b₁) (a, b₂)
-- Relational product based on Ra and Rb
inductive rprod : A × B → A × B → Type :=
intro : ∀{a₁ b₁ a₂ b₂}, Ra a₁ a₂ → Rb b₁ b₂ → rprod (a₁, b₁) (a₂, b₂)
end
section
parameters {A B : Type}
parameters {Ra : A → A → Type} {Rb : B → B → Type}
local infix `≺`:50 := lex Ra Rb
definition lex.accessible {a} (aca : acc Ra a) (acb : ∀b, acc Rb b): ∀b, acc (lex Ra Rb) (a, b) :=
acc.rec_on aca
(λxa aca (iHa : ∀y, Ra y xa → ∀b, acc (lex Ra Rb) (y, b)),
λb, acc.rec_on (acb b)
(λxb acb
(iHb : ∀y, Rb y xb → acc (lex Ra Rb) (xa, y)),
acc.intro (xa, xb) (λp (lt : p ≺ (xa, xb)),
have aux : xa = xa → xb = xb → acc (lex Ra Rb) p, from
@prod.lex.rec_on A B Ra Rb (λp₁ p₂ h, pr₁ p₂ = xa → pr₂ p₂ = xb → acc (lex Ra Rb) p₁)
p (xa, xb) lt
(λa₁ b₁ a₂ b₂ (H : Ra a₁ a₂) (eq₂ : a₂ = xa) (eq₃ : b₂ = xb),
show acc (lex Ra Rb) (a₁, b₁), from
have Ra₁ : Ra a₁ xa, from eq.rec_on eq₂ H,
iHa a₁ Ra₁ b₁)
(λa b₁ b₂ (H : Rb b₁ b₂) (eq₂ : a = xa) (eq₃ : b₂ = xb),
show acc (lex Ra Rb) (a, b₁), from
have Rb₁ : Rb b₁ xb, from eq.rec_on eq₃ H,
have eq₂' : xa = a, from eq.rec_on eq₂ rfl,
eq.rec_on eq₂' (iHb b₁ Rb₁)),
aux rfl rfl)))
-- The lexicographical order of well founded relations is well-founded
definition lex.wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (lex Ra Rb) :=
well_founded.intro (λp, destruct p (λa b, lex.accessible (Ha a) (well_founded.apply Hb) b))
-- Relational product is a subrelation of the lex
definition rprod.sub_lex : ∀ a b, rprod Ra Rb a b → lex Ra Rb a b :=
λa b H, prod.rprod.rec_on H (λ a₁ b₁ a₂ b₂ H₁ H₂, lex.left Rb a₂ b₂ H₁)
-- The relational product of well founded relations is well-founded
definition rprod.wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (rprod Ra Rb) :=
subrelation.wf (rprod.sub_lex) (lex.wf Ha Hb)
end
end prod
|
24118532a4eb9ecf25a136c0d3b53fe089136e7c | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Lean/Server/Watchdog.lean | bb22b52f7be8b70e7c2e1274e5923f667e102cb9 | [
"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 | 34,035 | lean | /-
Copyright (c) 2020 Marc Huisinga. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Marc Huisinga, Wojciech Nawrocki
-/
import Init.System.IO
import Init.Data.ByteArray
import Std.Data.RBMap
import Std.System.Uri
import Lean.Elab.Import
import Lean.Util.Paths
import Lean.Data.FuzzyMatching
import Lean.Data.Json
import Lean.Data.Lsp
import Lean.Server.Utils
import Lean.Server.Requests
import Lean.Server.References
/-!
For general server architecture, see `README.md`. This module implements the watchdog process.
## Watchdog state
Most LSP clients only send us file diffs, so to facilitate sending entire file contents to freshly restarted
workers, the watchdog needs to maintain the current state of each file. It can also use this state to detect changes
to the header and thus restart the corresponding worker, freeing its imports.
TODO(WN):
We may eventually want to keep track of approximately (since this isn't knowable exactly) where in the file a worker
crashed. Then on restart, we tell said worker to only parse up to that point and query the user about how to proceed
(continue OR allow the user to fix the bug and then continue OR ..). Without this, if the crash is deterministic,
users may be confused about why the server seemingly stopped working for a single file.
## Watchdog <-> worker communication
The watchdog process and its file worker processes communicate via LSP. If the necessity arises,
we might add non-standard commands similarly based on JSON-RPC. Most requests and notifications
are forwarded to the corresponding file worker process, with the exception of these notifications:
- textDocument/didOpen: Launch the file worker, create the associated watchdog state and launch a task to
asynchronously receive LSP packets from the worker (e.g. request responses).
- textDocument/didChange: Update the local file state. If the header was mutated,
signal a shutdown to the file worker by closing the I/O channels.
Then restart the file worker. Otherwise, forward the `didChange` notification.
- textDocument/didClose: Signal a shutdown to the file worker and remove the associated watchdog state.
Moreover, we don't implement the full protocol at this level:
- Upon starting, the `initialize` request is forwarded to the worker, but it must not respond with its server
capabilities. Consequently, the watchdog will not send an `initialized` notification to the worker.
- After `initialize`, the watchdog sends the corresponding `didOpen` notification with the full current state of
the file. No additional `didOpen` notifications will be forwarded to the worker process.
- `$/cancelRequest` notifications are forwarded to all file workers.
- File workers are always terminated with an `exit` notification, without previously receiving a `shutdown` request.
Similarly, they never receive a `didClose` notification.
## Watchdog <-> client communication
The watchdog itself should implement the LSP standard as closely as possible. However we reserve the right to add
non-standard extensions in case they're needed, for example to communicate tactic state.
-/
namespace Lean.Server.Watchdog
open IO
open Std (RBMap RBMap.empty)
open Lsp
open JsonRpc
open System.Uri
section Utils
structure OpenDocument where
meta : DocumentMeta
headerAst : Syntax
def workerCfg : Process.StdioConfig := {
stdin := Process.Stdio.piped
stdout := Process.Stdio.piped
-- We pass workers' stderr through to the editor.
stderr := Process.Stdio.inherit
}
/-- Events that worker-specific tasks signal to the main thread. -/
inductive WorkerEvent where
| /-- A synthetic event signalling that the grouped edits should be processed. -/
processGroupedEdits
| terminated
| crashed (e : IO.Error)
| ioError (e : IO.Error)
inductive WorkerState where
| /-- The watchdog can detect a crashed file worker in two places: When trying to send a message to the file worker
and when reading a request reply.
In the latter case, the forwarding task terminates and delegates a `crashed` event to the main task.
Then, in both cases, the file worker has its state set to `crashed` and requests that are in-flight are errored.
Upon receiving the next packet for that file worker, the file worker is restarted and the packet is forwarded
to it. If the crash was detected while writing a packet, we queue that packet until the next packet for the file
worker arrives. -/
crashed (queuedMsgs : Array JsonRpc.Message)
| running
abbrev PendingRequestMap := RBMap RequestID JsonRpc.Message compare
private def parseHeaderAst (input : String) : IO Syntax := do
let inputCtx := Parser.mkInputContext input "<input>"
let (stx, _, _) ← Parser.parseHeader inputCtx
return stx
end Utils
section FileWorker
/-- A group of edits which will be processed at a future instant. -/
structure GroupedEdits where
/-- When to process the edits. -/
applyTime : Nat
params : DidChangeTextDocumentParams
/-- Signals when `applyTime` has been reached. -/
signalTask : Task WorkerEvent
/-- We should not reorder messages when delaying edits, so we queue other messages since the last request here. -/
queuedMsgs : Array JsonRpc.Message
structure FileWorker where
doc : OpenDocument
proc : Process.Child workerCfg
commTask : Task WorkerEvent
state : WorkerState
-- This should not be mutated outside of namespace FileWorker, as it is used as shared mutable state
/-- The pending requests map contains all requests
that have been received from the LSP client, but were not answered yet.
This includes the queued messages in the grouped edits. -/
pendingRequestsRef : IO.Ref PendingRequestMap
groupedEditsRef : IO.Ref (Option GroupedEdits)
namespace FileWorker
def stdin (fw : FileWorker) : FS.Stream :=
FS.Stream.ofHandle fw.proc.stdin
def stdout (fw : FileWorker) : FS.Stream :=
FS.Stream.ofHandle fw.proc.stdout
def erasePendingRequest (fw : FileWorker) (id : RequestID) : IO Unit :=
fw.pendingRequestsRef.modify fun pendingRequests => pendingRequests.erase id
def errorPendingRequests (fw : FileWorker) (hError : FS.Stream) (code : ErrorCode) (msg : String) : IO Unit := do
let pendingRequests ← fw.pendingRequestsRef.modifyGet (fun pendingRequests => (pendingRequests, RBMap.empty))
for ⟨id, _⟩ in pendingRequests do
hError.writeLspResponseError { id := id, code := code, message := msg }
partial def runEditsSignalTask (fw : FileWorker) : IO (Task WorkerEvent) := do
-- check `applyTime` in a loop since it might have been postponed by a subsequent edit notification
let rec loopAction : IO WorkerEvent := do
let now ← monoMsNow
let some ge ← fw.groupedEditsRef.get
| throwServerError "Internal error: empty grouped edits reference in signal task"
if ge.applyTime ≤ now then
return WorkerEvent.processGroupedEdits
else
IO.sleep <| UInt32.ofNat <| ge.applyTime - now
loopAction
let t ← IO.asTask loopAction
return t.map fun
| Except.ok ev => ev
| Except.error e => WorkerEvent.ioError e
end FileWorker
end FileWorker
section ServerM
abbrev FileWorkerMap := RBMap DocumentUri FileWorker compare
structure ServerContext where
hIn : FS.Stream
hOut : FS.Stream
hLog : FS.Stream
/-- Command line arguments. -/
args : List String
fileWorkersRef : IO.Ref FileWorkerMap
/-- We store these to pass them to workers. -/
initParams : InitializeParams
editDelay : Nat
workerPath : System.FilePath
srcSearchPath : System.SearchPath
references : IO.Ref References
abbrev ServerM := ReaderT ServerContext IO
def updateFileWorkers (val : FileWorker) : ServerM Unit := do
(←read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.insert val.doc.meta.uri val)
def findFileWorker? (uri : DocumentUri) : ServerM (Option FileWorker) :=
return (← (←read).fileWorkersRef.get).find? uri
def findFileWorker! (uri : DocumentUri) : ServerM FileWorker := do
let some fw ← findFileWorker? uri
| throwServerError s!"cannot find open document '{uri}'"
return fw
def eraseFileWorker (uri : DocumentUri) : ServerM Unit := do
let s ← read
s.fileWorkersRef.modify (fun fileWorkers => fileWorkers.erase uri)
if let some path := fileUriToPath? uri then
if let some module ← searchModuleNameOfFileName path s.srcSearchPath then
s.references.modify fun refs => refs.removeWorkerRefs module
def log (msg : String) : ServerM Unit := do
let st ← read
st.hLog.putStrLn msg
st.hLog.flush
def handleIleanInfoUpdate (fw : FileWorker) (params : LeanIleanInfoParams) : ServerM Unit := do
let s ← read
if let some path := fileUriToPath? fw.doc.meta.uri then
if let some module ← searchModuleNameOfFileName path s.srcSearchPath then
s.references.modify fun refs => refs.updateWorkerRefs module params.version params.references
def handleIleanInfoFinal (fw : FileWorker) (params : LeanIleanInfoParams) : ServerM Unit := do
let s ← read
if let some path := fileUriToPath? fw.doc.meta.uri then
if let some module ← searchModuleNameOfFileName path s.srcSearchPath then
s.references.modify fun refs => refs.finalizeWorkerRefs module params.version params.references
/-- Creates a Task which forwards a worker's messages into the output stream until an event
which must be handled in the main watchdog thread (e.g. an I/O error) happens. -/
private partial def forwardMessages (fw : FileWorker) : ServerM (Task WorkerEvent) := do
let o := (←read).hOut
let rec loop : ServerM WorkerEvent := do
try
let msg ← fw.stdout.readLspMessage
-- Re. `o.writeLspMessage msg`:
-- Writes to Lean I/O channels are atomic, so these won't trample on each other.
match msg with
| Message.response id _ => do
fw.erasePendingRequest id
o.writeLspMessage msg
| Message.responseError id _ _ _ => do
fw.erasePendingRequest id
o.writeLspMessage msg
| Message.notification "$/lean/ileanInfoUpdate" params =>
if let some params := params then
if let Except.ok params := FromJson.fromJson? <| ToJson.toJson params then
handleIleanInfoUpdate fw params
| Message.notification "$/lean/ileanInfoFinal" params =>
if let some params := params then
if let Except.ok params := FromJson.fromJson? <| ToJson.toJson params then
handleIleanInfoFinal fw params
| _ => o.writeLspMessage msg
catch err =>
-- If writeLspMessage from above errors we will block here, but the main task will
-- quit eventually anyways if that happens
let exitCode ← fw.proc.wait
if exitCode = 0 then
-- Worker was terminated
fw.errorPendingRequests o ErrorCode.contentModified
("The file worker has been terminated. Either the header has changed,"
++ " or the file was closed, or the server is shutting down.")
return WorkerEvent.terminated
else
-- Worker crashed
fw.errorPendingRequests o (if exitCode = 1 then ErrorCode.workerExited else ErrorCode.workerCrashed)
s!"Server process for {fw.doc.meta.uri} crashed, {if exitCode = 1 then "see stderr for exception" else "likely due to a stack overflow or a bug"}."
publishProgressAtPos fw.doc.meta 0 o (kind := LeanFileProgressKind.fatalError)
return WorkerEvent.crashed err
loop
let task ← IO.asTask (loop $ ←read) Task.Priority.dedicated
return task.map fun
| Except.ok ev => ev
| Except.error e => WorkerEvent.ioError e
def startFileWorker (m : DocumentMeta) : ServerM Unit := do
publishProgressAtPos m 0 (← read).hOut
let st ← read
let headerAst ← parseHeaderAst m.text.source
let workerProc ← Process.spawn {
toStdioConfig := workerCfg
cmd := st.workerPath.toString
args := #["--worker"] ++ st.args.toArray ++ #[m.uri]
}
let pendingRequestsRef ← IO.mkRef (RBMap.empty : PendingRequestMap)
-- The task will never access itself, so this is fine
let fw : FileWorker := {
doc := ⟨m, headerAst⟩
proc := workerProc
commTask := Task.pure WorkerEvent.terminated
state := WorkerState.running
pendingRequestsRef := pendingRequestsRef
groupedEditsRef := ← IO.mkRef none
}
let commTask ← forwardMessages fw
let fw : FileWorker := { fw with commTask := commTask }
fw.stdin.writeLspRequest ⟨0, "initialize", st.initParams⟩
fw.stdin.writeLspNotification {
method := "textDocument/didOpen"
param := {
textDocument := {
uri := m.uri
languageId := "lean"
version := m.version
text := m.text.source
} : DidOpenTextDocumentParams
}
}
updateFileWorkers fw
def terminateFileWorker (uri : DocumentUri) : ServerM Unit := do
let fw ← findFileWorker! uri
try
fw.stdin.writeLspMessage (Message.notification "exit" none)
catch _ =>
/- The file worker must have crashed just when we were about to terminate it!
That's fine - just forget about it then.
(on didClose we won't need the crashed file worker anymore,
when the header changed we'll start a new one right after
anyways and when we're shutting down the server
it's over either way.) -/
return
eraseFileWorker uri
def handleCrash (uri : DocumentUri) (queuedMsgs : Array JsonRpc.Message) : ServerM Unit := do
updateFileWorkers { ←findFileWorker! uri with state := WorkerState.crashed queuedMsgs }
/-- Tries to write a message, sets the state of the FileWorker to `crashed` if it does not succeed
and restarts the file worker if the `crashed` flag was already set. Just logs an error if there
is no FileWorker at this `uri`.
Messages that couldn't be sent can be queued up via the queueFailedMessage flag and
will be discharged after the FileWorker is restarted. -/
def tryWriteMessage (uri : DocumentUri) (msg : JsonRpc.Message) (queueFailedMessage := true) (restartCrashedWorker := false) :
ServerM Unit := do
let some fw ← findFileWorker? uri
| do
(←read).hLog.putStrLn s!"Cannot send message to unknown document '{uri}':\n{(toJson msg).compress}"
return
let pendingEdit ← fw.groupedEditsRef.modifyGet fun
| some ge => (true, some { ge with queuedMsgs := ge.queuedMsgs.push msg })
| none => (false, none)
if pendingEdit then
return
match fw.state with
| WorkerState.crashed queuedMsgs =>
let mut queuedMsgs := queuedMsgs
if queueFailedMessage then
queuedMsgs := queuedMsgs.push msg
if !restartCrashedWorker then
return
-- restart the crashed FileWorker
eraseFileWorker uri
startFileWorker fw.doc.meta
let newFw ← findFileWorker! uri
let mut crashedMsgs := #[]
-- try to discharge all queued msgs, tracking the ones that we can't discharge
for msg in queuedMsgs do
try
newFw.stdin.writeLspMessage msg
catch _ =>
crashedMsgs := crashedMsgs.push msg
if ¬ crashedMsgs.isEmpty then
handleCrash uri crashedMsgs
| WorkerState.running =>
let initialQueuedMsgs :=
if queueFailedMessage then
#[msg]
else
#[]
try
fw.stdin.writeLspMessage msg
catch _ =>
handleCrash uri initialQueuedMsgs
end ServerM
section RequestHandling
open FuzzyMatching
def findDefinitions (p : TextDocumentPositionParams) : ServerM <| Array Location := do
let mut definitions := #[]
if let some path := fileUriToPath? p.textDocument.uri then
let srcSearchPath := (← read).srcSearchPath
if let some module ← searchModuleNameOfFileName path srcSearchPath then
let references ← (← read).references.get
for ident in references.findAt module p.position do
if let some definition ← references.definitionOf? ident srcSearchPath then
definitions := definitions.push definition
return definitions
def handleReference (p : ReferenceParams) : ServerM (Array Location) := do
let mut result := #[]
if let some path := fileUriToPath? p.textDocument.uri then
let srcSearchPath := (← read).srcSearchPath
if let some module ← searchModuleNameOfFileName path srcSearchPath then
let references ← (← read).references.get
for ident in references.findAt module p.position do
let identRefs ← references.referringTo module ident srcSearchPath p.context.includeDeclaration
result := result.append identRefs
return result
def handleWorkspaceSymbol (p : WorkspaceSymbolParams) : ServerM (Array SymbolInformation) := do
if p.query.isEmpty then
return #[]
let references ← (← read).references.get
let srcSearchPath := (← read).srcSearchPath
let symbols ← references.definitionsMatching srcSearchPath (maxAmount? := none)
fun name =>
let name := privateToUserName? name |>.getD name
if let some score := fuzzyMatchScoreWithThreshold? p.query name.toString then
some (name.toString, score)
else
none
return symbols
|>.qsort (fun ((_, s1), _) ((_, s2), _) => s1 > s2)
|>.extract 0 100 -- max amount
|>.map fun ((name, _), location) =>
{ name, kind := SymbolKind.constant, location }
end RequestHandling
section NotificationHandling
def handleDidOpen (p : DidOpenTextDocumentParams) : ServerM Unit :=
let doc := p.textDocument
/- NOTE(WN): `toFileMap` marks line beginnings as immediately following
"\n", which should be enough to handle both LF and CRLF correctly.
This is because LSP always refers to characters by (line, column),
so if we get the line number correct it shouldn't matter that there
is a CR there. -/
startFileWorker ⟨doc.uri, doc.version, doc.text.toFileMap⟩
def handleEdits (fw : FileWorker) : ServerM Unit := do
let some ge ← fw.groupedEditsRef.modifyGet (·, none)
| throwServerError "Internal error: empty grouped edits reference"
let doc := ge.params.textDocument
let changes := ge.params.contentChanges
let oldDoc := fw.doc
let some newVersion ← pure doc.version?
| throwServerError "Expected version number"
if newVersion <= oldDoc.meta.version then
throwServerError "Got outdated version number"
if changes.isEmpty then
return
let newDocText := foldDocumentChanges changes oldDoc.meta.text
let newMeta : DocumentMeta := ⟨doc.uri, newVersion, newDocText⟩
let newHeaderAst ← parseHeaderAst newDocText.source
if newHeaderAst != oldDoc.headerAst then
terminateFileWorker doc.uri
startFileWorker newMeta
else
let newDoc : OpenDocument := ⟨newMeta, oldDoc.headerAst⟩
updateFileWorkers { fw with doc := newDoc }
tryWriteMessage doc.uri (Notification.mk "textDocument/didChange" ge.params) (restartCrashedWorker := true)
for msg in ge.queuedMsgs do
tryWriteMessage doc.uri msg
def handleDidClose (p : DidCloseTextDocumentParams) : ServerM Unit :=
terminateFileWorker p.textDocument.uri
def handleDidChangeWatchedFiles (p : DidChangeWatchedFilesParams) : ServerM Unit := do
let references := (← read).references
let oleanSearchPath ← Lean.searchPathRef.get
let ileans ← oleanSearchPath.findAllWithExt "ilean"
for change in p.changes do
if let some path := fileUriToPath? change.uri then
if let FileChangeType.Deleted := change.type then
references.modify (fun r => r.removeIlean path)
else if ileans.contains path then
let ilean ← Ilean.load path
if let FileChangeType.Changed := change.type then
references.modify (fun r => r.removeIlean path |>.addIlean path ilean)
else
references.modify (fun r => r.addIlean path ilean)
def handleCancelRequest (p : CancelParams) : ServerM Unit := do
let fileWorkers ← (←read).fileWorkersRef.get
for ⟨uri, fw⟩ in fileWorkers do
-- Cancelled requests still require a response, so they can't be removed
-- from the pending requests map.
if (← fw.pendingRequestsRef.get).contains p.id then
tryWriteMessage uri (Notification.mk "$/cancelRequest" p) (queueFailedMessage := false)
def forwardNotification {α : Type} [ToJson α] [FileSource α] (method : String) (params : α) : ServerM Unit :=
tryWriteMessage (fileSource params) (Notification.mk method params) (queueFailedMessage := true)
end NotificationHandling
section MessageHandling
def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType :=
match fromJson? params with
| Except.ok parsed => pure parsed
| Except.error inner => throwServerError s!"Got param with wrong structure: {params.compress}\n{inner}"
def forwardRequestToWorker (id : RequestID) (method : String) (params : Json) : ServerM Unit := do
let uri: DocumentUri ←
-- This request is handled specially.
if method == "$/lean/rpc/connect" then
let ps ← parseParams Lsp.RpcConnectParams params
pure <| fileSource ps
else match (← routeLspRequest method params) with
| Except.error e =>
(←read).hOut.writeLspResponseError <| e.toLspResponseError id
return
| Except.ok uri => pure uri
let some fw ← findFileWorker? uri
/- Clients may send requests to closed files, which we respond to with an error.
For example, VSCode sometimes sends requests just after closing a file,
and RPC clients may also do so, e.g. due to remaining timers. -/
| do
(←read).hOut.writeLspResponseError
{ id := id
/- Some clients (VSCode) also send requests *before* opening a file. We reply
with `contentModified` as that does not display a "request failed" popup. -/
code := ErrorCode.contentModified
message := s!"Cannot process request to closed file '{uri}'" }
return
let r := Request.mk id method params
fw.pendingRequestsRef.modify (·.insert id r)
tryWriteMessage uri r
def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do
let handle α β [FromJson α] [ToJson β] (handler : α → ServerM β) : ServerM Unit := do
let hOut := (← read).hOut
try
let params ← parseParams α params
let result ← handler params
hOut.writeLspResponse ⟨id, result⟩
catch
-- TODO Do fancier error handling, like in file worker?
| e => hOut.writeLspResponseError {
id := id
code := ErrorCode.internalError
message := s!"Failed to process request {id}: {e}"
}
-- If a definition is in a different, modified file, the ilean data should
-- have the correct location while the olean still has outdated info from
-- the last compilation. This is easier than catching the client's reply and
-- fixing the definition's location afterwards, but it doesn't work for
-- go-to-type-definition.
if method == "textDocument/definition" || method == "textDocument/declaration" then
let params ← parseParams TextDocumentPositionParams params
let definitions ← findDefinitions params
if !definitions.isEmpty then
(← read).hOut.writeLspResponse ⟨id, definitions⟩
return
match method with
| "textDocument/references" => handle ReferenceParams (Array Location) handleReference
| "workspace/symbol" => handle WorkspaceSymbolParams (Array SymbolInformation) handleWorkspaceSymbol
| _ => forwardRequestToWorker id method params
def handleNotification (method : String) (params : Json) : ServerM Unit := do
let handle := (fun α [FromJson α] (handler : α → ServerM Unit) => parseParams α params >>= handler)
match method with
| "textDocument/didOpen" => handle DidOpenTextDocumentParams handleDidOpen
/- NOTE: textDocument/didChange is handled in the main loop. -/
| "textDocument/didClose" => handle DidCloseTextDocumentParams handleDidClose
| "workspace/didChangeWatchedFiles" => handle DidChangeWatchedFilesParams handleDidChangeWatchedFiles
| "$/cancelRequest" => handle CancelParams handleCancelRequest
| "$/lean/rpc/connect" => handle RpcConnectParams (forwardNotification method)
| "$/lean/rpc/release" => handle RpcReleaseParams (forwardNotification method)
| "$/lean/rpc/keepAlive" => handle RpcKeepAliveParams (forwardNotification method)
| _ =>
if !"$/".isPrefixOf method then -- implementation-dependent notifications can be safely ignored
(←read).hLog.putStrLn s!"Got unsupported notification: {method}"
end MessageHandling
section MainLoop
def shutdown : ServerM Unit := do
let fileWorkers ← (←read).fileWorkersRef.get
for ⟨uri, _⟩ in fileWorkers do
terminateFileWorker uri
for ⟨_, fw⟩ in fileWorkers do
discard <| IO.wait fw.commTask
inductive ServerEvent where
| workerEvent (fw : FileWorker) (ev : WorkerEvent)
| clientMsg (msg : JsonRpc.Message)
| clientError (e : IO.Error)
def runClientTask : ServerM (Task ServerEvent) := do
let st ← read
let readMsgAction : IO ServerEvent := do
/- Runs asynchronously. -/
let msg ← st.hIn.readLspMessage
pure <| ServerEvent.clientMsg msg
let clientTask := (← IO.asTask readMsgAction).map fun
| Except.ok ev => ev
| Except.error e => ServerEvent.clientError e
return clientTask
partial def mainLoop (clientTask : Task ServerEvent) : ServerM Unit := do
let st ← read
let workers ← st.fileWorkersRef.get
let mut workerTasks := #[]
for (_, fw) in workers do
if let WorkerState.running := fw.state then
workerTasks := workerTasks.push <| fw.commTask.map (ServerEvent.workerEvent fw)
if let some ge ← fw.groupedEditsRef.get then
workerTasks := workerTasks.push <| ge.signalTask.map (ServerEvent.workerEvent fw)
let ev ← IO.waitAny (workerTasks.push clientTask |>.toList)
match ev with
| ServerEvent.clientMsg msg =>
match msg with
| Message.request id "shutdown" _ =>
shutdown
st.hOut.writeLspResponse ⟨id, Json.null⟩
| Message.request id method (some params) =>
handleRequest id method (toJson params)
mainLoop (←runClientTask)
| Message.notification "textDocument/didChange" (some params) =>
let p ← parseParams DidChangeTextDocumentParams (toJson params)
let fw ← findFileWorker! p.textDocument.uri
let now ← monoMsNow
/- We wait `editDelay`ms since last edit before applying the changes. -/
let applyTime := now + st.editDelay
let queuedMsgs? ← fw.groupedEditsRef.modifyGet fun
| some ge => (some ge.queuedMsgs, some { ge with
applyTime := applyTime
params.textDocument := p.textDocument
params.contentChanges := ge.params.contentChanges ++ p.contentChanges
-- drain now-outdated messages and respond with `contentModified` below
queuedMsgs := #[] })
| none => (none, some {
applyTime := applyTime
params := p
/- This is overwritten just below. -/
signalTask := Task.pure WorkerEvent.processGroupedEdits
queuedMsgs := #[] })
match queuedMsgs? with
| some queuedMsgs =>
for msg in queuedMsgs do
match msg with
| JsonRpc.Message.request id _ _ =>
fw.erasePendingRequest id
(← read).hOut.writeLspResponseError {
id := id
code := ErrorCode.contentModified
message := "File changed."
}
| _ => pure () -- notifications do not need to be cancelled
| _ =>
let t ← fw.runEditsSignalTask
fw.groupedEditsRef.modify (Option.map fun ge => { ge with signalTask := t } )
mainLoop (←runClientTask)
| Message.notification method (some params) =>
handleNotification method (toJson params)
mainLoop (←runClientTask)
| Message.response "register_ilean_watcher" _ =>
mainLoop (←runClientTask)
| _ => throwServerError "Got invalid JSON-RPC message"
| ServerEvent.clientError e => throw e
| ServerEvent.workerEvent fw ev =>
match ev with
| WorkerEvent.processGroupedEdits =>
handleEdits fw
mainLoop clientTask
| WorkerEvent.ioError e =>
throwServerError s!"IO error while processing events for {fw.doc.meta.uri}: {e}"
| WorkerEvent.crashed _ =>
handleCrash fw.doc.meta.uri #[]
mainLoop clientTask
| WorkerEvent.terminated =>
throwServerError "Internal server error: got termination event for worker that should have been removed"
end MainLoop
def mkLeanServerCapabilities : ServerCapabilities := {
textDocumentSync? := some {
openClose := true
change := TextDocumentSyncKind.incremental
willSave := false
willSaveWaitUntil := false
save? := none
}
-- refine
completionProvider? := some {
triggerCharacters? := some #["."]
}
hoverProvider := true
declarationProvider := true
definitionProvider := true
typeDefinitionProvider := true
referencesProvider := true
workspaceSymbolProvider := true
documentHighlightProvider := true
documentSymbolProvider := true
foldingRangeProvider := true
semanticTokensProvider? := some {
legend := {
tokenTypes := SemanticTokenType.names
tokenModifiers := SemanticTokenModifier.names
}
full := true
range := true
}
}
def initAndRunWatchdogAux : ServerM Unit := do
let st ← read
try
discard $ st.hIn.readLspNotificationAs "initialized" InitializedParams
let clientTask ← runClientTask
mainLoop clientTask
catch err =>
shutdown
throw err
/- NOTE(WN): It looks like instead of sending the `exit` notification,
VSCode just closes the stream. In that case, pretend we got an `exit`. -/
let Message.notification "exit" none ←
try st.hIn.readLspMessage
catch _ => pure (Message.notification "exit" none)
| throwServerError "Got `shutdown` request, expected an `exit` notification"
def findWorkerPath : IO System.FilePath := do
let mut workerPath ← IO.appPath
if let some path := (←IO.getEnv "LEAN_SYSROOT") then
workerPath := System.FilePath.mk path / "bin" / "lean" |>.withExtension System.FilePath.exeExtension
if let some path := (←IO.getEnv "LEAN_WORKER_PATH") then
workerPath := System.FilePath.mk path
return workerPath
def loadReferences : IO References := do
let oleanSearchPath ← Lean.searchPathRef.get
let mut refs := References.empty
for path in ← oleanSearchPath.findAllWithExt "ilean" do
try
refs := refs.addIlean path (← Ilean.load path)
catch _ =>
-- could be a race with the build system, for example
-- ilean load errors should not be fatal, but we *should* log them
-- when we add logging to the server
pure ()
return refs
def initAndRunWatchdog (args : List String) (i o e : FS.Stream) : IO Unit := do
let workerPath ← findWorkerPath
let srcSearchPath ← initSrcSearchPath (← getBuildDir)
let references ← IO.mkRef (← loadReferences)
let fileWorkersRef ← IO.mkRef (RBMap.empty : FileWorkerMap)
let i ← maybeTee "wdIn.txt" false i
let o ← maybeTee "wdOut.txt" true o
let e ← maybeTee "wdErr.txt" true e
let initRequest ← i.readLspRequestAs "initialize" InitializeParams
o.writeLspResponse {
id := initRequest.id
result := {
capabilities := mkLeanServerCapabilities
serverInfo? := some {
name := "Lean 4 Server"
version? := "0.1.1"
}
: InitializeResult
}
}
o.writeLspRequest {
id := RequestID.str "register_ilean_watcher"
method := "client/registerCapability"
param := some {
registrations := #[ {
id := "ilean_watcher"
method := "workspace/didChangeWatchedFiles"
registerOptions := some <| toJson {
watchers := #[ { globPattern := "**/*.ilean" } ]
: DidChangeWatchedFilesRegistrationOptions }
} ]
: RegistrationParams }
}
ReaderT.run initAndRunWatchdogAux {
hIn := i
hOut := o
hLog := e
args := args
fileWorkersRef := fileWorkersRef
initParams := initRequest.param
editDelay := initRequest.param.initializationOptions? |>.bind InitializationOptions.editDelay? |>.getD 200
workerPath
srcSearchPath
references
: ServerContext
}
@[export lean_server_watchdog_main]
def watchdogMain (args : List String) : IO UInt32 := do
let i ← IO.getStdin
let o ← IO.getStdout
let e ← IO.getStderr
try
initAndRunWatchdog args i o e
return 0
catch err =>
e.putStrLn s!"Watchdog error: {err}"
return 1
end Lean.Server.Watchdog
|
17962f7c63a58f07b28f2e4a22013e4102de669e | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/logic/default.lean | 21d615c022df37a3e36b8c373cd9ed3e46a7c399 | [
"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 | 246 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
-/
import logic.eq logic.connectives logic.cast
import logic.quantifiers logic.identities
|
cb3e4d060923a87e1ab1e86d2da66df79dc932f4 | 2c096fdfecf64e46ea7bc6ce5521f142b5926864 | /src/Lean/PrettyPrinter/Delaborator/Builtins.lean | 4cf71c1fda5eb97cf8a6260c5fef36b8c0c3ad37 | [
"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 | 32,385 | lean | /-
Copyright (c) 2020 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
import Lean.PrettyPrinter.Delaborator.Basic
import Lean.PrettyPrinter.Delaborator.SubExpr
import Lean.PrettyPrinter.Delaborator.TopDownAnalyze
import Lean.Parser
namespace Lean.PrettyPrinter.Delaborator
open Lean.Meta
open Lean.Parser.Term
open SubExpr
open TSyntax.Compat
def maybeAddBlockImplicit (ident : Syntax) : DelabM Syntax := do
if ← getPPOption getPPAnalysisBlockImplicit then `(@$ident:ident) else pure ident
def unfoldMDatas : Expr → Expr
| Expr.mdata _ e => unfoldMDatas e
| e => e
@[builtin_delab fvar]
def delabFVar : Delab := do
let Expr.fvar fvarId ← getExpr | unreachable!
try
let l ← fvarId.getDecl
maybeAddBlockImplicit (mkIdent l.userName)
catch _ =>
-- loose free variable, use internal name
maybeAddBlockImplicit <| mkIdent fvarId.name
-- loose bound variable, use pseudo syntax
@[builtin_delab bvar]
def delabBVar : Delab := do
let Expr.bvar idx ← getExpr | unreachable!
pure $ mkIdent $ Name.mkSimple $ "#" ++ toString idx
@[builtin_delab mvar]
def delabMVar : Delab := do
let Expr.mvar n ← getExpr | unreachable!
let mvarDecl ← n.getDecl
let n :=
match mvarDecl.userName with
| Name.anonymous => n.name.replacePrefix `_uniq `m
| n => n
`(?$(mkIdent n))
@[builtin_delab sort]
def delabSort : Delab := do
let Expr.sort l ← getExpr | unreachable!
match l with
| Level.zero => `(Prop)
| Level.succ .zero => `(Type)
| _ => match l.dec with
| some l' => `(Type $(Level.quote l' max_prec))
| none => `(Sort $(Level.quote l max_prec))
-- NOTE: not a registered delaborator, as `const` is never called (see [delab] description)
def delabConst : Delab := do
let Expr.const c₀ ls ← getExpr | unreachable!
let c₀ := if (← getPPOption getPPPrivateNames) then c₀ else (privateToUserName? c₀).getD c₀
let mut c ← unresolveNameGlobal c₀ (fullNames := ← getPPOption getPPFullNames)
let stx ← if ls.isEmpty || !(← getPPOption getPPUniverses) then
if (← getLCtx).usesUserName c then
-- `c` is also a local declaration
if c == c₀ && !(← read).inPattern then
-- `c` is the fully qualified named. So, we append the `_root_` prefix
c := `_root_ ++ c
else
c := c₀
pure <| mkIdent c
else
`($(mkIdent c).{$[$(ls.toArray.map quote)],*})
let mut stx ← maybeAddBlockImplicit stx
if (← getPPOption getPPTagAppFns) then
stx ← annotateCurPos stx
addTermInfo (← getPos) stx (← getExpr)
return stx
def withMDataOptions [Inhabited α] (x : DelabM α) : DelabM α := do
match ← getExpr with
| Expr.mdata m .. =>
let mut posOpts := (← read).optionsPerPos
let pos ← getPos
for (k, v) in m do
if (`pp).isPrefixOf k then
let opts := posOpts.find? pos |>.getD {}
posOpts := posOpts.insert pos (opts.insert k v)
withReader ({ · with optionsPerPos := posOpts }) $ withMDataExpr x
| _ => x
partial def withMDatasOptions [Inhabited α] (x : DelabM α) : DelabM α := do
if (← getExpr).isMData then withMDataOptions (withMDatasOptions x) else x
def delabAppFn : Delab := do
if (← getExpr).consumeMData.isConst then
withMDatasOptions delabConst
else
delab
structure ParamKind where
name : Name
bInfo : BinderInfo
defVal : Option Expr := none
isAutoParam : Bool := false
def ParamKind.isRegularExplicit (param : ParamKind) : Bool :=
param.bInfo.isExplicit && !param.isAutoParam && param.defVal.isNone
/-- Return array with n-th element set to kind of n-th parameter of `e`. -/
partial def getParamKinds : DelabM (Array ParamKind) := do
let e ← getExpr
try
withTransparency TransparencyMode.all do
forallTelescopeArgs e.getAppFn e.getAppArgs fun params _ => do
params.mapM fun param => do
let l ← param.fvarId!.getDecl
pure { name := l.userName, bInfo := l.binderInfo, defVal := l.type.getOptParamDefault?, isAutoParam := l.type.isAutoParam }
catch _ => pure #[] -- recall that expr may be nonsensical
where
forallTelescopeArgs f args k := do
forallBoundedTelescope (← inferType f) args.size fun xs b =>
if xs.isEmpty || xs.size == args.size then
-- we still want to consider optParams
forallTelescopeReducing b fun ys b => k (xs ++ ys) b
else
forallTelescopeArgs (mkAppN f $ args.shrink xs.size) (args.extract xs.size args.size) fun ys b =>
k (xs ++ ys) b
@[builtin_delab app]
def delabAppExplicit : Delab := do
let paramKinds ← getParamKinds
let tagAppFn ← getPPOption getPPTagAppFns
let (fnStx, _, argStxs) ← withAppFnArgs
(do
let stx ← withOptionAtCurrPos `pp.tagAppFns tagAppFn delabAppFn
let needsExplicit := stx.raw.getKind != ``Lean.Parser.Term.explicit
let stx ← if needsExplicit then `(@$stx) else pure stx
pure (stx, paramKinds.toList, #[]))
(fun ⟨fnStx, paramKinds, argStxs⟩ => do
let isInstImplicit := match paramKinds with
| [] => false
| param :: _ => param.bInfo == BinderInfo.instImplicit
let argStx ← if ← getPPOption getPPAnalysisHole then `(_)
else if isInstImplicit == true then
let stx ← if ← getPPOption getPPInstances then delab else `(_)
if ← getPPOption getPPInstanceTypes then
let typeStx ← withType delab
`(($stx : $typeStx))
else pure stx
else delab
pure (fnStx, paramKinds.tailD [], argStxs.push argStx))
return Syntax.mkApp fnStx argStxs
def shouldShowMotive (motive : Expr) (opts : Options) : MetaM Bool := do
pure (getPPMotivesAll opts)
<||> (pure (getPPMotivesPi opts) <&&> returnsPi motive)
<||> (pure (getPPMotivesNonConst opts) <&&> isNonConstFun motive)
def isRegularApp : DelabM Bool := do
let e ← getExpr
if not (unfoldMDatas e.getAppFn).isConst then return false
if ← withNaryFn (withMDatasOptions (getPPOption getPPUniverses <||> getPPOption getPPAnalysisBlockImplicit)) then return false
for i in [:e.getAppNumArgs] do
if ← withNaryArg i (getPPOption getPPAnalysisNamedArg) then return false
return true
def unexpandRegularApp (stx : Syntax) : Delab := do
let Expr.const c .. := (unfoldMDatas (← getExpr).getAppFn) | unreachable!
let fs := appUnexpanderAttribute.getValues (← getEnv) c
let ref ← getRef
fs.firstM fun f =>
match f stx |>.run ref |>.run () with
| EStateM.Result.ok stx _ => pure stx
| _ => failure
def unexpandStructureInstance (stx : Syntax) : Delab := whenPPOption getPPStructureInstances do
let env ← getEnv
let e ← getExpr
let some s ← pure $ e.isConstructorApp? env | failure
guard $ isStructure env s.induct;
/- If implicit arguments should be shown, and the structure has parameters, we should not
pretty print using { ... }, because we will not be able to see the parameters. -/
let fieldNames := getStructureFields env s.induct
let mut fields := #[]
guard $ fieldNames.size == stx[1].getNumArgs
let args := e.getAppArgs
let fieldVals := args.extract s.numParams args.size
for idx in [:fieldNames.size] do
let fieldName := fieldNames[idx]!
let fieldId := mkIdent fieldName
let fieldPos ← nextExtraPos
let fieldId := annotatePos fieldPos fieldId
addFieldInfo fieldPos (s.induct ++ fieldName) fieldName fieldId fieldVals[idx]!
let field ← `(structInstField|$fieldId:ident := $(stx[1][idx]))
fields := fields.push field
let tyStx ← withType do
if (← getPPOption getPPStructureInstanceType) then delab >>= pure ∘ some else pure none
`({ $fields,* $[: $tyStx]? })
@[builtin_delab app]
def delabAppImplicit : Delab := do
-- TODO: always call the unexpanders, make them guard on the right # args?
let paramKinds ← getParamKinds
if ← getPPOption getPPExplicit then
if paramKinds.any (fun param => !param.isRegularExplicit) then failure
-- If the application has an implicit function type, fall back to delabAppExplicit.
-- This is e.g. necessary for `@Eq`.
let isImplicitApp ← try
let ty ← whnf (← inferType (← getExpr))
pure <| ty.isForall && (ty.binderInfo == BinderInfo.implicit || ty.binderInfo == BinderInfo.instImplicit)
catch _ => pure false
if isImplicitApp then failure
let tagAppFn ← getPPOption getPPTagAppFns
let (fnStx, _, argStxs) ← withAppFnArgs
(withOptionAtCurrPos `pp.tagAppFns tagAppFn <|
return (← delabAppFn, paramKinds.toList, #[]))
(fun (fnStx, paramKinds, argStxs) => do
let arg ← getExpr
let opts ← getOptions
let mkNamedArg (name : Name) (argStx : Syntax) : DelabM Syntax := do
`(Parser.Term.namedArgument| ($(mkIdent name) := $argStx))
let argStx? : Option Syntax ←
if ← getPPOption getPPAnalysisSkip then pure none
else if ← getPPOption getPPAnalysisHole then `(_)
else
match paramKinds with
| [] => delab
| param :: rest =>
if param.defVal.isSome && rest.isEmpty then
let v := param.defVal.get!
if !v.hasLooseBVars && v == arg then pure none else delab
else if !param.isRegularExplicit && param.defVal.isNone then
if ← getPPOption getPPAnalysisNamedArg <||> (pure (param.name == `motive) <&&> shouldShowMotive arg opts) then some <$> mkNamedArg param.name (← delab) else pure none
else delab
let argStxs := match argStx? with
| none => argStxs
| some stx => argStxs.push stx
pure (fnStx, paramKinds.tailD [], argStxs))
let stx := Syntax.mkApp fnStx argStxs
if ← isRegularApp then
(guard (← getPPOption getPPNotation) *> unexpandRegularApp stx)
<|> (guard (← getPPOption getPPStructureInstances) *> unexpandStructureInstance stx)
<|> pure stx
else pure stx
/-- State for `delabAppMatch` and helpers. -/
structure AppMatchState where
info : MatcherInfo
matcherTy : Expr
params : Array Expr := #[]
motive : Option (Term × Expr) := none
motiveNamed : Bool := false
discrs : Array Term := #[]
varNames : Array (Array Name) := #[]
rhss : Array Term := #[]
-- additional arguments applied to the result of the `match` expression
moreArgs : Array Term := #[]
/--
Extract arguments of motive applications from the matcher type.
For the example below: `#[#[`([])], #[`(a::as)]]` -/
private partial def delabPatterns (st : AppMatchState) : DelabM (Array (Array Term)) :=
withReader (fun ctx => { ctx with inPattern := true, optionsPerPos := {} }) do
let ty ← instantiateForall st.matcherTy st.params
-- need to reduce `let`s that are lifted into the matcher type
forallTelescopeReducing ty fun params _ => do
-- skip motive and discriminators
let alts := Array.ofSubarray params[1 + st.discrs.size:]
alts.mapIdxM fun idx alt => do
let ty ← inferType alt
-- TODO: this is a hack; we are accessing the expression out-of-sync with the position
-- Currently, we reset `optionsPerPos` at the beginning of `delabPatterns` to avoid
-- incorrectly considering annotations.
withTheReader SubExpr ({ · with expr := ty }) $
usingNames st.varNames[idx]! do
withAppFnArgs (pure #[]) (fun pats => do pure $ pats.push (← delab))
where
usingNames {α} (varNames : Array Name) (x : DelabM α) : DelabM α :=
usingNamesAux 0 varNames x
usingNamesAux {α} (i : Nat) (varNames : Array Name) (x : DelabM α) : DelabM α :=
if i < varNames.size then
withBindingBody varNames[i]! <| usingNamesAux (i+1) varNames x
else
x
/-- Skip `numParams` binders, and execute `x varNames` where `varNames` contains the new binder names. -/
private partial def skippingBinders {α} (numParams : Nat) (x : Array Name → DelabM α) : DelabM α :=
loop numParams #[]
where
loop : Nat → Array Name → DelabM α
| 0, varNames => x varNames
| n+1, varNames => do
let rec visitLambda : DelabM α := do
let varName := (← getExpr).bindingName!.eraseMacroScopes
-- Pattern variables cannot shadow each other
if varNames.contains varName then
let varName := (← getLCtx).getUnusedName varName
withBindingBody varName do
loop n (varNames.push varName)
else
withBindingBodyUnusedName fun id => do
loop n (varNames.push id.getId)
let e ← getExpr
if e.isLambda then
visitLambda
else
-- eta expand `e`
let e ← forallTelescopeReducing (← inferType e) fun xs _ => do
if xs.size == 1 && (← inferType xs[0]!).isConstOf ``Unit then
-- `e` might be a thunk create by the dependent pattern matching compiler, and `xs[0]` may not even be a pattern variable.
-- If it is a pattern variable, it doesn't look too bad to use `()` instead of the pattern variable.
-- If it becomes a problem in the future, we should modify the dependent pattern matching compiler, and make sure
-- it adds an annotation to distinguish these two cases.
mkLambdaFVars xs (mkApp e (mkConst ``Unit.unit))
else
mkLambdaFVars xs (mkAppN e xs)
withTheReader SubExpr (fun ctx => { ctx with expr := e }) visitLambda
/--
Delaborate applications of "matchers" such as
```
List.map.match_1 : {α : Type _} →
(motive : List α → Sort _) →
(x : List α) → (Unit → motive List.nil) → ((a : α) → (as : List α) → motive (a :: as)) → motive x
```
-/
@[builtin_delab app]
def delabAppMatch : Delab := whenPPOption getPPNotation <| whenPPOption getPPMatch do
-- incrementally fill `AppMatchState` from arguments
let st ← withAppFnArgs
(do
let (Expr.const c us) ← getExpr | failure
let (some info) ← getMatcherInfo? c | failure
let matcherTy ← instantiateTypeLevelParams (← getConstInfo c) us
return { matcherTy, info : AppMatchState })
(fun st => do
if st.params.size < st.info.numParams then
return { st with params := st.params.push (← getExpr) }
else if st.motive.isNone then
-- store motive argument separately
let lamMotive ← getExpr
let piMotive ← lambdaTelescope lamMotive fun xs body => mkForallFVars xs body
-- TODO: pp.analyze has not analyzed `piMotive`, only `lamMotive`
-- Thus the binder types won't have any annotations
let piStx ← withTheReader SubExpr (fun cfg => { cfg with expr := piMotive }) delab
let named ← getPPOption getPPAnalysisNamedArg
return { st with motive := (piStx, lamMotive), motiveNamed := named }
else if st.discrs.size < st.info.numDiscrs then
let idx := st.discrs.size
let discr ← delab
if let some hName := st.info.discrInfos[idx]!.hName? then
-- TODO: we should check whether the corresponding binder name, matches `hName`.
-- If it does not we should pretty print this `match` as a regular application.
return { st with discrs := st.discrs.push (← `(matchDiscr| $(mkIdent hName) : $discr)) }
else
return { st with discrs := st.discrs.push (← `(matchDiscr| $discr:term)) }
else if st.rhss.size < st.info.altNumParams.size then
/- We save the variables names here to be able to implement safe_shadowing.
The pattern delaboration must use the names saved here. -/
let (varNames, rhs) ← skippingBinders st.info.altNumParams[st.rhss.size]! fun varNames => do
let rhs ← delab
return (varNames, rhs)
return { st with rhss := st.rhss.push rhs, varNames := st.varNames.push varNames }
else
return { st with moreArgs := st.moreArgs.push (← delab) })
if st.discrs.size < st.info.numDiscrs || st.rhss.size < st.info.altNumParams.size then
-- underapplied
failure
match st.discrs, st.rhss with
| #[discr], #[] =>
let stx ← `(nomatch $discr)
return Syntax.mkApp stx st.moreArgs
| _, #[] => failure
| _, _ =>
let pats ← delabPatterns st
let stx ← do
let (piStx, lamMotive) := st.motive.get!
let opts ← getOptions
-- TODO: disable the match if other implicits are needed?
if ← pure st.motiveNamed <||> shouldShowMotive lamMotive opts then
`(match (motive := $piStx) $[$st.discrs:matchDiscr],* with $[| $pats,* => $st.rhss]*)
else
`(match $[$st.discrs:matchDiscr],* with $[| $pats,* => $st.rhss]*)
return Syntax.mkApp stx st.moreArgs
/--
Delaborate applications of the form `(fun x => b) v` as `let_fun x := v; b`
-/
def delabLetFun : Delab := do
let stxV ← withAppArg delab
withAppFn do
let Expr.lam n _ b _ ← getExpr | unreachable!
let n ← getUnusedName n b
let stxB ← withBindingBody n delab
if ← getPPOption getPPLetVarTypes <||> getPPOption getPPAnalysisLetVarType then
let stxT ← withBindingDomain delab
`(let_fun $(mkIdent n) : $stxT := $stxV; $stxB)
else
`(let_fun $(mkIdent n) := $stxV; $stxB)
@[builtin_delab mdata]
def delabMData : Delab := do
if let some _ := inaccessible? (← getExpr) then
let s ← withMDataExpr delab
if (← read).inPattern then
`(.($s)) -- We only include the inaccessible annotation when we are delaborating patterns
else
return s
else if isLetFun (← getExpr) && getPPNotation (← getOptions) then
withMDataExpr <| delabLetFun
else if let some _ := isLHSGoal? (← getExpr) then
withMDataExpr <| withAppFn <| withAppArg <| delab
else
withMDataOptions delab
/--
Check for a `Syntax.ident` of the given name anywhere in the tree.
This is usually a bad idea since it does not check for shadowing bindings,
but in the delaborator we assume that bindings are never shadowed.
-/
partial def hasIdent (id : Name) : Syntax → Bool
| Syntax.ident _ _ id' _ => id == id'
| Syntax.node _ _ args => args.any (hasIdent id)
| _ => false
/--
Return `true` iff current binder should be merged with the nested
binder, if any, into a single binder group:
* both binders must have same binder info and domain
* they cannot be inst-implicit (`[a b : A]` is not valid syntax)
* `pp.binderTypes` must be the same value for both terms
* prefer `fun a b` over `fun (a b)`
-/
private def shouldGroupWithNext : DelabM Bool := do
let e ← getExpr
let ppEType ← getPPOption (getPPBinderTypes e)
let go (e' : Expr) := do
let ppE'Type ← withBindingBody `_ $ getPPOption (getPPBinderTypes e)
pure $ e.binderInfo == e'.binderInfo &&
e.bindingDomain! == e'.bindingDomain! &&
e'.binderInfo != BinderInfo.instImplicit &&
ppEType == ppE'Type &&
(e'.binderInfo != BinderInfo.default || ppE'Type)
match e with
| Expr.lam _ _ e'@(Expr.lam _ _ _ _) _ => go e'
| Expr.forallE _ _ e'@(Expr.forallE _ _ _ _) _ => go e'
| _ => pure false
where
getPPBinderTypes (e : Expr) :=
if e.isForall then getPPPiBinderTypes else getPPFunBinderTypes
private partial def delabBinders (delabGroup : Array Syntax → Syntax → Delab) : optParam (Array Syntax) #[] → Delab
-- Accumulate names (`Syntax.ident`s with position information) of the current, unfinished
-- binder group `(d e ...)` as determined by `shouldGroupWithNext`. We cannot do grouping
-- inside-out, on the Syntax level, because it depends on comparing the Expr binder types.
| curNames => do
if ← shouldGroupWithNext then
-- group with nested binder => recurse immediately
withBindingBodyUnusedName fun stxN => delabBinders delabGroup (curNames.push stxN)
else
-- don't group => delab body and prepend current binder group
let (stx, stxN) ← withBindingBodyUnusedName fun stxN => return (← delab, stxN)
delabGroup (curNames.push stxN) stx
@[builtin_delab lam]
def delabLam : Delab :=
delabBinders fun curNames stxBody => do
let e ← getExpr
let stxT ← withBindingDomain delab
let ppTypes ← getPPOption getPPFunBinderTypes
let usedDownstream := curNames.any (fun n => hasIdent n.getId stxBody)
-- leave lambda implicit if possible
-- TODO: for now we just always block implicit lambdas when delaborating. We can revisit.
-- Note: the current issue is that it requires state, i.e. if *any* previous binder was implicit,
-- it doesn't seem like we can leave a subsequent binder implicit.
let blockImplicitLambda := true
/-
let blockImplicitLambda := expl ||
e.binderInfo == BinderInfo.default ||
-- Note: the following restriction fixes many issues with roundtripping,
-- but this condition may still not be perfectly in sync with the elaborator.
e.binderInfo == BinderInfo.instImplicit ||
Elab.Term.blockImplicitLambda stxBody ||
usedDownstream
-/
if !blockImplicitLambda then
pure stxBody
else
let defaultCase (_ : Unit) : Delab := do
if ppTypes then
-- "default" binder group is the only one that expects binder names
-- as a term, i.e. a single `Syntax.ident` or an application thereof
let stxCurNames ←
if curNames.size > 1 then
`($(curNames.get! 0) $(curNames.eraseIdx 0)*)
else
pure $ curNames.get! 0;
`(funBinder| ($stxCurNames : $stxT))
else
pure curNames.back -- here `curNames.size == 1`
let group ← match e.binderInfo, ppTypes with
| BinderInfo.default, _ => defaultCase ()
| BinderInfo.implicit, true => `(funBinder| {$curNames* : $stxT})
| BinderInfo.implicit, false => `(funBinder| {$curNames*})
| BinderInfo.strictImplicit, true => `(funBinder| ⦃$curNames* : $stxT⦄)
| BinderInfo.strictImplicit, false => `(funBinder| ⦃$curNames*⦄)
| BinderInfo.instImplicit, _ =>
if usedDownstream then `(funBinder| [$curNames.back : $stxT]) -- here `curNames.size == 1`
else `(funBinder| [$stxT])
match stxBody with
| `(fun $binderGroups* => $stxBody) => `(fun $group $binderGroups* => $stxBody)
| _ => `(fun $group => $stxBody)
/--
Similar to `delabBinders`, but tracking whether `forallE` is dependent or not.
See issue #1571
-/
private partial def delabForallBinders (delabGroup : Array Syntax → Bool → Syntax → Delab) (curNames : Array Syntax := #[]) (curDep := false) : Delab := do
let dep := !(← getExpr).isArrow
if !curNames.isEmpty && dep != curDep then
-- don't group
delabGroup curNames curDep (← delab)
else
let curDep := dep
if ← shouldGroupWithNext then
-- group with nested binder => recurse immediately
withBindingBodyUnusedName fun stxN => delabForallBinders delabGroup (curNames.push stxN) curDep
else
-- don't group => delab body and prepend current binder group
let (stx, stxN) ← withBindingBodyUnusedName fun stxN => return (← delab, stxN)
delabGroup (curNames.push stxN) curDep stx
@[builtin_delab forallE]
def delabForall : Delab := do
delabForallBinders fun curNames dependent stxBody => do
let e ← getExpr
let prop ← try isProp e catch _ => pure false
let stxT ← withBindingDomain delab
let group ← match e.binderInfo with
| BinderInfo.implicit => `(bracketedBinderF|{$curNames* : $stxT})
| BinderInfo.strictImplicit => `(bracketedBinderF|⦃$curNames* : $stxT⦄)
-- here `curNames.size == 1`
| BinderInfo.instImplicit => `(bracketedBinderF|[$curNames.back : $stxT])
| _ =>
-- NOTE: non-dependent arrows are available only for the default binder info
if dependent then
if prop && !(← getPPOption getPPPiBinderTypes) then
return ← `(∀ $curNames:ident*, $stxBody)
else
`(bracketedBinderF|($curNames* : $stxT))
else
return ← curNames.foldrM (fun _ stxBody => `($stxT → $stxBody)) stxBody
if prop then
match stxBody with
| `(∀ $groups*, $stxBody) => `(∀ $group $groups*, $stxBody)
| _ => `(∀ $group, $stxBody)
else
`($group:bracketedBinder → $stxBody)
@[builtin_delab letE]
def delabLetE : Delab := do
let Expr.letE n t v b _ ← getExpr | unreachable!
let n ← getUnusedName n b
let stxV ← descend v 1 delab
let stxB ← withLetDecl n t v fun fvar =>
let b := b.instantiate1 fvar
descend b 2 delab
if ← getPPOption getPPLetVarTypes <||> getPPOption getPPAnalysisLetVarType then
let stxT ← descend t 0 delab
`(let $(mkIdent n) : $stxT := $stxV; $stxB)
else `(let $(mkIdent n) := $stxV; $stxB)
@[builtin_delab lit]
def delabLit : Delab := do
let Expr.lit l ← getExpr | unreachable!
match l with
| Literal.natVal n => pure $ quote n
| Literal.strVal s => pure $ quote s
-- `@OfNat.ofNat _ n _` ~> `n`
@[builtin_delab app.OfNat.ofNat]
def delabOfNat : Delab := whenPPOption getPPCoercions do
let .app (.app _ (.lit (.natVal n))) _ ← getExpr | failure
return quote n
-- `@OfDecimal.ofDecimal _ _ m s e` ~> `m*10^(sign * e)` where `sign == 1` if `s = false` and `sign = -1` if `s = true`
@[builtin_delab app.OfScientific.ofScientific]
def delabOfScientific : Delab := whenPPOption getPPCoercions do
let expr ← getExpr
guard <| expr.getAppNumArgs == 5
let .lit (.natVal m) ← pure (expr.getArg! 2) | failure
let .lit (.natVal e) ← pure (expr.getArg! 4) | failure
let s ← match expr.getArg! 3 with
| Expr.const ``Bool.true _ => pure true
| Expr.const ``Bool.false _ => pure false
| _ => failure
let str := toString m
if s && e == str.length then
return Syntax.mkScientificLit ("0." ++ str)
else if s && e < str.length then
let mStr := str.extract 0 ⟨str.length - e⟩
let eStr := str.extract ⟨str.length - e⟩ ⟨str.length⟩
return Syntax.mkScientificLit (mStr ++ "." ++ eStr)
else
return Syntax.mkScientificLit (str ++ "e" ++ (if s then "-" else "") ++ toString e)
/--
Delaborate a projection primitive. These do not usually occur in
user code, but are pretty-printed when e.g. `#print`ing a projection
function.
-/
@[builtin_delab proj]
def delabProj : Delab := do
let Expr.proj _ idx _ ← getExpr | unreachable!
let e ← withProj delab
-- not perfectly authentic: elaborates to the `idx`-th named projection
-- function (e.g. `e.1` is `Prod.fst e`), which unfolds to the actual
-- `proj`.
let idx := Syntax.mkLit fieldIdxKind (toString (idx + 1));
`($(e).$idx:fieldIdx)
/-- Delaborate a call to a projection function such as `Prod.fst`. -/
@[builtin_delab app]
def delabProjectionApp : Delab := whenPPOption getPPStructureProjections $ do
let e@(Expr.app fn _) ← getExpr | failure
let .const c@(.str _ f) _ ← pure fn.getAppFn | failure
let env ← getEnv
let some info ← pure $ env.getProjectionFnInfo? c | failure
-- can't use with classes since the instance parameter is implicit
guard $ !info.fromClass
-- projection function should be fully applied (#struct params + 1 instance parameter)
-- TODO: support over-application
guard $ e.getAppNumArgs == info.numParams + 1
-- If pp.explicit is true, and the structure has parameters, we should not
-- use field notation because we will not be able to see the parameters.
let expl ← getPPOption getPPExplicit
guard $ !expl || info.numParams == 0
let appStx ← withAppArg delab
`($(appStx).$(mkIdent f):ident)
@[builtin_delab app.dite]
def delabDIte : Delab := whenPPOption getPPNotation do
-- Note: we keep this as a delaborator for now because it actually accesses the expression.
guard $ (← getExpr).getAppNumArgs == 5
let c ← withAppFn $ withAppFn $ withAppFn $ withAppArg delab
let (t, h) ← withAppFn $ withAppArg $ delabBranch none
let (e, _) ← withAppArg $ delabBranch h
`(if $(mkIdent h):ident : $c then $t else $e)
where
delabBranch (h? : Option Name) : DelabM (Syntax × Name) := do
let e ← getExpr
guard e.isLambda
let h ← match h? with
| some h => return (← withBindingBody h delab, h)
| none => withBindingBodyUnusedName fun h => do
return (← delab, h.getId)
@[builtin_delab app.cond]
def delabCond : Delab := whenPPOption getPPNotation do
guard $ (← getExpr).getAppNumArgs == 4
let c ← withAppFn $ withAppFn $ withAppArg delab
let t ← withAppFn $ withAppArg delab
let e ← withAppArg delab
`(bif $c then $t else $e)
@[builtin_delab app.namedPattern]
def delabNamedPattern : Delab := do
-- Note: we keep this as a delaborator because it accesses the DelabM context
guard (← read).inPattern
guard $ (← getExpr).getAppNumArgs == 4
let x ← withAppFn $ withAppFn $ withAppArg delab
let p ← withAppFn $ withAppArg delab
-- TODO: we should hide `h` if it has an inaccessible name and is not used in the rhs
let h ← withAppArg delab
guard x.raw.isIdent
`($x:ident@$h:ident:$p:term)
-- Sigma and PSigma delaborators
def delabSigmaCore (sigma : Bool) : Delab := whenPPOption getPPNotation do
guard $ (← getExpr).getAppNumArgs == 2
guard $ (← getExpr).appArg!.isLambda
withAppArg do
let α ← withBindingDomain delab
let bodyExpr := (← getExpr).bindingBody!
withBindingBodyUnusedName fun n => do
let b ← delab
if bodyExpr.hasLooseBVars then
if sigma then `(($n:ident : $α) × $b) else `(($n:ident : $α) ×' $b)
else
if sigma then `((_ : $α) × $b) else `((_ : $α) ×' $b)
@[builtin_delab app.Sigma]
def delabSigma : Delab := delabSigmaCore (sigma := true)
@[builtin_delab app.PSigma]
def delabPSigma : Delab := delabSigmaCore (sigma := false)
partial def delabDoElems : DelabM (List Syntax) := do
let e ← getExpr
if e.isAppOfArity ``Bind.bind 6 then
-- Bind.bind.{u, v} : {m : Type u → Type v} → [self : Bind m] → {α β : Type u} → m α → (α → m β) → m β
let α := e.getAppArgs[2]!
let ma ← withAppFn $ withAppArg delab
withAppArg do
match (← getExpr) with
| Expr.lam _ _ body _ =>
withBindingBodyUnusedName fun n => do
if body.hasLooseBVars then
prependAndRec `(doElem|let $n:term ← $ma:term)
else if α.isConstOf ``Unit || α.isConstOf ``PUnit then
prependAndRec `(doElem|$ma:term)
else
prependAndRec `(doElem|let _ ← $ma:term)
| _ => failure
else if e.isLet then
let Expr.letE n t v b _ ← getExpr | unreachable!
let n ← getUnusedName n b
let stxT ← descend t 0 delab
let stxV ← descend v 1 delab
withLetDecl n t v fun fvar =>
let b := b.instantiate1 fvar
descend b 2 $
prependAndRec `(doElem|let $(mkIdent n) : $stxT := $stxV)
else
let stx ← delab
return [← `(doElem|$stx:term)]
where
prependAndRec x : DelabM _ := List.cons <$> x <*> delabDoElems
@[builtin_delab app.Bind.bind]
def delabDo : Delab := whenPPOption getPPNotation do
guard <| (← getExpr).isAppOfArity ``Bind.bind 6
let elems ← delabDoElems
let items ← elems.toArray.mapM (`(doSeqItem|$(·):doElem))
`(do $items:doSeqItem*)
def reifyName : Expr → DelabM Name
| .const ``Lean.Name.anonymous .. => return Name.anonymous
| .app (.app (.const ``Lean.Name.str ..) n) (.lit (.strVal s)) => return (← reifyName n).mkStr s
| .app (.app (.const ``Lean.Name.num ..) n) (.lit (.natVal i)) => return (← reifyName n).mkNum i
| _ => failure
@[builtin_delab app.Lean.Name.str]
def delabNameMkStr : Delab := whenPPOption getPPNotation do
let n ← reifyName (← getExpr)
-- not guaranteed to be a syntactically valid name, but usually more helpful than the explicit version
return mkNode ``Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!"`{n}"]
@[builtin_delab app.Lean.Name.num]
def delabNameMkNum : Delab := delabNameMkStr
end Lean.PrettyPrinter.Delaborator
|
51682487c8654972ff18dde8c130d84a47ad8fe9 | 49bd2218ae088932d847f9030c8dbff1c5607bb7 | /src/data/finsupp.lean | c0918452b2d3d6462a0bb9166b5f0d6a9306ba26 | [
"Apache-2.0"
] | permissive | FredericLeRoux/mathlib | e8f696421dd3e4edc8c7edb3369421c8463d7bac | 3645bf8fb426757e0a20af110d1fdded281d286e | refs/heads/master | 1,607,062,870,732 | 1,578,513,186,000 | 1,578,513,186,000 | 231,653,181 | 0 | 0 | Apache-2.0 | 1,578,080,327,000 | 1,578,080,326,000 | null | UTF-8 | Lean | false | false | 61,675 | 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
Type of functions with finite support.
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 advice is to not use α →₀ β directly, as the type class setup might not be fitting.
The best is to define a copy and select the instances best suited.
-/
import data.finset data.set.finite algebra.big_operators algebra.module
noncomputable theory
open_locale classical
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
section basic
variable [has_zero β]
instance : has_coe_to_fun (α →₀ β) := ⟨λ_, α → β, finsupp.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.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 _))
def equiv_fun_on_fintype [fintype α] : (α →₀ β) ≃ (α → β) :=
⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp),
begin intro f, ext a, refl end,
begin intro f, ext a, refl end⟩
end basic
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 finset.singleton 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 [finsupp.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_right_inj (h : b ≠ 0) :
single a b = single a' b ↔ a = a' :=
⟨λ H, by simpa [h, single_eq_single_iff] 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 [finsupp.single_eq_same, finsupp.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 [single_apply]; ac_refl
lemma unique_single [unique α] (x : α →₀ β) : x = single (default α) (x (default α)) :=
by ext i; simp [unique.eq_default i]
@[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
section on_finset
variables [has_zero β]
/-- `on_finset s f hf` is the finsupp function representing `f` restricted to the set `s`.
The function needs to be 0 outside of `s`. Use this when the set needs filtered anyway, otherwise
often better set representation is 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
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 :=
finsupp.ext $ λ a, by simp [hf]
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) :=
finsupp.ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf]
end map_range
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 [h],
rw [← finsupp.not_mem_support_iff, not_not],
apply finset.choose_mem },
{ simp [h] } }
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 (finsupp.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, finsupp.ext $ λ a, by simpa [emb_domain_apply] using finsupp.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 = finsupp.single a b) :
∃ x, l = finsupp.single x b ∧ f x = a :=
begin
have h_map_support : finset.map f (l.support) = finset.singleton a,
by rw [←finsupp.support_emb_domain, h, finsupp.support_single_ne_zero hb]; refl,
have ha : a ∈ finset.map f (l.support),
by simp [h_map_support],
rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩,
use c,
split,
{ ext d,
rw [← finsupp.emb_domain_apply f l, h],
by_cases h_cases : c = d,
{ simp [h_cases.symm, hc₂] },
{ rw [finsupp.single_apply, finsupp.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
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 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
section erase
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
end erase
-- [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 : α → β → γ) : γ :=
f.support.sum (λa, 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 : α → β → γ) : γ :=
f.support.prod (λa, g a (f a))
@[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
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
end nat_sub
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, insert_empty_eq_singleton,
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 _ }
instance (a : α) : is_add_monoid_hom (λ g : α →₀ β, g a) :=
{ map_add := λ _ _, add_apply, map_zero := zero_apply }
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)]
@[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₂ :=
finsupp.ext $ λ a, by simp [hf']
end add_monoid
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 (s.sum f) = s.sum (λb, 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₂) :=
(f.support.sum_hom (λf : α →₀ β, f a₂)).symm
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} : finset α).sum (λa', ite (a' = a) (f a') 0),
begin
intro a,
by_cases h : a ∈ f.support,
{ have : (finset.singleton 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 (f.support.sum (λa, (0 : β))),
{ refine (finset.sum_congr rfl $ λ a' ha', if_neg _),
rintro rfl, exact h ha' },
{ rw [sum_const_zero, insert_empty_eq_singleton, sum_singleton,
if_pos rfl, not_mem_support_iff.1 h] } }
end,
ext $ assume a, by simp only [sum_apply, single_apply, this,
insert_empty_eq_singleton, 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 : (f.support ∪ g.support).prod (λa, 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 : (f.support ∪ g.support).prod (λa, 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 (f + g).support.prod (λa, h a ((f + g) a)) =
(f.support ∪ g.support).prod (λa, h a ((f + g) a)) :
finset.prod_subset support_add $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]
... = (f.support ∪ g.support).prod (λa, h a (f a)) *
(f.support ∪ g.support).prod (λa, 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₂) :
s.prod (λi, (g i).prod h) = (s.sum g).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 (s.sum g) = s.sum (λx, 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
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 (s.sum v) = s.sum (λi, 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 (function.embedding.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
section comap_domain
noncomputable def comap_domain {α₁ α₂ γ : Type*} [has_zero γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) : α₁ →₀ γ :=
{ 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 }
lemma comap_domain_apply {α₁ α₂ γ : Type*} [has_zero γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) (a : α₁) :
comap_domain f l hf a = l (f a) :=
begin
unfold_coes,
unfold comap_domain,
simp,
refl
end
lemma sum_comap_domain {α₁ α₂ β γ : Type*} [has_zero β] [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ β) (g : α₂ → β → γ) (hf : set.bij_on f (f ⁻¹' l.support.to_set) l.support.to_set):
(comap_domain f l (set.inj_on_of_bij_on hf)).sum (g ∘ f) = l.sum g :=
begin
unfold sum,
haveI := classical.dec_eq α₂,
simp only [comap_domain, comap_domain_apply, 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.to_set) l.support.to_set) :
comap_domain f l (set.inj_on_of_bij_on hf) = 0 → l = 0 :=
begin
rw [← support_eq_empty, ← support_eq_empty, comap_domain],
simp only [finset.ext, 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 (set.inj_on_of_injective _ hf)) = l :=
begin
ext a,
haveI := classical.dec (a ∈ set.range f),
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
/-- The product of `f g : α →₀ β` is the finitely supported function
whose value at `a` is the sum of `f x * g y` over all pairs `x, y`
such that `x + y = a`. (Think of the product of multivariate
polynomials where `α` is the monoid of monomial exponents.) -/
instance [has_add α] [semiring β] : has_mul (α →₀ β) :=
⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩
lemma mul_def [has_add α] [semiring β] {f g : α →₀ β} :
f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl
lemma support_mul [has_add α] [semiring β] (a b : α →₀ β) :
(a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ + a₂}) :=
subset.trans support_sum $ bind_mono $ assume a₁ _,
subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset
/-- The unit of the multiplication is `single 0 1`, i.e. the function
that is 1 at 0 and zero elsewhere. -/
instance [has_zero α] [has_zero β] [has_one β] : has_one (α →₀ β) :=
⟨single 0 1⟩
lemma one_def [has_zero α] [has_zero β] [has_one β] : 1 = (single 0 1 : α →₀ β) := rfl
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.mpr $ 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 :=
finsupp.ext $ λ x, begin
by_cases h' : p x; simp [h'],
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 :=
finsupp.ext $ λ x, begin
by_cases h' : p x; simp [h'],
rw single_eq_of_ne, rintro rfl, exact h h'
end
end has_zero
lemma filter_pos_add_filter_neg [add_monoid β] (f : α →₀ β) (p : α → Prop) :
f.filter p + f.filter (λa, ¬ p a) = f :=
finsupp.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
section frange
variables [has_zero β]
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
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, by by_cases p a; simp [h]
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 : γ → α →₀ β} :
(s.sum h).subtype_domain p = s.sum (λc, (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 : γ → α →₀ β) :
(s.sum f).filter p = s.sum (λa, 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
section multiset
def to_multiset (f : α →₀ ℕ) : multiset α :=
f.sum (λa n, add_monoid.smul 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, add_monoid.zero_smul _) (assume a b₁ b₂, add_monoid.add_smul _ _ _)
lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = add_monoid.smul n {a} :=
by rw [to_multiset, sum_single_index]; apply add_monoid.zero_smul
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_smul (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_smul _ _ hn,
multiset.singleton_eq_singleton, multiset.to_finset_cons, multiset.to_finset_zero],
refl,
refine disjoint_mono support_single_subset (subset.refl _) _,
rwa [finset.singleton_eq_singleton, 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, (add_monoid.smul 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]
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
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 ∈ (s.sum h).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
section curry_uncurry
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
protected def uncurry [add_comm_monoid γ] (f : α →₀ (β →₀ γ)) : (α × β) →₀ γ :=
f.sum $ λa g, g.sum $ λb c, single (a, b) c
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 [add_monoid α] [semiring β]
-- TODO: the simplifier unfolds 0 in the instance proof!
private lemma zero_mul (f : α →₀ β) : 0 * f = 0 := by simp only [mul_def, sum_zero_index]
private lemma mul_zero (f : α →₀ β) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero]
private lemma left_distrib (a b c : α →₀ β) : a * (b + c) = a * b + a * c :=
by simp only [mul_def, sum_add_index, mul_add, _root_.mul_zero, single_zero, single_add,
eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add]
private lemma right_distrib (a b c : α →₀ β) : (a + b) * c = a * c + b * c :=
by simp only [mul_def, sum_add_index, add_mul, _root_.mul_zero, _root_.zero_mul, single_zero, single_add,
eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add]
instance : semiring (α →₀ β) :=
{ one := 1,
mul := (*),
one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.zero_mul, single_zero, sum_zero,
zero_add, one_mul, sum_single],
mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.mul_zero, single_zero, sum_zero,
add_zero, mul_one, sum_single],
zero_mul := zero_mul,
mul_zero := mul_zero,
mul_assoc := assume f g h, by simp only [mul_def, 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,
add_mul, mul_add, add_assoc, mul_assoc, _root_.zero_mul, _root_.mul_zero, sum_zero, sum_add],
left_distrib := left_distrib,
right_distrib := right_distrib,
.. finsupp.add_comm_monoid }
end
instance [add_comm_monoid α] [comm_semiring β] : comm_semiring (α →₀ β) :=
{ mul_comm := assume f g,
begin
simp only [mul_def, finsupp.sum, mul_comm],
rw [finset.sum_comm],
simp only [add_comm]
end,
.. finsupp.semiring }
instance [add_monoid α] [ring β] : ring (α →₀ β) :=
{ neg := has_neg.neg,
add_left_neg := add_left_neg,
.. finsupp.semiring }
instance [add_comm_monoid α] [comm_ring β] : comm_ring (α →₀ β) :=
{ mul_comm := mul_comm, .. finsupp.ring}
lemma single_mul_single [has_add α] [semiring β] {a₁ a₂ : α} {b₁ b₂ : β}:
single a₁ b₁ * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) :=
(sum_single_index (by simp only [_root_.zero_mul, single_zero, sum_zero])).trans
(sum_single_index (by rw [_root_.mul_zero, single_zero]))
lemma prod_single [add_comm_monoid α] [comm_semiring β]
{s : finset ι} {a : ι → α} {b : ι → β} :
s.prod (λi, single (a i) (b i)) = single (s.sum a) (s.prod b) :=
finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih,
single_mul_single, sum_insert has, prod_insert has]
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, finsupp.ext $ λ _, smul_add _ _ _,
add_smul := λ a x y, finsupp.ext $ λ _, add_smul _ _ _,
one_smul := λ x, finsupp.ext $ λ _, one_smul _ _,
mul_smul := λ r s x, finsupp.ext $ λ _, mul_smul _ _ _,
zero_smul := λ x, finsupp.ext $ λ _, zero_smul _ _,
smul_zero := λ x, finsupp.ext $ λ _, smul_zero _ }
instance [ring γ] [add_comm_group β] [module γ β] : module γ (α →₀ β) :=
{ ..finsupp.semimodule α β }
instance [discrete_field γ] [add_comm_group β] [vector_space γ β] : vector_space γ (α →₀ β) :=
{ ..finsupp.module α β }
variables {α β}
lemma support_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {g : α →₀ β} :
(b • g).support ⊆ g.support :=
λ a, by simp; 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, by by_cases p a; simp [h]
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},
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}, simp [h]]
end
@[simp] lemma smul_apply [ring β] {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 [eq_zero_of_zero_eq_one β zero_eq_one (l i)]
end
def restrict_support_equiv [add_comm_monoid β] (s : set α) :
{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
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⟩
section sigma
variables {αs : ι → Type*} [has_zero β] (l : (Σ i, αs i) →₀ β)
noncomputable 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
def split_support : finset ι := finset.image (sigma.fst) l.support
lemma mem_split_support_iff_nonzero (i : ι) :
i ∈ split_support l ↔ split l i ≠ 0 :=
begin
classical,
rw [split_support, mem_image, ne.def, ← support_eq_empty,
← exists_mem_iff_ne_empty, split, comap_domain],
simp
end
noncomputable 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,
haveI := classical.dec,
rwa not_iff_not,
exact hg _ _,
end }
lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) :=
by simp [finset.ext, split_support, split, comap_domain]; tauto
lemma sigma_sum [add_comm_monoid γ] (f : (Σ (i : ι), αs i) → β → γ) :
l.sum f = (split_support l).sum (λ (i : ι), (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b)) :=
by simp [sum, sigma_support, sum_sigma,split_apply]
end sigma
end finsupp
namespace multiset
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 simp [finsupp.single_apply, h] 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
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, finsupp.ext $ λ s, le_antisymm (hfg s) (hgf s),
.. finsupp.preorder }
instance [ordered_cancel_comm_monoid α] :
add_left_cancel_semigroup (σ →₀ α) :=
{ add_left_cancel := λ a b c h, finsupp.ext $ λ s,
by { rw finsupp.ext_iff at h, exact add_left_cancel (h s) },
.. finsupp.add_monoid }
instance [ordered_cancel_comm_monoid α] :
add_right_cancel_semigroup (σ →₀ α) :=
{ add_right_cancel := λ a b c h, finsupp.ext $ λ s,
by { rw finsupp.ext_iff at h, exact add_right_cancel (h s) },
.. finsupp.add_monoid }
instance [ordered_cancel_comm_monoid α] :
ordered_cancel_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_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)⟩
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 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 {σ}
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 using congr_arg multiset.to_finsupp h },
{ intro h,
refine ⟨⟨p.1.to_multiset, p.2.to_multiset⟩, _, _⟩,
{ simpa 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 [mem_antidiagonal_support, add_comm] using hf
end finsupp
|
45e756cbb978c37f8564f740ca27c010fb71f6c8 | 2fbe653e4bc441efde5e5d250566e65538709888 | /src/data/subtype.lean | 37d3289d0667dca7a5e34cee8c59060cdaa36102 | [
"Apache-2.0"
] | permissive | aceg00/mathlib | 5e15e79a8af87ff7eb8c17e2629c442ef24e746b | 8786ea6d6d46d6969ac9a869eb818bf100802882 | refs/heads/master | 1,649,202,698,930 | 1,580,924,783,000 | 1,580,924,783,000 | 149,197,272 | 0 | 0 | Apache-2.0 | 1,537,224,208,000 | 1,537,224,207,000 | null | UTF-8 | Lean | false | false | 4,570 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
-/
-- Lean complains if this section is turned into a namespace
open function
section subtype
variables {α : Sort*} {p : α → Prop}
@[simp] theorem subtype.forall {q : {a // p a} → Prop} :
(∀ x, q x) ↔ (∀ a b, q ⟨a, b⟩) :=
⟨assume h a b, h ⟨a, b⟩, assume h ⟨a, b⟩, h a b⟩
/-- An alternative version of `subtype.forall`. This one is useful if Lean cannot figure out `q`
when using `subtype.forall` from right to left. -/
theorem subtype.forall' {q : ∀x, p x → Prop} :
(∀ x h, q x h) ↔ (∀ x : {a // p a}, q x.1 x.2) :=
(@subtype.forall _ _ (λ x, q x.1 x.2)).symm
@[simp] theorem subtype.exists {q : {a // p a} → Prop} :
(∃ x, q x) ↔ (∃ a b, q ⟨a, b⟩) :=
⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩
end subtype
namespace subtype
variables {α : Sort*} {β : Sort*} {γ : Sort*} {p : α → Prop}
protected lemma eq' : ∀ {a1 a2 : {x // p x}}, a1.val = a2.val → a1 = a2
| ⟨x, h1⟩ ⟨.(x), h2⟩ rfl := rfl
lemma ext {a1 a2 : {x // p x}} : a1 = a2 ↔ a1.val = a2.val :=
⟨congr_arg _, subtype.eq'⟩
lemma coe_ext {a1 a2 : {x // p x}} : a1 = a2 ↔ (a1 : α) = a2 :=
ext
theorem val_injective : injective (@val _ p) :=
λ a b, subtype.eq'
/- Restrict a (dependent) function to a subtype -/
def restrict {α} {β : α → Type*} (f : Πx, β x) (p : α → Prop) (x : subtype p) : β x.1 :=
f x.1
lemma restrict_apply {α} {β : α → Type*} (f : Πx, β x) (p : α → Prop) (x : subtype p) :
restrict f p x = f x.1 :=
by refl
lemma restrict_def {α β} (f : α → β) (p : α → Prop) : restrict f p = f ∘ subtype.val :=
by refl
lemma restrict_injective {α β} {f : α → β} (p : α → Prop) (h : injective f) :
injective (restrict f p) :=
injective_comp h subtype.val_injective
/-- Defining a map into a subtype, this can be seen as an "coinduction principle" of `subtype`-/
def coind {α β} (f : α → β) {p : β → Prop} (h : ∀a, p (f a)) : α → subtype p :=
λ a, ⟨f a, h a⟩
theorem coind_injective {α β} {f : α → β} {p : β → Prop} (h : ∀a, p (f a))
(hf : injective f) : injective (coind f h) :=
λ x y hxy, hf $ by apply congr_arg subtype.val hxy
/-- Restriction of a function to a function on subtypes. -/
def map {p : α → Prop} {q : β → Prop} (f : α → β) (h : ∀a, p a → q (f a)) :
subtype p → subtype q :=
λ x, ⟨f x.1, h x.1 x.2⟩
theorem map_comp {p : α → Prop} {q : β → Prop} {r : γ → Prop} {x : subtype p}
(f : α → β) (h : ∀a, p a → q (f a)) (g : β → γ) (l : ∀a, q a → r (g a)) :
map g l (map f h x) = map (g ∘ f) (assume a ha, l (f a) $ h a ha) x :=
rfl
theorem map_id {p : α → Prop} {h : ∀a, p a → p (id a)} : map (@id α) h = id :=
funext $ assume ⟨v, h⟩, rfl
lemma map_injective {p : α → Prop} {q : β → Prop} {f : α → β} (h : ∀a, p a → q (f a))
(hf : injective f) : injective (map f h) :=
coind_injective _ $ injective_comp hf val_injective
instance [has_equiv α] (p : α → Prop) : has_equiv (subtype p) :=
⟨λ s t, s.val ≈ t.val⟩
theorem equiv_iff [has_equiv α] {p : α → Prop} {s t : subtype p} :
s ≈ t ↔ s.val ≈ t.val :=
iff.rfl
variables [setoid α]
protected theorem refl (s : subtype p) : s ≈ s :=
setoid.refl s.val
protected theorem symm {s t : subtype p} (h : s ≈ t) : t ≈ s :=
setoid.symm h
protected theorem trans {s t u : subtype p} (h₁ : s ≈ t) (h₂ : t ≈ u) : s ≈ u :=
setoid.trans h₁ h₂
theorem equivalence (p : α → Prop) : equivalence (@has_equiv.equiv (subtype p) _) :=
mk_equivalence _ subtype.refl (@subtype.symm _ p _) (@subtype.trans _ p _)
instance (p : α → Prop) : setoid (subtype p) :=
setoid.mk (≈) (equivalence p)
end subtype
namespace subtype
variables {α : Type*} {β : Type*} {γ : Type*} {p : α → Prop}
@[simp] theorem coe_eta {α : Type*} {p : α → Prop}
(a : {a // p a}) (h : p a) : mk ↑a h = a := eta _ _
@[simp] theorem coe_mk {α : Type*} {p : α → Prop}
(a h) : (@mk α p a h : α) = a := rfl
@[simp] theorem mk_eq_mk {α : Type*} {p : α → Prop}
{a h a' h'} : @mk α p a h = @mk α p a' h' ↔ a = a' :=
⟨λ H, by injection H, λ H, by congr; assumption⟩
@[simp] lemma val_prop {S : set α} (a : {a // a ∈ S}) : a.val ∈ S := a.property
@[simp] lemma val_prop' {S : set α} (a : {a // a ∈ S}) : ↑a ∈ S := a.property
end subtype
|
a9a94199d7648a0f1e829bc54ee3dab42a9b9c1b | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/openScoped.lean | 9b8e02ef984e8aaf5b4fe1d840038cffda062378 | [
"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 | 409 | lean | #check epsilon -- Error
noncomputable def foo1 (f g : Nat → Nat) : Nat :=
if f = g then 1 else 2 -- Error
section
open Classical
#check epsilon
noncomputable def foo2 (f g : Nat → Nat) : Nat :=
if f = g then 1 else 2 -- Ok
end
#check epsilon -- Error
section
open scoped Classical
#check epsilon -- Error
noncomputable def foo3 (f g : Nat → Nat) : Nat :=
if f = g then 1 else 2 -- Ok
end
|
aea23d99378b0ad09ad0defebe3bc8437c5a0bb2 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/algebra/group/hom.lean | f094b7f71a111057556887f42fc3ffec88e5b13f | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 37,003 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes,
Johannes Hölzl, Yury Kudryashov
-/
import algebra.group.commute
import algebra.group_with_zero.defs
/-!
# monoid and group homomorphisms
This file defines the bundled structures for monoid and group homomorphisms. Namely, we define
`monoid_hom` (resp., `add_monoid_hom`) to be bundled homomorphisms between multiplicative (resp.,
additive) monoids or groups.
We also define coercion to a function, and usual operations: composition, identity homomorphism,
pointwise multiplication and pointwise inversion.
This file also defines the lesser-used (and notation-less) homomorphism types which are used as
building blocks for other homomorphisms:
* `zero_hom`
* `one_hom`
* `add_hom`
* `mul_hom`
* `monoid_with_zero_hom`
## Notations
* `→*` for bundled monoid homs (also use for group homs)
* `→+` for bundled add_monoid homs (also use for add_group 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 `group_hom` -- the idea is that `monoid_hom` is used.
The constructor for `monoid_hom` needs a proof of `map_one` as well
as `map_mul`; a separate constructor `monoid_hom.mk'` will construct
group homs (i.e. monoid homs between groups) given only a proof
that multiplication is preserved,
Implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the
instances can be inferred because they are implicit arguments to the type `monoid_hom`. When they
can be inferred from the type it is faster to use this method than to use type class inference.
Historically this file also included definitions of unbundled homomorphism classes; they were
deprecated and moved to `deprecated/group`.
## Tags
monoid_hom, add_monoid_hom
-/
variables {M : Type*} {N : Type*} {P : Type*} -- monoids
{G : Type*} {H : Type*} -- groups
-- for easy multiple inheritance
set_option old_structure_cmd true
/-- Homomorphism that preserves zero -/
structure zero_hom (M : Type*) (N : Type*) [has_zero M] [has_zero N] :=
(to_fun : M → N)
(map_zero' : to_fun 0 = 0)
/-- Homomorphism that preserves addition -/
structure add_hom (M : Type*) (N : Type*) [has_add M] [has_add N] :=
(to_fun : M → N)
(map_add' : ∀ x y, to_fun (x + y) = to_fun x + to_fun y)
/-- Bundled add_monoid homomorphisms; use this for bundled add_group homomorphisms too. -/
@[ancestor zero_hom add_hom]
structure add_monoid_hom (M : Type*) (N : Type*) [add_zero_class M] [add_zero_class N]
extends zero_hom M N, add_hom M N
attribute [nolint doc_blame] add_monoid_hom.to_add_hom
attribute [nolint doc_blame] add_monoid_hom.to_zero_hom
infixr ` →+ `:25 := add_monoid_hom
/-- Homomorphism that preserves one -/
@[to_additive]
structure one_hom (M : Type*) (N : Type*) [has_one M] [has_one N] :=
(to_fun : M → N)
(map_one' : to_fun 1 = 1)
/-- Homomorphism that preserves multiplication -/
@[to_additive]
structure mul_hom (M : Type*) (N : Type*) [has_mul M] [has_mul N] :=
(to_fun : M → N)
(map_mul' : ∀ x y, to_fun (x * y) = to_fun x * to_fun y)
/-- Bundled monoid homomorphisms; use this for bundled group homomorphisms too. -/
@[ancestor one_hom mul_hom, to_additive]
structure monoid_hom (M : Type*) (N : Type*) [mul_one_class M] [mul_one_class N]
extends one_hom M N, mul_hom M N
/-- Bundled monoid with zero homomorphisms; use this for bundled group with zero homomorphisms
too. -/
@[ancestor zero_hom monoid_hom]
structure monoid_with_zero_hom (M : Type*) (N : Type*) [mul_zero_one_class M] [mul_zero_one_class N]
extends zero_hom M N, monoid_hom M N
attribute [nolint doc_blame] monoid_hom.to_mul_hom
attribute [nolint doc_blame] monoid_hom.to_one_hom
attribute [nolint doc_blame] monoid_with_zero_hom.to_monoid_hom
attribute [nolint doc_blame] monoid_with_zero_hom.to_zero_hom
infixr ` →* `:25 := monoid_hom
-- completely uninteresting lemmas about coercion to function, that all homs need
section coes
/-! Bundled morphisms can be down-cast to weaker bundlings -/
@[to_additive]
instance monoid_hom.has_coe_to_one_hom {mM : mul_one_class M} {mN : mul_one_class N} :
has_coe (M →* N) (one_hom M N) := ⟨monoid_hom.to_one_hom⟩
@[to_additive]
instance monoid_hom.has_coe_to_mul_hom {mM : mul_one_class M} {mN : mul_one_class N} :
has_coe (M →* N) (mul_hom M N) := ⟨monoid_hom.to_mul_hom⟩
instance monoid_with_zero_hom.has_coe_to_monoid_hom
{mM : mul_zero_one_class M} {mN : mul_zero_one_class N} :
has_coe (monoid_with_zero_hom M N) (M →* N) := ⟨monoid_with_zero_hom.to_monoid_hom⟩
instance monoid_with_zero_hom.has_coe_to_zero_hom
{mM : mul_zero_one_class M} {mN : mul_zero_one_class N} :
has_coe (monoid_with_zero_hom M N) (zero_hom M N) := ⟨monoid_with_zero_hom.to_zero_hom⟩
/-! The simp-normal form of morphism coercion is `f.to_..._hom`. This choice is primarily because
this is the way things were before the above coercions were introduced. Bundled morphisms defined
elsewhere in Mathlib may choose `↑f` as their simp-normal form instead. -/
@[simp, to_additive]
lemma monoid_hom.coe_eq_to_one_hom {mM : mul_one_class M} {mN : mul_one_class N} (f : M →* N) :
(f : one_hom M N) = f.to_one_hom := rfl
@[simp, to_additive]
lemma monoid_hom.coe_eq_to_mul_hom {mM : mul_one_class M} {mN : mul_one_class N} (f : M →* N) :
(f : mul_hom M N) = f.to_mul_hom := rfl
@[simp]
lemma monoid_with_zero_hom.coe_eq_to_monoid_hom
{mM : mul_zero_one_class M} {mN : mul_zero_one_class N} (f : monoid_with_zero_hom M N) :
(f : M →* N) = f.to_monoid_hom := rfl
@[simp]
lemma monoid_with_zero_hom.coe_eq_to_zero_hom
{mM : mul_zero_one_class M} {mN : mul_zero_one_class N} (f : monoid_with_zero_hom M N) :
(f : zero_hom M N) = f.to_zero_hom := rfl
@[to_additive]
instance {mM : has_one M} {mN : has_one N} : has_coe_to_fun (one_hom M N) (λ _, M → N) :=
⟨one_hom.to_fun⟩
@[to_additive]
instance {mM : has_mul M} {mN : has_mul N} : has_coe_to_fun (mul_hom M N) (λ _, M → N) :=
⟨mul_hom.to_fun⟩
@[to_additive]
instance {mM : mul_one_class M} {mN : mul_one_class N} : has_coe_to_fun (M →* N) (λ _, M → N) :=
⟨monoid_hom.to_fun⟩
instance {mM : mul_zero_one_class M} {mN : mul_zero_one_class N} :
has_coe_to_fun (monoid_with_zero_hom M N) (λ _, M → N) :=
⟨monoid_with_zero_hom.to_fun⟩
-- these must come after the coe_to_fun definitions
initialize_simps_projections zero_hom (to_fun → apply)
initialize_simps_projections add_hom (to_fun → apply)
initialize_simps_projections add_monoid_hom (to_fun → apply)
initialize_simps_projections one_hom (to_fun → apply)
initialize_simps_projections mul_hom (to_fun → apply)
initialize_simps_projections monoid_hom (to_fun → apply)
initialize_simps_projections monoid_with_zero_hom (to_fun → apply)
@[simp, to_additive]
lemma one_hom.to_fun_eq_coe [has_one M] [has_one N] (f : one_hom M N) : f.to_fun = f := rfl
@[simp, to_additive]
lemma mul_hom.to_fun_eq_coe [has_mul M] [has_mul N] (f : mul_hom M N) : f.to_fun = f := rfl
@[simp, to_additive]
lemma monoid_hom.to_fun_eq_coe [mul_one_class M] [mul_one_class N]
(f : M →* N) : f.to_fun = f := rfl
@[simp]
lemma monoid_with_zero_hom.to_fun_eq_coe [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) : f.to_fun = f := rfl
@[simp, to_additive]
lemma one_hom.coe_mk [has_one M] [has_one N]
(f : M → N) (h1) : ⇑(one_hom.mk f h1) = f := rfl
@[simp, to_additive]
lemma mul_hom.coe_mk [has_mul M] [has_mul N]
(f : M → N) (hmul) : ⇑(mul_hom.mk f hmul) = f := rfl
@[simp, to_additive]
lemma monoid_hom.coe_mk [mul_one_class M] [mul_one_class N]
(f : M → N) (h1 hmul) : ⇑(monoid_hom.mk f h1 hmul) = f := rfl
@[simp]
lemma monoid_with_zero_hom.coe_mk [mul_zero_one_class M] [mul_zero_one_class N]
(f : M → N) (h0 h1 hmul) : ⇑(monoid_with_zero_hom.mk f h0 h1 hmul) = f := rfl
@[simp, to_additive]
lemma monoid_hom.to_one_hom_coe [mul_one_class M] [mul_one_class N] (f : M →* N) :
(f.to_one_hom : M → N) = f := rfl
@[simp, to_additive]
lemma monoid_hom.to_mul_hom_coe [mul_one_class M] [mul_one_class N] (f : M →* N) :
(f.to_mul_hom : M → N) = f := rfl
@[simp]
lemma monoid_with_zero_hom.to_zero_hom_coe [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) :
(f.to_zero_hom : M → N) = f := rfl
@[simp]
lemma monoid_with_zero_hom.to_monoid_hom_coe [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) :
(f.to_monoid_hom : M → N) = f := rfl
@[to_additive]
theorem one_hom.congr_fun [has_one M] [has_one N]
{f g : one_hom M N} (h : f = g) (x : M) : f x = g x :=
congr_arg (λ h : one_hom M N, h x) h
@[to_additive]
theorem mul_hom.congr_fun [has_mul M] [has_mul N]
{f g : mul_hom M N} (h : f = g) (x : M) : f x = g x :=
congr_arg (λ h : mul_hom M N, h x) h
@[to_additive]
theorem monoid_hom.congr_fun [mul_one_class M] [mul_one_class N]
{f g : M →* N} (h : f = g) (x : M) : f x = g x :=
congr_arg (λ h : M →* N, h x) h
theorem monoid_with_zero_hom.congr_fun [mul_zero_one_class M] [mul_zero_one_class N]
{f g : monoid_with_zero_hom M N} (h : f = g) (x : M) : f x = g x :=
congr_arg (λ h : monoid_with_zero_hom M N, h x) h
@[to_additive]
theorem one_hom.congr_arg [has_one M] [has_one N]
(f : one_hom M N) {x y : M} (h : x = y) : f x = f y :=
congr_arg (λ x : M, f x) h
@[to_additive]
theorem mul_hom.congr_arg [has_mul M] [has_mul N]
(f : mul_hom M N) {x y : M} (h : x = y) : f x = f y :=
congr_arg (λ x : M, f x) h
@[to_additive]
theorem monoid_hom.congr_arg [mul_one_class M] [mul_one_class N]
(f : M →* N) {x y : M} (h : x = y) : f x = f y :=
congr_arg (λ x : M, f x) h
theorem monoid_with_zero_hom.congr_arg [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) {x y : M} (h : x = y) : f x = f y :=
congr_arg (λ x : M, f x) h
@[to_additive]
lemma one_hom.coe_inj [has_one M] [has_one N] ⦃f g : one_hom M N⦄ (h : (f : M → N) = g) : f = g :=
by cases f; cases g; cases h; refl
@[to_additive]
lemma mul_hom.coe_inj [has_mul M] [has_mul N] ⦃f g : mul_hom M N⦄ (h : (f : M → N) = g) : f = g :=
by cases f; cases g; cases h; refl
@[to_additive]
lemma monoid_hom.coe_inj [mul_one_class M] [mul_one_class N]
⦃f g : M →* N⦄ (h : (f : M → N) = g) : f = g :=
by cases f; cases g; cases h; refl
lemma monoid_with_zero_hom.coe_inj [mul_zero_one_class M] [mul_zero_one_class N]
⦃f g : monoid_with_zero_hom M N⦄ (h : (f : M → N) = g) : f = g :=
by cases f; cases g; cases h; refl
@[ext, to_additive]
lemma one_hom.ext [has_one M] [has_one N] ⦃f g : one_hom M N⦄ (h : ∀ x, f x = g x) : f = g :=
one_hom.coe_inj (funext h)
@[ext, to_additive]
lemma mul_hom.ext [has_mul M] [has_mul N] ⦃f g : mul_hom M N⦄ (h : ∀ x, f x = g x) : f = g :=
mul_hom.coe_inj (funext h)
@[ext, to_additive]
lemma monoid_hom.ext [mul_one_class M] [mul_one_class N]
⦃f g : M →* N⦄ (h : ∀ x, f x = g x) : f = g :=
monoid_hom.coe_inj (funext h)
@[ext]
lemma monoid_with_zero_hom.ext [mul_zero_one_class M] [mul_zero_one_class N]
⦃f g : monoid_with_zero_hom M N⦄ (h : ∀ x, f x = g x) : f = g :=
monoid_with_zero_hom.coe_inj (funext h)
@[to_additive]
lemma one_hom.ext_iff [has_one M] [has_one N] {f g : one_hom M N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, one_hom.ext h⟩
@[to_additive]
lemma mul_hom.ext_iff [has_mul M] [has_mul N] {f g : mul_hom M N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, mul_hom.ext h⟩
@[to_additive]
lemma monoid_hom.ext_iff [mul_one_class M] [mul_one_class N]
{f g : M →* N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, monoid_hom.ext h⟩
lemma monoid_with_zero_hom.ext_iff [mul_zero_one_class M] [mul_zero_one_class N]
{f g : monoid_with_zero_hom M N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, monoid_with_zero_hom.ext h⟩
@[simp, to_additive]
lemma one_hom.mk_coe [has_one M] [has_one N]
(f : one_hom M N) (h1) : one_hom.mk f h1 = f :=
one_hom.ext $ λ _, rfl
@[simp, to_additive]
lemma mul_hom.mk_coe [has_mul M] [has_mul N]
(f : mul_hom M N) (hmul) : mul_hom.mk f hmul = f :=
mul_hom.ext $ λ _, rfl
@[simp, to_additive]
lemma monoid_hom.mk_coe [mul_one_class M] [mul_one_class N]
(f : M →* N) (h1 hmul) : monoid_hom.mk f h1 hmul = f :=
monoid_hom.ext $ λ _, rfl
@[simp]
lemma monoid_with_zero_hom.mk_coe [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) (h0 h1 hmul) : monoid_with_zero_hom.mk f h0 h1 hmul = f :=
monoid_with_zero_hom.ext $ λ _, rfl
end coes
@[simp, to_additive]
lemma one_hom.map_one [has_one M] [has_one N] (f : one_hom M N) : f 1 = 1 := f.map_one'
/-- If `f` is a monoid homomorphism then `f 1 = 1`. -/
@[simp, to_additive]
lemma monoid_hom.map_one [mul_one_class M] [mul_one_class N] (f : M →* N) : f 1 = 1 := f.map_one'
@[simp]
lemma monoid_with_zero_hom.map_one [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) : f 1 = 1 := f.map_one'
/-- If `f` is an additive monoid homomorphism then `f 0 = 0`. -/
add_decl_doc add_monoid_hom.map_zero
@[simp]
lemma monoid_with_zero_hom.map_zero [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) : f 0 = 0 := f.map_zero'
@[simp, to_additive]
lemma mul_hom.map_mul [has_mul M] [has_mul N]
(f : mul_hom M N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b
/-- If `f` is a monoid homomorphism then `f (a * b) = f a * f b`. -/
@[simp, to_additive]
lemma monoid_hom.map_mul [mul_one_class M] [mul_one_class N]
(f : M →* N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b
@[simp]
lemma monoid_with_zero_hom.map_mul [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b
/-- If `f` is an additive monoid homomorphism then `f (a + b) = f a + f b`. -/
add_decl_doc add_monoid_hom.map_add
namespace monoid_hom
variables {mM : mul_one_class M} {mN : mul_one_class N} {mP : mul_one_class P}
variables [group G] [comm_group H]
include mM mN
@[to_additive]
lemma map_mul_eq_one (f : M →* N) {a b : M} (h : a * b = 1) : f a * f b = 1 :=
by rw [← f.map_mul, h, f.map_one]
/-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a right inverse,
then `f x` has a right inverse too. For elements invertible on both sides see `is_unit.map`. -/
@[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has
a right inverse, then `f x` has a right inverse too."]
lemma map_exists_right_inv (f : M →* N) {x : M} (hx : ∃ y, x * y = 1) :
∃ y, f x * y = 1 :=
let ⟨y, hy⟩ := hx in ⟨f y, f.map_mul_eq_one hy⟩
/-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a left inverse,
then `f x` has a left inverse too. For elements invertible on both sides see `is_unit.map`. -/
@[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has
a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see
`is_add_unit.map`."]
lemma map_exists_left_inv (f : M →* N) {x : M} (hx : ∃ y, y * x = 1) :
∃ y, y * f x = 1 :=
let ⟨y, hy⟩ := hx in ⟨f y, f.map_mul_eq_one hy⟩
end monoid_hom
/-- Inversion on a commutative group, considered as a monoid homomorphism. -/
@[to_additive "Inversion on a commutative additive group, considered as an additive
monoid homomorphism."]
def comm_group.inv_monoid_hom {G : Type*} [comm_group G] : G →* G :=
{ to_fun := has_inv.inv,
map_one' := one_inv,
map_mul' := mul_inv }
/-- The identity map from a type with 1 to itself. -/
@[to_additive, simps]
def one_hom.id (M : Type*) [has_one M] : one_hom M M :=
{ to_fun := λ x, x, map_one' := rfl, }
/-- The identity map from a type with multiplication to itself. -/
@[to_additive, simps]
def mul_hom.id (M : Type*) [has_mul M] : mul_hom M M :=
{ to_fun := λ x, x, map_mul' := λ _ _, rfl, }
/-- The identity map from a monoid to itself. -/
@[to_additive, simps]
def monoid_hom.id (M : Type*) [mul_one_class M] : M →* M :=
{ to_fun := λ x, x, map_one' := rfl, map_mul' := λ _ _, rfl, }
/-- The identity map from a monoid_with_zero to itself. -/
@[simps]
def monoid_with_zero_hom.id (M : Type*) [mul_zero_one_class M] : monoid_with_zero_hom M M :=
{ to_fun := λ x, x, map_zero' := rfl, map_one' := rfl, map_mul' := λ _ _, rfl, }
/-- The identity map from an type with zero to itself. -/
add_decl_doc zero_hom.id
/-- The identity map from an type with addition to itself. -/
add_decl_doc add_hom.id
/-- The identity map from an additive monoid to itself. -/
add_decl_doc add_monoid_hom.id
/-- Composition of `one_hom`s as a `one_hom`. -/
@[to_additive]
def one_hom.comp [has_one M] [has_one N] [has_one P]
(hnp : one_hom N P) (hmn : one_hom M N) : one_hom M P :=
{ to_fun := hnp ∘ hmn, map_one' := by simp, }
/-- Composition of `mul_hom`s as a `mul_hom`. -/
@[to_additive]
def mul_hom.comp [has_mul M] [has_mul N] [has_mul P]
(hnp : mul_hom N P) (hmn : mul_hom M N) : mul_hom M P :=
{ to_fun := hnp ∘ hmn, map_mul' := by simp, }
/-- Composition of monoid morphisms as a monoid morphism. -/
@[to_additive]
def monoid_hom.comp [mul_one_class M] [mul_one_class N] [mul_one_class P]
(hnp : N →* P) (hmn : M →* N) : M →* P :=
{ to_fun := hnp ∘ hmn, map_one' := by simp, map_mul' := by simp, }
/-- Composition of `monoid_with_zero_hom`s as a `monoid_with_zero_hom`. -/
def monoid_with_zero_hom.comp [mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P]
(hnp : monoid_with_zero_hom N P) (hmn : monoid_with_zero_hom M N) : monoid_with_zero_hom M P :=
{ to_fun := hnp ∘ hmn, map_zero' := by simp, map_one' := by simp, map_mul' := by simp, }
/-- Composition of `zero_hom`s as a `zero_hom`. -/
add_decl_doc zero_hom.comp
/-- Composition of `add_hom`s as a `add_hom`. -/
add_decl_doc add_hom.comp
/-- Composition of additive monoid morphisms as an additive monoid morphism. -/
add_decl_doc add_monoid_hom.comp
@[simp, to_additive] lemma one_hom.coe_comp [has_one M] [has_one N] [has_one P]
(g : one_hom N P) (f : one_hom M N) :
⇑(g.comp f) = g ∘ f := rfl
@[simp, to_additive] lemma mul_hom.coe_comp [has_mul M] [has_mul N] [has_mul P]
(g : mul_hom N P) (f : mul_hom M N) :
⇑(g.comp f) = g ∘ f := rfl
@[simp, to_additive] lemma monoid_hom.coe_comp [mul_one_class M] [mul_one_class N] [mul_one_class P]
(g : N →* P) (f : M →* N) :
⇑(g.comp f) = g ∘ f := rfl
@[simp] lemma monoid_with_zero_hom.coe_comp [mul_zero_one_class M] [mul_zero_one_class N]
[mul_zero_one_class P]
(g : monoid_with_zero_hom N P) (f : monoid_with_zero_hom M N) :
⇑(g.comp f) = g ∘ f := rfl
@[to_additive] lemma one_hom.comp_apply [has_one M] [has_one N] [has_one P]
(g : one_hom N P) (f : one_hom M N) (x : M) :
g.comp f x = g (f x) := rfl
@[to_additive] lemma mul_hom.comp_apply [has_mul M] [has_mul N] [has_mul P]
(g : mul_hom N P) (f : mul_hom M N) (x : M) :
g.comp f x = g (f x) := rfl
@[to_additive] lemma monoid_hom.comp_apply [mul_one_class M] [mul_one_class N] [mul_one_class P]
(g : N →* P) (f : M →* N) (x : M) :
g.comp f x = g (f x) := rfl
lemma monoid_with_zero_hom.comp_apply
[mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P]
(g : monoid_with_zero_hom N P) (f : monoid_with_zero_hom M N) (x : M) :
g.comp f x = g (f x) := rfl
/-- Composition of monoid homomorphisms is associative. -/
@[to_additive] lemma one_hom.comp_assoc {Q : Type*} [has_one M] [has_one N] [has_one P] [has_one Q]
(f : one_hom M N) (g : one_hom N P) (h : one_hom P Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
@[to_additive] lemma mul_hom.comp_assoc {Q : Type*} [has_mul M] [has_mul N] [has_mul P] [has_mul Q]
(f : mul_hom M N) (g : mul_hom N P) (h : mul_hom P Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
@[to_additive] lemma monoid_hom.comp_assoc {Q : Type*}
[mul_one_class M] [mul_one_class N] [mul_one_class P] [mul_one_class Q]
(f : M →* N) (g : N →* P) (h : P →* Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
lemma monoid_with_zero_hom.comp_assoc {Q : Type*}
[mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P] [mul_zero_one_class Q]
(f : monoid_with_zero_hom M N) (g : monoid_with_zero_hom N P) (h : monoid_with_zero_hom P Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
@[to_additive]
lemma one_hom.cancel_right [has_one M] [has_one N] [has_one P]
{g₁ g₂ : one_hom N P} {f : one_hom M N} (hf : function.surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, one_hom.ext $ (forall_iff_forall_surj hf).1 (one_hom.ext_iff.1 h), λ h, h ▸ rfl⟩
@[to_additive]
lemma mul_hom.cancel_right [has_mul M] [has_mul N] [has_mul P]
{g₁ g₂ : mul_hom N P} {f : mul_hom M N} (hf : function.surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, mul_hom.ext $ (forall_iff_forall_surj hf).1 (mul_hom.ext_iff.1 h), λ h, h ▸ rfl⟩
@[to_additive]
lemma monoid_hom.cancel_right
[mul_one_class M] [mul_one_class N] [mul_one_class P]
{g₁ g₂ : N →* P} {f : M →* N} (hf : function.surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, monoid_hom.ext $ (forall_iff_forall_surj hf).1 (monoid_hom.ext_iff.1 h), λ h, h ▸ rfl⟩
lemma monoid_with_zero_hom.cancel_right
[mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P]
{g₁ g₂ : monoid_with_zero_hom N P} {f : monoid_with_zero_hom M N} (hf : function.surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, monoid_with_zero_hom.ext $ (forall_iff_forall_surj hf).1 (monoid_with_zero_hom.ext_iff.1 h),
λ h, h ▸ rfl⟩
@[to_additive]
lemma one_hom.cancel_left [has_one M] [has_one N] [has_one P]
{g : one_hom N P} {f₁ f₂ : one_hom M N} (hg : function.injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, one_hom.ext $ λ x, hg $ by rw [← one_hom.comp_apply, h, one_hom.comp_apply],
λ h, h ▸ rfl⟩
@[to_additive]
lemma mul_hom.cancel_left [has_mul M] [has_mul N] [has_mul P]
{g : mul_hom N P} {f₁ f₂ : mul_hom M N} (hg : function.injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, mul_hom.ext $ λ x, hg $ by rw [← mul_hom.comp_apply, h, mul_hom.comp_apply],
λ h, h ▸ rfl⟩
@[to_additive]
lemma monoid_hom.cancel_left [mul_one_class M] [mul_one_class N] [mul_one_class P]
{g : N →* P} {f₁ f₂ : M →* N} (hg : function.injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, monoid_hom.ext $ λ x, hg $ by rw [← monoid_hom.comp_apply, h, monoid_hom.comp_apply],
λ h, h ▸ rfl⟩
lemma monoid_with_zero_hom.cancel_left
[mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P]
{g : monoid_with_zero_hom N P} {f₁ f₂ : monoid_with_zero_hom M N} (hg : function.injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, monoid_with_zero_hom.ext $ λ x, hg $ by rw [
← monoid_with_zero_hom.comp_apply, h, monoid_with_zero_hom.comp_apply],
λ h, h ▸ rfl⟩
@[to_additive]
lemma monoid_hom.to_one_hom_injective [mul_one_class M] [mul_one_class N] :
function.injective (monoid_hom.to_one_hom : (M →* N) → one_hom M N) :=
λ f g h, monoid_hom.ext $ one_hom.ext_iff.mp h
@[to_additive]
lemma monoid_hom.to_mul_hom_injective [mul_one_class M] [mul_one_class N] :
function.injective (monoid_hom.to_mul_hom : (M →* N) → mul_hom M N) :=
λ f g h, monoid_hom.ext $ mul_hom.ext_iff.mp h
lemma monoid_with_zero_hom.to_monoid_hom_injective [monoid_with_zero M] [monoid_with_zero N] :
function.injective (monoid_with_zero_hom.to_monoid_hom : monoid_with_zero_hom M N → M →* N) :=
λ f g h, monoid_with_zero_hom.ext $ monoid_hom.ext_iff.mp h
lemma monoid_with_zero_hom.to_zero_hom_injective [monoid_with_zero M] [monoid_with_zero N] :
function.injective (monoid_with_zero_hom.to_zero_hom : monoid_with_zero_hom M N → zero_hom M N) :=
λ f g h, monoid_with_zero_hom.ext $ zero_hom.ext_iff.mp h
@[simp, to_additive] lemma one_hom.comp_id [has_one M] [has_one N]
(f : one_hom M N) : f.comp (one_hom.id M) = f := one_hom.ext $ λ x, rfl
@[simp, to_additive] lemma mul_hom.comp_id [has_mul M] [has_mul N]
(f : mul_hom M N) : f.comp (mul_hom.id M) = f := mul_hom.ext $ λ x, rfl
@[simp, to_additive] lemma monoid_hom.comp_id [mul_one_class M] [mul_one_class N]
(f : M →* N) : f.comp (monoid_hom.id M) = f := monoid_hom.ext $ λ x, rfl
@[simp] lemma monoid_with_zero_hom.comp_id [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) : f.comp (monoid_with_zero_hom.id M) = f :=
monoid_with_zero_hom.ext $ λ x, rfl
@[simp, to_additive] lemma one_hom.id_comp [has_one M] [has_one N]
(f : one_hom M N) : (one_hom.id N).comp f = f := one_hom.ext $ λ x, rfl
@[simp, to_additive] lemma mul_hom.id_comp [has_mul M] [has_mul N]
(f : mul_hom M N) : (mul_hom.id N).comp f = f := mul_hom.ext $ λ x, rfl
@[simp, to_additive] lemma monoid_hom.id_comp [mul_one_class M] [mul_one_class N]
(f : M →* N) : (monoid_hom.id N).comp f = f := monoid_hom.ext $ λ x, rfl
@[simp] lemma monoid_with_zero_hom.id_comp [mul_zero_one_class M] [mul_zero_one_class N]
(f : monoid_with_zero_hom M N) : (monoid_with_zero_hom.id N).comp f = f :=
monoid_with_zero_hom.ext $ λ x, rfl
section End
namespace monoid
variables (M) [mul_one_class M]
/-- The monoid of endomorphisms. -/
protected def End := M →* M
namespace End
instance : monoid (monoid.End M) :=
{ mul := monoid_hom.comp,
one := monoid_hom.id M,
mul_assoc := λ _ _ _, monoid_hom.comp_assoc _ _ _,
mul_one := monoid_hom.comp_id,
one_mul := monoid_hom.id_comp }
instance : inhabited (monoid.End M) := ⟨1⟩
instance : has_coe_to_fun (monoid.End M) (λ _, M → M) := ⟨monoid_hom.to_fun⟩
end End
@[simp] lemma coe_one : ((1 : monoid.End M) : M → M) = id := rfl
@[simp] lemma coe_mul (f g) : ((f * g : monoid.End M) : M → M) = f ∘ g := rfl
end monoid
namespace add_monoid
variables (A : Type*) [add_zero_class A]
/-- The monoid of endomorphisms. -/
protected def End := A →+ A
namespace End
instance : monoid (add_monoid.End A) :=
{ mul := add_monoid_hom.comp,
one := add_monoid_hom.id A,
mul_assoc := λ _ _ _, add_monoid_hom.comp_assoc _ _ _,
mul_one := add_monoid_hom.comp_id,
one_mul := add_monoid_hom.id_comp }
instance : inhabited (add_monoid.End A) := ⟨1⟩
instance : has_coe_to_fun (add_monoid.End A) (λ _, A → A) := ⟨add_monoid_hom.to_fun⟩
end End
@[simp] lemma coe_one : ((1 : add_monoid.End A) : A → A) = id := rfl
@[simp] lemma coe_mul (f g) : ((f * g : add_monoid.End A) : A → A) = f ∘ g := rfl
end add_monoid
end End
/-- `1` is the homomorphism sending all elements to `1`. -/
@[to_additive]
instance [has_one M] [has_one N] : has_one (one_hom M N) := ⟨⟨λ _, 1, rfl⟩⟩
/-- `1` is the multiplicative homomorphism sending all elements to `1`. -/
@[to_additive]
instance [has_mul M] [mul_one_class N] : has_one (mul_hom M N) :=
⟨⟨λ _, 1, λ _ _, (one_mul 1).symm⟩⟩
/-- `1` is the monoid homomorphism sending all elements to `1`. -/
@[to_additive]
instance [mul_one_class M] [mul_one_class N] : has_one (M →* N) :=
⟨⟨λ _, 1, rfl, λ _ _, (one_mul 1).symm⟩⟩
/-- `0` is the homomorphism sending all elements to `0`. -/
add_decl_doc zero_hom.has_zero
/-- `0` is the additive homomorphism sending all elements to `0`. -/
add_decl_doc add_hom.has_zero
/-- `0` is the additive monoid homomorphism sending all elements to `0`. -/
add_decl_doc add_monoid_hom.has_zero
@[simp, to_additive] lemma one_hom.one_apply [has_one M] [has_one N]
(x : M) : (1 : one_hom M N) x = 1 := rfl
@[simp, to_additive] lemma monoid_hom.one_apply [mul_one_class M] [mul_one_class N]
(x : M) : (1 : M →* N) x = 1 := rfl
@[simp, to_additive] lemma one_hom.one_comp [has_one M] [has_one N] [has_one P] (f : one_hom M N) :
(1 : one_hom N P).comp f = 1 := rfl
@[simp, to_additive] lemma one_hom.comp_one [has_one M] [has_one N] [has_one P] (f : one_hom N P) :
f.comp (1 : one_hom M N) = 1 :=
by { ext, simp only [one_hom.map_one, one_hom.coe_comp, function.comp_app, one_hom.one_apply] }
@[to_additive]
instance [has_one M] [has_one N] : inhabited (one_hom M N) := ⟨1⟩
@[to_additive]
instance [has_mul M] [mul_one_class N] : inhabited (mul_hom M N) := ⟨1⟩
@[to_additive]
instance [mul_one_class M] [mul_one_class N] : inhabited (M →* N) := ⟨1⟩
-- unlike the other homs, `monoid_with_zero_hom` does not have a `1` or `0`
instance [mul_zero_one_class M] : inhabited (monoid_with_zero_hom M M) :=
⟨monoid_with_zero_hom.id M⟩
namespace monoid_hom
variables [mM : mul_one_class M] [mN : mul_one_class N] [mP : mul_one_class P]
variables [group G] [comm_group H]
/-- Given two monoid morphisms `f`, `g` to a commutative monoid, `f * g` is the monoid morphism
sending `x` to `f x * g x`. -/
@[to_additive]
instance {M N} {mM : mul_one_class M} [comm_monoid N] : has_mul (M →* N) :=
⟨λ f g,
{ to_fun := λ m, f m * g m,
map_one' := show f 1 * g 1 = 1, by simp,
map_mul' := begin intros, show f (x * y) * g (x * y) = f x * g x * (f y * g y),
rw [f.map_mul, g.map_mul, ←mul_assoc, ←mul_assoc, mul_right_comm (f x)], end }⟩
/-- Given two additive monoid morphisms `f`, `g` to an additive commutative monoid, `f + g` is the
additive monoid morphism sending `x` to `f x + g x`. -/
add_decl_doc add_monoid_hom.has_add
@[simp, to_additive] lemma mul_apply {M N} {mM : mul_one_class M} {mN : comm_monoid N}
(f g : M →* N) (x : M) :
(f * g) x = f x * g x := rfl
@[simp, to_additive] lemma one_comp [mul_one_class M] [mul_one_class N] [mul_one_class P]
(f : M →* N) : (1 : N →* P).comp f = 1 := rfl
@[simp, to_additive] lemma comp_one [mul_one_class M] [mul_one_class N] [mul_one_class P]
(f : N →* P) : f.comp (1 : M →* N) = 1 :=
by { ext, simp only [map_one, coe_comp, function.comp_app, one_apply] }
@[to_additive] lemma mul_comp [mul_one_class M] [comm_monoid N] [comm_monoid P]
(g₁ g₂ : N →* P) (f : M →* N) :
(g₁ * g₂).comp f = g₁.comp f * g₂.comp f := rfl
@[to_additive] lemma comp_mul [mul_one_class M] [comm_monoid N] [comm_monoid P]
(g : N →* P) (f₁ f₂ : M →* N) :
g.comp (f₁ * f₂) = g.comp f₁ * g.comp f₂ :=
by { ext, simp only [mul_apply, function.comp_app, map_mul, coe_comp] }
/-- If two homomorphism from a group to a monoid are equal at `x`, then they are equal at `x⁻¹`. -/
@[to_additive "If two homomorphism from an additive group to an additive monoid are equal at `x`,
then they are equal at `-x`." ]
lemma eq_on_inv {G} [group G] [monoid M] {f g : G →* M} {x : G} (h : f x = g x) :
f x⁻¹ = g x⁻¹ :=
left_inv_eq_right_inv (f.map_mul_eq_one $ inv_mul_self x) $
h.symm ▸ g.map_mul_eq_one $ mul_inv_self x
/-- Group homomorphisms preserve inverse. -/
@[simp, to_additive]
theorem map_inv {G H} [group G] [group H] (f : G →* H) (g : G) : f g⁻¹ = (f g)⁻¹ :=
eq_inv_of_mul_eq_one $ f.map_mul_eq_one $ inv_mul_self g
/-- Group homomorphisms preserve division. -/
@[simp, to_additive]
theorem map_mul_inv {G H} [group G] [group H] (f : G →* H) (g h : G) :
f (g * h⁻¹) = (f g) * (f h)⁻¹ := by rw [f.map_mul, f.map_inv]
/-- Group homomorphisms preserve division. -/
@[simp, to_additive /-" Additive group homomorphisms preserve subtraction. "-/]
theorem map_div {G H} [group G] [group H] (f : G →* H) (g h : G) : f (g / h) = (f g) / (f h) :=
by rw [div_eq_mul_inv, div_eq_mul_inv, f.map_mul_inv g h]
/-- A homomorphism from a group to a monoid is injective iff its kernel is trivial.
For the iff statement on the triviality of the kernel, see `monoid_hom.injective_iff'`. -/
@[to_additive /-" A homomorphism from an additive group to an additive monoid is injective iff
its kernel is trivial. For the iff statement on the triviality of the kernel,
see `add_monoid_hom.injective_iff'`. "-/]
lemma injective_iff {G H} [group G] [mul_one_class H] (f : G →* H) :
function.injective f ↔ (∀ a, f a = 1 → a = 1) :=
⟨λ h x hfx, h $ hfx.trans f.map_one.symm,
λ h x y hxy, mul_inv_eq_one.1 $ h _ $ by rw [f.map_mul, hxy, ← f.map_mul, mul_inv_self, f.map_one]⟩
/-- A homomorphism from a group to a monoid is injective iff its kernel is trivial,
stated as an iff on the triviality of the kernel.
For the implication, see `monoid_hom.injective_iff`. -/
@[to_additive /-" A homomorphism from an additive group to an additive monoid is injective iff
its kernel is trivial, stated as an iff on the triviality of the kernel. For the implication, see
`add_monoid_hom.injective_iff`. "-/]
lemma injective_iff' {G H} [group G] [mul_one_class H] (f : G →* H) :
function.injective f ↔ (∀ a, f a = 1 ↔ a = 1) :=
f.injective_iff.trans $ forall_congr $ λ a, ⟨λ h, ⟨h, λ H, H.symm ▸ f.map_one⟩, iff.mp⟩
include mM
/-- Makes a group homomorphism from a proof that the map preserves multiplication. -/
@[to_additive "Makes an additive group homomorphism from a proof that the map preserves addition.",
simps {fully_applied := ff}]
def mk' (f : M → G) (map_mul : ∀ a b : M, f (a * b) = f a * f b) : M →* G :=
{ to_fun := f,
map_mul' := map_mul,
map_one' := mul_left_eq_self.1 $ by rw [←map_mul, mul_one] }
omit mM
/-- Makes a group homomorphism from a proof that the map preserves right division `λ x y, x * y⁻¹`.
See also `monoid_hom.of_map_div` for a version using `λ x y, x / y`.
-/
@[to_additive "Makes an additive group homomorphism from a proof that the map preserves
the operation `λ a b, a + -b`. See also `add_monoid_hom.of_map_sub` for a version using
`λ a b, a - b`."]
def of_map_mul_inv {H : Type*} [group H] (f : G → H)
(map_div : ∀ a b : G, f (a * b⁻¹) = f a * (f b)⁻¹) :
G →* H :=
mk' f $ λ x y,
calc f (x * y) = f x * (f $ 1 * 1⁻¹ * y⁻¹)⁻¹ : by simp only [one_mul, one_inv, ← map_div, inv_inv]
... = f x * f y : by { simp only [map_div], simp only [mul_right_inv, one_mul, inv_inv] }
@[simp, to_additive] lemma coe_of_map_mul_inv {H : Type*} [group H] (f : G → H)
(map_div : ∀ a b : G, f (a * b⁻¹) = f a * (f b)⁻¹) :
⇑(of_map_mul_inv f map_div) = f :=
rfl
/-- Define a morphism of additive groups given a map which respects ratios. -/
@[to_additive /-"Define a morphism of additive groups given a map which respects difference."-/]
def of_map_div {H : Type*} [group H] (f : G → H) (hf : ∀ x y, f (x / y) = f x / f y) : G →* H :=
of_map_mul_inv f (by simpa only [div_eq_mul_inv] using hf)
@[simp, to_additive]
lemma coe_of_map_div {H : Type*} [group H] (f : G → H) (hf : ∀ x y, f (x / y) = f x / f y) :
⇑(of_map_div f hf) = f :=
rfl
/-- If `f` is a monoid homomorphism to a commutative group, then `f⁻¹` is the homomorphism sending
`x` to `(f x)⁻¹`. -/
@[to_additive]
instance {M G} [mul_one_class M] [comm_group G] : has_inv (M →* G) :=
⟨λ f, mk' (λ g, (f g)⁻¹) $ λ a b, by rw [←mul_inv, f.map_mul]⟩
/-- If `f` is an additive monoid homomorphism to an additive commutative group, then `-f` is the
homomorphism sending `x` to `-(f x)`. -/
add_decl_doc add_monoid_hom.has_neg
@[simp, to_additive] lemma inv_apply {M G} {mM : mul_one_class M} {gG : comm_group G}
(f : M →* G) (x : M) :
f⁻¹ x = (f x)⁻¹ := rfl
@[simp, to_additive] lemma inv_comp {M N A} {mM : mul_one_class M} {gN : mul_one_class N}
{gA : comm_group A} (φ : N →* A) (ψ : M →* N) : φ⁻¹.comp ψ = (φ.comp ψ)⁻¹ :=
by { ext, simp only [function.comp_app, inv_apply, coe_comp] }
@[simp, to_additive] lemma comp_inv {M A B} {mM : mul_one_class M} {mA : comm_group A}
{mB : comm_group B} (φ : A →* B) (ψ : M →* A) : φ.comp ψ⁻¹ = (φ.comp ψ)⁻¹ :=
by { ext, simp only [function.comp_app, inv_apply, map_inv, coe_comp] }
/-- If `f` and `g` are monoid homomorphisms to a commutative group, then `f / g` is the homomorphism
sending `x` to `(f x) / (g x)`. -/
@[to_additive]
instance {M G} [mul_one_class M] [comm_group G] : has_div (M →* G) :=
⟨λ f g, mk' (λ x, f x / g x) $ λ a b,
by simp [div_eq_mul_inv, mul_assoc, mul_left_comm, mul_comm]⟩
/-- If `f` and `g` are monoid homomorphisms to an additive commutative group, then `f - g`
is the homomorphism sending `x` to `(f x) - (g x)`. -/
add_decl_doc add_monoid_hom.has_sub
@[simp, to_additive] lemma div_apply {M G} {mM : mul_one_class M} {gG : comm_group G}
(f g : M →* G) (x : M) :
(f / g) x = f x / g x := rfl
end monoid_hom
section commute
variables [mul_one_class M] [mul_one_class N] {a x y : M}
@[simp, to_additive]
protected lemma semiconj_by.map (h : semiconj_by a x y) (f : M →* N) :
semiconj_by (f a) (f x) (f y) :=
by simpa only [semiconj_by, f.map_mul] using congr_arg f h
@[simp, to_additive]
protected lemma commute.map (h : commute x y) (f : M →* N) : commute (f x) (f y) := h.map f
end commute
|
c43c9342869f422590a1d1f9d22ac5a82eac1302 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/algebra/continued_fractions/computation/approximations.lean | 31dceda924bfd36fcb42bb3f5aa81a02788f9ee9 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 14,663 | lean | /-
Copyright (c) 2020 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import algebra.continued_fractions.computation.translations
import algebra.continued_fractions.continuants_recurrence
import algebra.continued_fractions.terminated_stable
import data.nat.fib
/-!
# Approximations for Continued Fraction Computations (`gcf.of`)
## Summary
Let us write `gcf` for `generalized_continued_fraction`. This file contains useful approximations
for the values involved in the continued fractions computation `gcf.of`.
## Main Theorems
- `gcf.of_part_num_eq_one`: shows that all partial numerators `aᵢ` are equal to one.
- `gcf.exists_int_eq_of_part_denom`: shows that all partial denominators `bᵢ` correspond to an integer.
- `gcf.one_le_of_nth_part_denom`: shows that `1 ≤ bᵢ`.
- `gcf.succ_nth_fib_le_of_nth_denom`: shows that the `n`th denominator `Bₙ` is greater than or equal to
the `n + 1`th fibonacci number `nat.fib (n + 1)`.
- `gcf.le_of_succ_nth_denom`: shows that `Bₙ₊₁ ≥ bₙ * Bₙ`, where `bₙ` is the `n`th partial denominator
of the continued fraction.
## References
- [*Hardy, GH and Wright, EM and Heath-Brown, Roger and Silverman, Joseph*][hardy2008introduction]
-/
namespace generalized_continued_fraction
open generalized_continued_fraction as gcf
variables {K : Type*} {v : K} {n : ℕ} [discrete_linear_ordered_field K] [floor_ring K]
/-
We begin with some lemmas about the stream of `int_fract_pair`s, which presumably are not
of great interest for the end user.
-/
namespace int_fract_pair
/-- Shows that the fractional parts of the stream are in `[0,1)`. -/
lemma nth_stream_fr_nonneg_lt_one {ifp_n : int_fract_pair K}
(nth_stream_eq : int_fract_pair.stream v n = some ifp_n) :
0 ≤ ifp_n.fr ∧ ifp_n.fr < 1 :=
begin
cases n,
case nat.zero
{ have : int_fract_pair.of v = ifp_n, by injection nth_stream_eq,
simp [fract_lt_one, fract_nonneg, int_fract_pair.of, this.symm] },
case nat.succ
{ rcases (succ_nth_stream_eq_some_iff.elim_left nth_stream_eq) with ⟨_, _, _, if_of_eq_ifp_n⟩,
simp [fract_lt_one, fract_nonneg, int_fract_pair.of, if_of_eq_ifp_n.symm] }
end
/-- Shows that the fractional parts of the stream are nonnegative. -/
lemma nth_stream_fr_nonneg {ifp_n : int_fract_pair K}
(nth_stream_eq : int_fract_pair.stream v n = some ifp_n) :
0 ≤ ifp_n.fr :=
(nth_stream_fr_nonneg_lt_one nth_stream_eq).left
/-- Shows that the fractional parts of the stream smaller than one. -/
lemma nth_stream_fr_lt_one {ifp_n : int_fract_pair K}
(nth_stream_eq : int_fract_pair.stream v n = some ifp_n) :
ifp_n.fr < 1 :=
(nth_stream_fr_nonneg_lt_one nth_stream_eq).right
/-- Shows that the integer parts of the stream are at least one. -/
lemma one_le_succ_nth_stream_b {ifp_succ_n : int_fract_pair K}
(succ_nth_stream_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) :
1 ≤ ifp_succ_n.b :=
begin
obtain ⟨ifp_n, nth_stream_eq, stream_nth_fr_ne_zero, ⟨_⟩⟩ :
∃ ifp_n, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr ≠ 0
∧ int_fract_pair.of ifp_n.fr⁻¹ = ifp_succ_n, from
succ_nth_stream_eq_some_iff.elim_left succ_nth_stream_eq,
change 1 ≤ ⌊ifp_n.fr⁻¹⌋,
suffices : 1 ≤ ifp_n.fr⁻¹, by { rw_mod_cast [le_floor], assumption },
suffices : 1 * ifp_n.fr ≤ 1, by
{ rw inv_eq_one_div,
have : 0 < ifp_n.fr, from
lt_of_le_of_ne (nth_stream_fr_nonneg nth_stream_eq) stream_nth_fr_ne_zero.symm,
solve_by_elim [le_div_of_mul_le], },
simp [(le_of_lt (nth_stream_fr_lt_one nth_stream_eq))]
end
/--
Shows that the `n + 1`th integer part `bₙ₊₁` of the stream is smaller or equal than the inverse of
the `n`th fractional part `frₙ` of the stream.
This result is straight-forward as `bₙ₊₁` is defined as the floor of `1 / frₙ`
-/
lemma succ_nth_stream_b_le_nth_stream_fr_inv {ifp_n ifp_succ_n : int_fract_pair K}
(nth_stream_eq : int_fract_pair.stream v n = some ifp_n)
(succ_nth_stream_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) :
(ifp_succ_n.b : K) ≤ ifp_n.fr⁻¹ :=
begin
suffices : (⌊ifp_n.fr⁻¹⌋ : K) ≤ ifp_n.fr⁻¹, by
{ cases ifp_n with _ ifp_n_fr,
have : ifp_n_fr ≠ 0, by
{ intro h, simpa [h, int_fract_pair.stream, nth_stream_eq] using succ_nth_stream_eq },
have : int_fract_pair.of ifp_n_fr⁻¹ = ifp_succ_n, by
{ rw with_one.coe_inj.symm,
simpa [this, int_fract_pair.stream, nth_stream_eq] using succ_nth_stream_eq },
rwa ←this },
exact (floor_le ifp_n.fr⁻¹)
end
end int_fract_pair
/-
Next we translate above results about the stream of `int_fract_pair`s to the computed continued
fraction `gcf.of`.
-/
/-- Shows that the integer parts of the continued fraction are at least one. -/
lemma of_one_le_nth_part_denom {b : K}
(nth_part_denom_eq : (gcf.of v).partial_denominators.nth n = some b) :
1 ≤ b :=
begin
obtain ⟨gp_n, nth_s_eq, ⟨_⟩⟩ : ∃ gp_n, (gcf.of v).s.nth n = some gp_n ∧ gp_n.b = b, from
exists_s_b_of_part_denom nth_part_denom_eq,
obtain ⟨ifp_n, succ_nth_stream_eq, ifp_n_b_eq_gp_n_b⟩ :
∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ (ifp.b : K) = gp_n.b, from
int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some nth_s_eq,
rw [←ifp_n_b_eq_gp_n_b],
exact_mod_cast (int_fract_pair.one_le_succ_nth_stream_b succ_nth_stream_eq)
end
/--
Shows that the partial numerators `aᵢ` of the continued fraction are equal to one and the partial
denominators `bᵢ` correspond to integers.
-/
lemma of_part_num_eq_one_and_exists_int_part_denom_eq {gp : gcf.pair K}
(nth_s_eq : (gcf.of v).s.nth n = some gp) :
gp.a = 1 ∧ ∃ (z : ℤ), gp.b = (z : K) :=
begin
obtain ⟨ifp, stream_succ_nth_eq, ifp_b_eq_gp_b⟩ :
∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ (ifp.b : K) = gp.b,
from int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some nth_s_eq,
have : (gcf.of v).s.nth n = some ⟨1, ifp.b⟩, from
nth_of_eq_some_of_succ_nth_int_fract_pair_stream stream_succ_nth_eq,
have : some gp = some ⟨1, ifp.b⟩, by rwa nth_s_eq at this,
have : gp = ⟨1, ifp.b⟩, by injection this,
-- We know the shape of gp, so now we just have to split the goal and use this knowledge.
cases gp,
split,
{ injection this },
{ existsi ifp.b, injection this }
end
/-- Shows that the partial numerators `aᵢ` are equal to one. -/
lemma of_part_num_eq_one {a : K} (nth_part_num_eq : (gcf.of v).partial_numerators.nth n = some a) :
a = 1 :=
begin
obtain ⟨gp, nth_s_eq, gp_a_eq_a_n⟩ : ∃ gp, (gcf.of v).s.nth n = some gp ∧ gp.a = a, from
exists_s_a_of_part_num nth_part_num_eq,
have : gp.a = 1, from (of_part_num_eq_one_and_exists_int_part_denom_eq nth_s_eq).left,
rwa gp_a_eq_a_n at this
end
/-- Shows that the partial denominators `bᵢ` correspond to an integer. -/
lemma exists_int_eq_of_part_denom {b : K}
(nth_part_denom_eq : (gcf.of v).partial_denominators.nth n = some b) :
∃ (z : ℤ), b = (z : K) :=
begin
obtain ⟨gp, nth_s_eq, gp_b_eq_b_n⟩ : ∃ gp, (gcf.of v).s.nth n = some gp ∧ gp.b = b, from
exists_s_b_of_part_denom nth_part_denom_eq,
have : ∃ (z : ℤ), gp.b = (z : K), from
(of_part_num_eq_one_and_exists_int_part_denom_eq nth_s_eq).right,
rwa gp_b_eq_b_n at this
end
/-
One of our next goals is to show that `Bₙ₊₁ ≥ bₙ * Bₙ`. For this, we first show that the partial
denominators `Bₙ` are bounded from below by the fibonacci sequence `nat.fib`. This then implies that
`0 ≤ Bₙ` and hence `Bₙ₊₂ = bₙ₊₁ * Bₙ₊₁ + Bₙ ≥ bₙ₊₁ * Bₙ₊₁ + 0 = bₙ₊₁ * Bₙ₊₁`.
-/
-- open `nat` as we will make use of fibonacci numbers.
open nat
lemma fib_le_of_continuants_aux_b : (n ≤ 1 ∨ ¬(gcf.of v).terminated_at (n - 2)) →
(fib n : K) ≤ ((gcf.of v).continuants_aux n).b :=
nat.strong_induction_on n
begin
clear n,
assume n IH hyp,
rcases n with _|_|n,
{ simp [fib_succ_succ, continuants_aux] }, -- case n = 0
{ simp [fib_succ_succ, continuants_aux] }, -- case n = 1
{ let g := gcf.of v, -- case 2 ≤ n
have : ¬(n + 2 ≤ 1), by linarith,
have not_terminated_at_n : ¬g.terminated_at n, from or.resolve_left hyp this,
obtain ⟨gp, s_ppred_nth_eq⟩ : ∃ gp, g.s.nth n = some gp, from
with_one.ne_one_iff_exists.elim_left not_terminated_at_n,
set pconts := g.continuants_aux (n + 1) with pconts_eq,
set ppconts := g.continuants_aux n with ppconts_eq,
-- use the recurrence of continuants_aux
suffices : (fib n : K) + fib (n + 1) ≤ gp.a * ppconts.b + gp.b * pconts.b, by
simpa [fib_succ_succ, add_comm,
(continuants_aux_recurrence s_ppred_nth_eq ppconts_eq pconts_eq)],
-- make use of the fact that gp.a = 1
suffices : (fib n : K) + fib (n + 1) ≤ ppconts.b + gp.b * pconts.b, by
simpa [(of_part_num_eq_one $ part_num_eq_s_a s_ppred_nth_eq)],
have not_terminated_at_pred_n : ¬g.terminated_at (n - 1), from
mt (terminated_stable $ nat.sub_le n 1) not_terminated_at_n,
have not_terminated_at_ppred_n : ¬terminated_at g (n - 2), from
mt (terminated_stable (n - 1).pred_le) not_terminated_at_pred_n,
-- use the IH to get the inequalities for `pconts` and `ppconts`
have : (fib (n + 1) : K) ≤ pconts.b, from
IH _ (nat.lt.base $ n + 1) (or.inr not_terminated_at_pred_n),
have ppred_nth_fib_le_ppconts_B : (fib n : K) ≤ ppconts.b, from
IH n (lt_trans (nat.lt.base n) $ nat.lt.base $ n + 1)
(or.inr not_terminated_at_ppred_n),
suffices : (fib (n + 1) : K) ≤ gp.b * pconts.b,
solve_by_elim [(add_le_add ppred_nth_fib_le_ppconts_B)],
-- finally use the fact that 1 ≤ gp.b to solve the goal
suffices : 1 * (fib (n + 1) : K) ≤ gp.b * pconts.b, by rwa [one_mul] at this,
have one_le_gp_b : (1 : K) ≤ gp.b, from
of_one_le_nth_part_denom (part_denom_eq_s_b s_ppred_nth_eq),
have : (0 : K) ≤ fib (n + 1), by exact_mod_cast (fib (n + 1)).zero_le,
have : (0 : K) ≤ gp.b, from le_trans zero_le_one one_le_gp_b,
mono }
end
/-- Shows that the `n`th denominator is greater than or equal to the `n + 1`th fibonacci number,
that is `nat.fib (n + 1) ≤ Bₙ`. -/
lemma succ_nth_fib_le_of_nth_denom (hyp: n = 0 ∨ ¬(gcf.of v).terminated_at (n - 1)) :
(fib (n + 1) : K) ≤ (gcf.of v).denominators n :=
begin
rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux],
have : (n + 1) ≤ 1 ∨ ¬(gcf.of v).terminated_at (n - 1), by
{ cases n,
case nat.zero : { exact (or.inl $ le_refl 1) },
case nat.succ : { exact or.inr (or.resolve_left hyp n.succ_ne_zero) } },
exact (fib_le_of_continuants_aux_b this)
end
/- As a simple consequence, we can now derive that all denominators are nonnegative. -/
lemma zero_le_of_continuants_aux_b : 0 ≤ ((gcf.of v).continuants_aux n).b :=
begin
let g := gcf.of v,
induction n with n IH,
case nat.zero: { refl },
case nat.succ:
{ cases (decidable.em $ g.terminated_at (n - 1)) with terminated not_terminated,
{ cases n,
{ simp[zero_le_one] },
{ have : g.continuants_aux (n + 2) = g.continuants_aux (n + 1), from
continuants_aux_stable_step_of_terminated terminated,
simp[this, IH] } },
{ calc
(0 : K) ≤ fib (n + 1) : by exact_mod_cast (n + 1).fib.zero_le
... ≤ ((gcf.of v).continuants_aux (n + 1)).b : fib_le_of_continuants_aux_b
(or.inr not_terminated) } }
end
/-- Shows that all denominators are nonnegative. -/
lemma zero_le_of_denom : 0 ≤ (gcf.of v).denominators n :=
by { rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], exact zero_le_of_continuants_aux_b }
lemma le_of_succ_succ_nth_continuants_aux_b {b : K}
(nth_part_denom_eq : (gcf.of v).partial_denominators.nth n = some b) :
b * ((gcf.of v).continuants_aux $ n + 1).b ≤ ((gcf.of v).continuants_aux $ n + 2).b :=
begin
set g := gcf.of v with g_eq,
obtain ⟨gp_n, nth_s_eq, ⟨_⟩⟩ : ∃ gp_n, g.s.nth n = some gp_n ∧ gp_n.b = b, from
exists_s_b_of_part_denom nth_part_denom_eq,
let conts := g.continuants_aux (n + 2),
set pconts := g.continuants_aux (n + 1) with pconts_eq,
set ppconts := g.continuants_aux n with ppconts_eq,
-- use the recurrence of continuants_aux and the fact that gp_n.a = 1
suffices : gp_n.b * pconts.b ≤ ppconts.b + gp_n.b * pconts.b, by
{ have : gp_n.a = 1, from of_part_num_eq_one (part_num_eq_s_a nth_s_eq),
finish [(gcf.continuants_aux_recurrence nth_s_eq ppconts_eq pconts_eq)] },
have : 0 ≤ ppconts.b, from zero_le_of_continuants_aux_b,
solve_by_elim [le_add_of_nonneg_of_le, le_refl]
end
/-- Shows that `Bₙ₊₁ ≥ bₙ * Bₙ`, where `bₙ` is the `n`th partial denominator and `Bₙ₊₁` and `Bₙ` are
the `n + 1`th and `n`th denominator of the continued fraction. -/
theorem le_of_succ_nth_denom {b : K}
(nth_part_denom_eq : (gcf.of v).partial_denominators.nth n = some b) :
b * (gcf.of v).denominators n ≤ (gcf.of v).denominators (n + 1) :=
begin
rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux],
exact (le_of_succ_succ_nth_continuants_aux_b nth_part_denom_eq)
end
/-- Shows that the sequence of denominators is monotonically increasing, that is `Bₙ ≤ Bₙ₊₁`. -/
theorem of_denom_mono : (gcf.of v).denominators n ≤ (gcf.of v).denominators (n + 1) :=
begin
let g := gcf.of v,
cases (decidable.em $ g.partial_denominators.terminated_at n) with terminated not_terminated,
{ have : g.partial_denominators.nth n = none, by rwa seq.terminated_at at terminated,
have : g.terminated_at n, from
terminated_at_iff_part_denom_none.elim_right (by rwa seq.terminated_at at terminated),
have : (gcf.of v).denominators (n + 1) = (gcf.of v).denominators n, from
denominators_stable_of_terminated n.le_succ this,
rw this },
{ obtain ⟨b, nth_part_denom_eq⟩ : ∃ b, g.partial_denominators.nth n = some b, from
with_one.ne_one_iff_exists.elim_left not_terminated,
have : 1 ≤ b, from of_one_le_nth_part_denom nth_part_denom_eq,
calc
(gcf.of v).denominators n ≤ b * (gcf.of v).denominators n : by simpa using
mul_le_mul_of_nonneg_right
this zero_le_of_denom
... ≤ (gcf.of v).denominators (n + 1) : le_of_succ_nth_denom
nth_part_denom_eq }
end
end generalized_continued_fraction
|
dfe8bae7b32c689a456456519a91b58f2d2232af | 74caf7451c921a8d5ab9c6e2b828c9d0a35aae95 | /library/init/meta/expr.lean | 0646a751536cc0fd9a7710261337e7d7c6a57452 | [
"Apache-2.0"
] | permissive | sakas--/lean | f37b6fad4fd4206f2891b89f0f8135f57921fc3f | 570d9052820be1d6442a5cc58ece37397f8a9e4c | refs/heads/master | 1,586,127,145,194 | 1,480,960,018,000 | 1,480,960,635,000 | 40,137,176 | 0 | 0 | null | 1,438,621,351,000 | 1,438,621,351,000 | null | UTF-8 | Lean | false | false | 6,867 | 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.level
inductive binder_info
| default | implicit | strict_implicit | inst_implicit | other
meta constant macro_def : Type
/- Reflect a C++ expr object. The VM replaces it with the C++ implementation. -/
meta inductive expr
| var : unsigned → expr
| sort : level → expr
| const : name → list level → expr
| mvar : name → expr → expr
| local_const : name → name → binder_info → expr → expr
| app : expr → expr → expr
| lam : name → binder_info → expr → expr → expr
| pi : name → binder_info → expr → expr → expr
| elet : name → expr → expr → expr → expr
| macro : macro_def → ∀ n : unsigned, (fin (unsigned.to_nat n) → expr) → expr
meta instance : inhabited expr :=
⟨expr.sort level.zero⟩
meta constant expr.mk_macro (d : macro_def) : list expr → expr
meta def expr.mk_var (n : nat) : expr :=
expr.var (unsigned.of_nat n)
-- Compares expressions, including binder names.
meta constant expr.has_decidable_eq : decidable_eq expr
attribute [instance] expr.has_decidable_eq
-- Compares expressions while ignoring binder names.
meta constant expr.alpha_eqv : expr → expr → bool
notation a ` =ₐ `:50 b:50 := expr.alpha_eqv a b = bool.tt
meta constant expr.to_string : expr → string
meta instance : has_to_string expr :=
has_to_string.mk expr.to_string
/- Coercion for letting users write (f a) instead of (expr.app f a) -/
meta instance : has_coe_to_fun expr :=
{ F := λ e, expr → expr, coe := λ e, expr.app e }
meta constant expr.hash : expr → nat
-- Compares expressions, ignoring binder names, and sorting by hash.
meta constant expr.lt : expr → expr → bool
-- Compares expressions, ignoring binder names.
meta constant expr.lex_lt : expr → expr → bool
-- Compares expressions, ignoring binder names, and sorting by hash.
meta def expr.cmp (a b : expr) : ordering :=
if expr.lt a b then ordering.lt
else if a =ₐ b then ordering.eq
else ordering.gt
meta constant expr.fold {α : Type} : expr → α → (expr → nat → α → α) → α
meta constant expr.replace : expr → (expr → nat → option expr) → expr
meta constant expr.abstract_local : expr → name → expr
meta constant expr.abstract_locals : expr → list name → expr
meta def expr.abstract : expr → expr → expr
| e (expr.local_const n m bi t) := e^.abstract_local n
| e _ := e
meta constant expr.instantiate_var : expr → expr → expr
meta constant expr.instantiate_vars : expr → list expr → expr
meta constant expr.has_var : expr → bool
meta constant expr.has_var_idx : expr → nat → bool
meta constant expr.has_local : expr → bool
meta constant expr.has_meta_var : expr → bool
meta constant expr.lift_vars : expr → nat → nat → expr
meta constant expr.lower_vars : expr → nat → nat → expr
/- (copy_pos_info src tgt) copy position information from src to tgt. -/
meta constant expr.copy_pos_info : expr → expr → expr
namespace expr
open decidable
-- Compares expressions, ignoring binder names, and sorting by hash.
meta instance : has_ordering expr :=
⟨ expr.cmp ⟩
meta def app_of_list : expr → list expr → expr
| f [] := f
| f (p::ps) := app_of_list (f p) ps
meta def is_app : expr → bool
| (app f a) := tt
| e := ff
meta def app_fn : expr → expr
| (app f a) := f
| a := a
meta def app_arg : expr → expr
| (app f a) := a
| a := a
meta def get_app_fn : expr → expr
| (app f a) := get_app_fn f
| a := a
meta def get_app_num_args : expr → nat
| (app f a) := get_app_num_args f + 1
| e := 0
meta def get_app_args_aux : list expr → expr → list expr
| r (app f a) := get_app_args_aux (a::r) f
| r e := r
meta def get_app_args : expr → list expr :=
get_app_args_aux []
meta def const_name : expr → name
| (const n ls) := n
| e := name.anonymous
meta def is_constant : expr → bool
| (const n ls) := tt
| e := ff
meta def is_local_constant : expr → bool
| (local_const n m bi t) := tt
| e := ff
meta def local_uniq_name : expr → name
| (local_const n m bi t) := n
| e := name.anonymous
meta def local_pp_name : expr → name
| (local_const x n bi t) := n
| e := name.anonymous
meta def is_constant_of : expr → name → bool
| (const n₁ ls) n₂ := to_bool (n₁ = n₂)
| e n := ff
meta def is_app_of (e : expr) (n : name) : bool :=
is_app e && is_constant_of (get_app_fn e) n
meta def is_napp_of (e : expr) (c : name) (n : nat) : bool :=
to_bool (is_app_of e c ∧ get_app_num_args e = n)
meta def is_false (e : expr) : bool :=
is_constant_of e `false
meta def is_not : expr → option expr
| (app f a) := if is_constant_of f `not then some a else none
| (pi n bi a b) := if is_false b then some a else none
| e := none
meta def is_eq (e : expr) : option (expr × expr) :=
if is_napp_of e `eq 3
then some (app_arg (app_fn e), app_arg e)
else none
meta def is_ne (e : expr) : option (expr × expr) :=
if is_napp_of e `ne 3
then some (app_arg (app_fn e), app_arg e)
else none
meta def is_bin_arith_app (e : expr) (op : name) : option (expr × expr) :=
if is_napp_of e op 4
then some (app_arg (app_fn e), app_arg e)
else none
meta def is_lt (e : expr) : option (expr × expr) :=
is_bin_arith_app e `lt
meta def is_gt (e : expr) : option (expr × expr) :=
is_bin_arith_app e `gt
meta def is_le (e : expr) : option (expr × expr) :=
is_bin_arith_app e `le
meta def is_ge (e : expr) : option (expr × expr) :=
is_bin_arith_app e `ge
meta def is_heq (e : expr) : option (expr × expr × expr × expr) :=
if is_napp_of e `heq 4
then some (app_arg (app_fn (app_fn (app_fn e))),
app_arg (app_fn (app_fn e)),
app_arg (app_fn e),
app_arg e)
else none
meta def is_pi : expr → bool
| (pi n bi d b) := tt
| e := ff
meta def is_arrow : expr → bool
| (pi n bi d b) := bnot (has_var b)
| e := ff
meta def is_let : expr → bool
| (elet n t v b) := tt
| e := ff
meta def binding_name : expr → name
| (pi n m d b) := n
| (lam n m d b) := n
| e := name.anonymous
meta def binding_info : expr → binder_info
| (pi n bi d b) := bi
| (lam n bi d b) := bi
| e := binder_info.default
meta def binding_domain : expr → expr
| (pi n bi d b) := d
| (lam n bi d b) := d
| e := e
meta def binding_body : expr → expr
| (pi n bi d b) := b
| (lam n bi d b) := b
| e := e
meta def prop : expr := expr.sort level.zero
end expr
|
1a6690690e4d0e3fd60a3ad14200ef688ea5dc01 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Init/SizeOf.lean | 000fa5538c568eed7a8bc29fed7051abaab7e9c6 | [
"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 | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 1,811 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Notation
/- SizeOf -/
class SizeOf (α : Sort u) where
sizeOf : α → Nat
export SizeOf (sizeOf)
/-
Declare sizeOf instances and theorems for types declared before SizeOf.
From now on, the inductive Compiler will automatically generate sizeOf instances and theorems.
-/
/- Every Type `α` has a default SizeOf instance that just returns 0 for every element of `α` -/
protected def default.sizeOf (α : Sort u) : α → Nat
| a => 0
instance (priority := low) (α : Sort u) : SizeOf α where
sizeOf := default.sizeOf α
instance : SizeOf Nat where
sizeOf n := n
deriving instance SizeOf for Prod
deriving instance SizeOf for PUnit
deriving instance SizeOf for Bool
deriving instance SizeOf for Option
deriving instance SizeOf for List
deriving instance SizeOf for Array
deriving instance SizeOf for Subtype
deriving instance SizeOf for Fin
deriving instance SizeOf for USize
deriving instance SizeOf for UInt8
deriving instance SizeOf for UInt16
deriving instance SizeOf for UInt32
deriving instance SizeOf for UInt64
deriving instance SizeOf for Char
deriving instance SizeOf for String
deriving instance SizeOf for Substring
deriving instance SizeOf for Except
deriving instance SizeOf for EStateM.Result
/- We manually define `Lean.Name` instance because we use
an opaque function for computing the hashcode field. -/
protected noncomputable def Lean.Name.sizeOf : Name → Nat
| anonymous => 1
| str p s _ => 1 + Name.sizeOf p + sizeOf s
| num p n _ => 1 + Name.sizeOf p + sizeOf n
noncomputable instance : SizeOf Lean.Name where
sizeOf n := n.sizeOf
deriving instance SizeOf for Lean.Syntax
|
265a0ad8c4ec49dcdae1029f01ef1e5a879d6b7b | 4b846d8dabdc64e7ea03552bad8f7fa74763fc67 | /tests/lean/run/IO3.lean | adeede7d3d323e5b40620d2a7e14843d4782af98 | [
"Apache-2.0"
] | permissive | pacchiano/lean | 9324b33f3ac3b5c5647285160f9f6ea8d0d767dc | fdadada3a970377a6df8afcd629a6f2eab6e84e8 | refs/heads/master | 1,611,357,380,399 | 1,489,870,101,000 | 1,489,870,101,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 217 | lean | import system.io
open io
def main : io unit :=
do { l ← get_line,
if l = "hello" then
put_str "you have typed hello\n"
else
do {put_str "you did not type hello\n", put_str "-----------\n"} }
|
80166defaa9a0d62216703a525ec3ee7608174e8 | 947b78d97130d56365ae2ec264df196ce769371a | /src/Lean/Elab/Attributes.lean | fe2b6d10605bdb5d8dddd9a9f815f3342055d670 | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,796 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Parser.Basic
import Lean.Attributes
import Lean.MonadEnv
namespace Lean
namespace Elab
structure Attribute :=
(name : Name) (args : Syntax := Syntax.missing)
instance Attribute.hasFormat : HasFormat Attribute :=
⟨fun attr => Format.bracket "@[" (toString attr.name ++ (if attr.args.isMissing then "" else toString attr.args)) "]"⟩
instance Attribute.inhabited : Inhabited Attribute := ⟨{ name := arbitrary _ }⟩
def elabAttr {m} [Monad m] [MonadEnv m] [MonadExceptOf Exception m] [Ref m] [AddErrorMessageContext m] (stx : Syntax) : m Attribute := do
-- rawIdent >> many attrArg
let nameStx := stx.getArg 0;
attrName ← match nameStx.isIdOrAtom? with
| none => withRef nameStx $ throwError "identifier expected"
| some str => pure $ mkNameSimple str;
env ← getEnv;
unless (isAttribute env attrName) $
throwError ("unknown attribute [" ++ attrName ++ "]");
let args := stx.getArg 1;
-- the old frontend passes Syntax.missing for empty args, for reasons
let args := if args.getNumArgs == 0 then Syntax.missing else args;
pure { name := attrName, args := args }
-- sepBy1 attrInstance ", "
def elabAttrs {m} [Monad m] [MonadEnv m] [MonadExceptOf Exception m] [Ref m] [AddErrorMessageContext m] (stx : Syntax) : m (Array Attribute) :=
stx.foldSepArgsM
(fun stx attrs => do
attr ← elabAttr stx;
pure $ attrs.push attr)
#[]
-- parser! "@[" >> sepBy1 attrInstance ", " >> "]"
def elabDeclAttrs {m} [Monad m] [MonadEnv m] [MonadExceptOf Exception m] [Ref m] [AddErrorMessageContext m] (stx : Syntax) : m (Array Attribute) :=
elabAttrs (stx.getArg 1)
end Elab
end Lean
|
b87bd38de6f081f29107918903ec5a425a85766f | 5e3548e65f2c037cb94cd5524c90c623fbd6d46a | /src_icannos_totilas/reduction/cpge_reduction_001.lean | a605de341c8302a595e58f28c35ce37688786b6d | [] | no_license | ahayat16/lean_exos | d4f08c30adb601a06511a71b5ffb4d22d12ef77f | 682f2552d5b04a8c8eb9e4ab15f875a91b03845c | refs/heads/main | 1,693,101,073,585 | 1,636,479,336,000 | 1,636,479,336,000 | 415,000,441 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 366 | lean | import algebra.module.basic
import algebra.module.linear_map
import linear_algebra.basic
import linear_algebra.prod
import linear_algebra.projection
import order.bounded_lattice
theorem cpge_reduction_1 (R : Type*) (M : Type*)
[semiring R] [add_comm_monoid M] [module R M] (u : linear_map R M M) (E : submodule R M) :
u '' u.ker = u.ker ∧ (u '' E) = E := sorry |
96582065f72c87f15acef7316d5b2a1815224570 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/combinatorics/set_family/harris_kleitman.lean | 153ea58531502ff4573d98f71bf6888d40976c1b | [
"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 | 8,224 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import algebra.big_operators.basic
import order.upper_lower
/-!
# Harris-Kleitman inequality
This file proves the Harris-Kleitman inequality. This relates `𝒜.card * ℬ.card` and
`2 ^ card α * (𝒜 ∩ ℬ).card` where `𝒜` and `ℬ` are upward- or downcard-closed finite families of
finsets. This can be interpreted as saying that any two lower sets (resp. any two upper sets)
correlate in the uniform measure.
## Main declarations
* `finset.non_member_subfamily`: `𝒜.non_member_subfamily a` is the subfamily of sets not containing
`a`.
* `finset.member_subfamily`: `𝒜.member_subfamily a` is the image of the subfamily of sets
containing `a` under removing `a`.
* `is_lower_set.le_card_inter_finset`: One form of the Harris-Kleitman inequality.
## References
* [D. J. Kleitman, *Families of non-disjoint subsets*][kleitman1966]
-/
open_locale big_operators
variables {α : Type*} [decidable_eq α] {𝒜 ℬ : finset (finset α)} {s : finset α} {a : α}
namespace finset
/-- ELements of `𝒜` that do not contain `a`. -/
def non_member_subfamily (𝒜 : finset (finset α)) (a : α) : finset (finset α) :=
𝒜.filter $ λ s, a ∉ s
/-- Image of the elements of `𝒜` which contain `a` under removing `a`. Finsets that do not contain
`a` such that `insert a s ∈ 𝒜`. -/
def member_subfamily (𝒜 : finset (finset α)) (a : α) : finset (finset α) :=
(𝒜.filter $ λ s, a ∈ s).image $ λ s, erase s a
@[simp] lemma mem_non_member_subfamily : s ∈ 𝒜.non_member_subfamily a ↔ s ∈ 𝒜 ∧ a ∉ s := mem_filter
@[simp] lemma mem_member_subfamily : s ∈ 𝒜.member_subfamily a ↔ insert a s ∈ 𝒜 ∧ a ∉ s :=
begin
simp_rw [member_subfamily, mem_image, mem_filter],
refine ⟨_, λ h, ⟨insert a s, ⟨h.1, mem_insert_self _ _⟩, erase_insert h.2⟩⟩,
rintro ⟨s, hs, rfl⟩,
rw insert_erase hs.2,
exact ⟨hs.1, not_mem_erase _ _⟩,
end
lemma non_member_subfamily_inter (𝒜 ℬ : finset (finset α)) (a : α) :
(𝒜 ∩ ℬ).non_member_subfamily a = 𝒜.non_member_subfamily a ∩ ℬ.non_member_subfamily a :=
filter_inter_distrib _ _ _
lemma member_subfamily_inter (𝒜 ℬ : finset (finset α)) (a : α) :
(𝒜 ∩ ℬ).member_subfamily a = 𝒜.member_subfamily a ∩ ℬ.member_subfamily a :=
begin
unfold member_subfamily,
rw [filter_inter_distrib, image_inter_of_inj_on _ _ ((erase_inj_on' _).mono _)],
rw [←coe_union, ←filter_union, coe_filter],
exact set.inter_subset_right _ _,
end
lemma card_member_subfamily_add_card_non_member_subfamily (𝒜 : finset (finset α)) (a : α) :
(𝒜.member_subfamily a).card + (𝒜.non_member_subfamily a).card = 𝒜.card :=
begin
rw [member_subfamily, non_member_subfamily, card_image_of_inj_on,
filter_card_add_filter_neg_card_eq_card],
exact (erase_inj_on' _).mono (λ s hs, (mem_filter.1 hs).2),
end
end finset
open finset
lemma is_lower_set.non_member_subfamily (h : is_lower_set (𝒜 : set (finset α))) :
is_lower_set (𝒜.non_member_subfamily a : set (finset α)) :=
λ s t hts, by { simp_rw [mem_coe, mem_non_member_subfamily], exact and.imp (h hts) (mt $ @hts _) }
lemma is_lower_set.member_subfamily (h : is_lower_set (𝒜 : set (finset α))) :
is_lower_set (𝒜.member_subfamily a : set (finset α)) :=
begin
rintro s t hts,
simp_rw [mem_coe, mem_member_subfamily],
exact and.imp (h $ insert_subset_insert _ hts) (mt $ @hts _),
end
lemma is_lower_set.member_subfamily_subset_non_member_subfamily
(h : is_lower_set (𝒜 : set (finset α))) :
𝒜.member_subfamily a ⊆ 𝒜.non_member_subfamily a :=
λ s, by { rw [mem_member_subfamily, mem_non_member_subfamily],
exact and.imp_left (h $ subset_insert _ _) }
/-- **Harris-Kleitman inequality**: Any two lower sets of finsets correlate. -/
lemma is_lower_set.le_card_inter_finset'
(h𝒜 : is_lower_set (𝒜 : set (finset α))) (hℬ : is_lower_set (ℬ : set (finset α)))
(h𝒜s : ∀ t ∈ 𝒜, t ⊆ s) (hℬs : ∀ t ∈ ℬ, t ⊆ s) :
𝒜.card * ℬ.card ≤ 2 ^ s.card * (𝒜 ∩ ℬ).card :=
begin
induction s using finset.induction with a s hs ih generalizing 𝒜 ℬ,
{ simp_rw [subset_empty, ←subset_singleton_iff', subset_singleton_iff] at h𝒜s hℬs,
obtain rfl | rfl := h𝒜s,
{ simp only [card_empty, empty_inter, mul_zero, zero_mul] },
obtain rfl | rfl := hℬs,
{ simp only [card_empty, inter_empty, mul_zero, zero_mul] },
{ simp only [card_empty, pow_zero, inter_singleton_of_mem, mem_singleton, card_singleton] } },
rw [card_insert_of_not_mem hs, ←card_member_subfamily_add_card_non_member_subfamily 𝒜 a,
←card_member_subfamily_add_card_non_member_subfamily ℬ a, add_mul, mul_add, mul_add,
add_comm (_ * _), add_add_add_comm],
refine (add_le_add_right (mul_add_mul_le_mul_add_mul
(card_le_of_subset h𝒜.member_subfamily_subset_non_member_subfamily) $
card_le_of_subset hℬ.member_subfamily_subset_non_member_subfamily) _).trans _,
rw [←two_mul, pow_succ, mul_assoc],
have h₀ : ∀ 𝒞 : finset (finset α), (∀ t ∈ 𝒞, t ⊆ insert a s) → ∀ t ∈ 𝒞.non_member_subfamily a,
t ⊆ s,
{ rintro 𝒞 h𝒞 t ht,
rw mem_non_member_subfamily at ht,
exact (subset_insert_iff_of_not_mem ht.2).1 (h𝒞 _ ht.1) },
have h₁ : ∀ 𝒞 : finset (finset α), (∀ t ∈ 𝒞, t ⊆ insert a s) → ∀ t ∈ 𝒞.member_subfamily a, t ⊆ s,
{ rintro 𝒞 h𝒞 t ht,
rw mem_member_subfamily at ht,
exact (subset_insert_iff_of_not_mem ht.2).1 ((subset_insert _ _).trans $ h𝒞 _ ht.1) },
refine mul_le_mul_left' _ _,
refine (add_le_add (ih (h𝒜.member_subfamily) (hℬ.member_subfamily) (h₁ _ h𝒜s) $ h₁ _ hℬs) $
ih (h𝒜.non_member_subfamily) (hℬ.non_member_subfamily) (h₀ _ h𝒜s) $ h₀ _ hℬs).trans_eq _,
rw [←mul_add, ←member_subfamily_inter, ←non_member_subfamily_inter,
card_member_subfamily_add_card_non_member_subfamily],
end
variables [fintype α]
/-- **Harris-Kleitman inequality**: Any two lower sets of finsets correlate. -/
lemma is_lower_set.le_card_inter_finset
(h𝒜 : is_lower_set (𝒜 : set (finset α))) (hℬ : is_lower_set (ℬ : set (finset α))) :
𝒜.card * ℬ.card ≤ 2 ^ fintype.card α * (𝒜 ∩ ℬ).card :=
h𝒜.le_card_inter_finset' hℬ (λ _ _, subset_univ _) $ λ _ _, subset_univ _
/-- **Harris-Kleitman inequality**: Upper sets and lower sets of finsets anticorrelate. -/
lemma is_upper_set.card_inter_le_finset
(h𝒜 : is_upper_set (𝒜 : set (finset α))) (hℬ : is_lower_set (ℬ : set (finset α))) :
2 ^ fintype.card α * (𝒜 ∩ ℬ).card ≤ 𝒜.card * ℬ.card :=
begin
rw [←is_lower_set_compl, ←coe_compl] at h𝒜,
have := h𝒜.le_card_inter_finset hℬ,
rwa [card_compl, fintype.card_finset, tsub_mul, tsub_le_iff_tsub_le, ←mul_tsub, ←card_sdiff
(inter_subset_right _ _), sdiff_inter_self_right, sdiff_compl, _root_.inf_comm] at this,
end
/-- **Harris-Kleitman inequality**: Lower sets and upper sets of finsets anticorrelate. -/
lemma is_lower_set.card_inter_le_finset
(h𝒜 : is_lower_set (𝒜 : set (finset α))) (hℬ : is_upper_set (ℬ : set (finset α))) :
2 ^ fintype.card α * (𝒜 ∩ ℬ).card ≤ 𝒜.card * ℬ.card :=
by { rw [inter_comm, mul_comm 𝒜.card], exact hℬ.card_inter_le_finset h𝒜 }
/-- **Harris-Kleitman inequality**: Any two upper sets of finsets correlate. -/
lemma is_upper_set.le_card_inter_finset
(h𝒜 : is_upper_set (𝒜 : set (finset α))) (hℬ : is_upper_set (ℬ : set (finset α))) :
𝒜.card * ℬ.card ≤ 2 ^ fintype.card α * (𝒜 ∩ ℬ).card :=
begin
rw [←is_lower_set_compl, ←coe_compl] at h𝒜,
have := h𝒜.card_inter_le_finset hℬ,
rwa [card_compl, fintype.card_finset, tsub_mul, le_tsub_iff_le_tsub, ←mul_tsub, ←card_sdiff
(inter_subset_right _ _), sdiff_inter_self_right, sdiff_compl, _root_.inf_comm] at this,
{ exact mul_le_mul_left' (card_le_of_subset $ inter_subset_right _ _) _ },
{ rw ←fintype.card_finset,
exact mul_le_mul_right' (card_le_univ _) _ }
end
|
94a58a1884a782e165e733d51b599a29729db1da | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebra/graded_monoid.lean | b1148140c6b47e7e439f609bfe38de5442c59bed | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 21,992 | lean | /-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import algebra.group.inj_surj
import data.list.big_operators
import data.list.range
import group_theory.group_action.defs
import group_theory.submonoid.basic
import data.set_like.basic
import data.sigma.basic
/-!
# Additively-graded multiplicative structures
This module provides a set of heterogeneous typeclasses for defining a multiplicative structure
over the sigma type `graded_monoid A` such that `(*) : A i → A j → A (i + j)`; that is to say, `A`
forms an additively-graded monoid. The typeclasses are:
* `graded_monoid.ghas_one A`
* `graded_monoid.ghas_mul A`
* `graded_monoid.gmonoid A`
* `graded_monoid.gcomm_monoid A`
With the `sigma_graded` locale open, these respectively imbue:
* `has_one (graded_monoid A)`
* `has_mul (graded_monoid A)`
* `monoid (graded_monoid A)`
* `comm_monoid (graded_monoid A)`
the base type `A 0` with:
* `graded_monoid.grade_zero.has_one`
* `graded_monoid.grade_zero.has_mul`
* `graded_monoid.grade_zero.monoid`
* `graded_monoid.grade_zero.comm_monoid`
and the `i`th grade `A i` with `A 0`-actions (`•`) defined as left-multiplication:
* (nothing)
* `graded_monoid.grade_zero.has_smul (A 0)`
* `graded_monoid.grade_zero.mul_action (A 0)`
* (nothing)
For now, these typeclasses are primarily used in the construction of `direct_sum.ring` and the rest
of that file.
## Dependent graded products
This also introduces `list.dprod`, which takes the (possibly non-commutative) product of a list
of graded elements of type `A i`. This definition primarily exist to allow `graded_monoid.mk`
and `direct_sum.of` to be pulled outside a product, such as in `graded_monoid.mk_list_dprod` and
`direct_sum.of_list_dprod`.
## Internally graded monoids
In addition to the above typeclasses, in the most frequent case when `A` is an indexed collection of
`set_like` subobjects (such as `add_submonoid`s, `add_subgroup`s, or `submodule`s), this file
provides the `Prop` typeclasses:
* `set_like.has_graded_one A` (which provides the obvious `graded_monoid.ghas_one A` instance)
* `set_like.has_graded_mul A` (which provides the obvious `graded_monoid.ghas_mul A` instance)
* `set_like.graded_monoid A` (which provides the obvious `graded_monoid.gmonoid A` and
`graded_monoid.gcomm_monoid A` instances)
which respectively provide the API lemmas
* `set_like.one_mem_graded`
* `set_like.mul_mem_graded`
* `set_like.pow_mem_graded`, `set_like.list_prod_map_mem_graded`
Strictly this last class is unecessary as it has no fields not present in its parents, but it is
included for convenience. Note that there is no need for `set_like.graded_ring` or similar, as all
the information it would contain is already supplied by `graded_monoid` when `A` is a collection
of objects satisfying `add_submonoid_class` such as `submodule`s. These constructions are explored
in `algebra.direct_sum.internal`.
This file also defines:
* `set_like.is_homogeneous A` (which says that `a` is homogeneous iff `a ∈ A i` for some `i : ι`)
* `set_like.homogeneous_submonoid A`, which is, as the name suggests, the submonoid consisting of
all the homogeneous elements.
## tags
graded monoid
-/
set_option old_structure_cmd true
variables {ι : Type*}
/-- A type alias of sigma types for graded monoids. -/
def graded_monoid (A : ι → Type*) := sigma A
namespace graded_monoid
instance {A : ι → Type*} [inhabited ι] [inhabited (A default)]: inhabited (graded_monoid A) :=
sigma.inhabited
/-- Construct an element of a graded monoid. -/
def mk {A : ι → Type*} : Π i, A i → graded_monoid A := sigma.mk
/-! ### Typeclasses -/
section defs
variables (A : ι → Type*)
/-- A graded version of `has_one`, which must be of grade 0. -/
class ghas_one [has_zero ι] :=
(one : A 0)
/-- `ghas_one` implies `has_one (graded_monoid A)` -/
instance ghas_one.to_has_one [has_zero ι] [ghas_one A] : has_one (graded_monoid A) :=
⟨⟨_, ghas_one.one⟩⟩
/-- A graded version of `has_mul`. Multiplication combines grades additively, like
`add_monoid_algebra`. -/
class ghas_mul [has_add ι] :=
(mul {i j} : A i → A j → A (i + j))
/-- `ghas_mul` implies `has_mul (graded_monoid A)`. -/
instance ghas_mul.to_has_mul [has_add ι] [ghas_mul A] :
has_mul (graded_monoid A) :=
⟨λ (x y : graded_monoid A), ⟨_, ghas_mul.mul x.snd y.snd⟩⟩
lemma mk_mul_mk [has_add ι] [ghas_mul A] {i j} (a : A i) (b : A j) :
mk i a * mk j b = mk (i + j) (ghas_mul.mul a b) :=
rfl
namespace gmonoid
variables {A} [add_monoid ι] [ghas_mul A] [ghas_one A]
/-- A default implementation of power on a graded monoid, like `npow_rec`.
`gmonoid.gnpow` should be used instead. -/
def gnpow_rec : Π (n : ℕ) {i}, A i → A (n • i)
| 0 i a := cast (congr_arg A (zero_nsmul i).symm) ghas_one.one
| (n + 1) i a := cast (congr_arg A (succ_nsmul i n).symm) (ghas_mul.mul a $ gnpow_rec _ a)
@[simp] lemma gnpow_rec_zero (a : graded_monoid A) : graded_monoid.mk _ (gnpow_rec 0 a.snd) = 1 :=
sigma.ext (zero_nsmul _) (heq_of_cast_eq _ rfl).symm
/-- Tactic used to autofill `graded_monoid.gmonoid.gnpow_zero'` when the default
`graded_monoid.gmonoid.gnpow_rec` is used. -/
meta def apply_gnpow_rec_zero_tac : tactic unit := `[apply graded_monoid.gmonoid.gnpow_rec_zero]
@[simp] lemma gnpow_rec_succ (n : ℕ) (a : graded_monoid A) :
(graded_monoid.mk _ $ gnpow_rec n.succ a.snd) = a * ⟨_, gnpow_rec n a.snd⟩ :=
sigma.ext (succ_nsmul _ _) (heq_of_cast_eq _ rfl).symm
/-- Tactic used to autofill `graded_monoid.gmonoid.gnpow_succ'` when the default
`graded_monoid.gmonoid.gnpow_rec` is used. -/
meta def apply_gnpow_rec_succ_tac : tactic unit := `[apply graded_monoid.gmonoid.gnpow_rec_succ]
end gmonoid
/-- A graded version of `monoid`.
Like `monoid.npow`, this has an optional `gmonoid.gnpow` field to allow definitional control of
natural powers of a graded monoid. -/
class gmonoid [add_monoid ι] extends ghas_mul A, ghas_one A :=
(one_mul (a : graded_monoid A) : 1 * a = a)
(mul_one (a : graded_monoid A) : a * 1 = a)
(mul_assoc (a b c : graded_monoid A) : a * b * c = a * (b * c))
(gnpow : Π (n : ℕ) {i}, A i → A (n • i) := gmonoid.gnpow_rec)
(gnpow_zero' : Π (a : graded_monoid A), graded_monoid.mk _ (gnpow 0 a.snd) = 1
. gmonoid.apply_gnpow_rec_zero_tac)
(gnpow_succ' : Π (n : ℕ) (a : graded_monoid A),
(graded_monoid.mk _ $ gnpow n.succ a.snd) = a * ⟨_, gnpow n a.snd⟩
. gmonoid.apply_gnpow_rec_succ_tac)
/-- `gmonoid` implies a `monoid (graded_monoid A)`. -/
instance gmonoid.to_monoid [add_monoid ι] [gmonoid A] :
monoid (graded_monoid A) :=
{ one := (1), mul := (*),
npow := λ n a, graded_monoid.mk _ (gmonoid.gnpow n a.snd),
npow_zero' := λ a, gmonoid.gnpow_zero' a,
npow_succ' := λ n a, gmonoid.gnpow_succ' n a,
one_mul := gmonoid.one_mul, mul_one := gmonoid.mul_one, mul_assoc := gmonoid.mul_assoc }
lemma mk_pow [add_monoid ι] [gmonoid A] {i} (a : A i) (n : ℕ) :
mk i a ^ n = mk (n • i) (gmonoid.gnpow _ a) :=
begin
induction n with n,
{ rw [pow_zero],
exact (gmonoid.gnpow_zero' ⟨_, a⟩).symm, },
{ rw [pow_succ, n_ih, mk_mul_mk],
exact (gmonoid.gnpow_succ' n ⟨_, a⟩).symm, },
end
/-- A graded version of `comm_monoid`. -/
class gcomm_monoid [add_comm_monoid ι] extends gmonoid A :=
(mul_comm (a : graded_monoid A) (b : graded_monoid A) : a * b = b * a)
/-- `gcomm_monoid` implies a `comm_monoid (graded_monoid A)`, although this is only used as an
instance locally to define notation in `gmonoid` and similar typeclasses. -/
instance gcomm_monoid.to_comm_monoid [add_comm_monoid ι] [gcomm_monoid A] :
comm_monoid (graded_monoid A) :=
{ mul_comm := gcomm_monoid.mul_comm, ..gmonoid.to_monoid A }
end defs
/-! ### Instances for `A 0`
The various `g*` instances are enough to promote the `add_comm_monoid (A 0)` structure to various
types of multiplicative structure.
-/
section grade_zero
variables (A : ι → Type*)
section one
variables [has_zero ι] [ghas_one A]
/-- `1 : A 0` is the value provided in `ghas_one.one`. -/
@[nolint unused_arguments]
instance grade_zero.has_one : has_one (A 0) :=
⟨ghas_one.one⟩
end one
section mul
variables [add_zero_class ι] [ghas_mul A]
/-- `(•) : A 0 → A i → A i` is the value provided in `graded_monoid.ghas_mul.mul`, composed with
an `eq.rec` to turn `A (0 + i)` into `A i`.
-/
instance grade_zero.has_smul (i : ι) : has_smul (A 0) (A i) :=
{ smul := λ x y, (zero_add i).rec (ghas_mul.mul x y) }
/-- `(*) : A 0 → A 0 → A 0` is the value provided in `graded_monoid.ghas_mul.mul`, composed with
an `eq.rec` to turn `A (0 + 0)` into `A 0`.
-/
instance grade_zero.has_mul : has_mul (A 0) :=
{ mul := (•) }
variables {A}
@[simp] lemma mk_zero_smul {i} (a : A 0) (b : A i) : mk _ (a • b) = mk _ a * mk _ b :=
sigma.ext (zero_add _).symm $ eq_rec_heq _ _
@[simp] lemma grade_zero.smul_eq_mul (a b : A 0) : a • b = a * b := rfl
end mul
section monoid
variables [add_monoid ι] [gmonoid A]
instance : has_pow (A 0) ℕ :=
{ pow := λ x n, (nsmul_zero n).rec (gmonoid.gnpow n x : A (n • 0)) }
variables {A}
@[simp] lemma mk_zero_pow (a : A 0) (n : ℕ) : mk _ (a ^ n) = mk _ a ^ n :=
sigma.ext (nsmul_zero n).symm $ eq_rec_heq _ _
variables (A)
/-- The `monoid` structure derived from `gmonoid A`. -/
instance grade_zero.monoid : monoid (A 0) :=
function.injective.monoid (mk 0) sigma_mk_injective rfl mk_zero_smul mk_zero_pow
end monoid
section monoid
variables [add_comm_monoid ι] [gcomm_monoid A]
/-- The `comm_monoid` structure derived from `gcomm_monoid A`. -/
instance grade_zero.comm_monoid : comm_monoid (A 0) :=
function.injective.comm_monoid (mk 0) sigma_mk_injective rfl mk_zero_smul mk_zero_pow
end monoid
section mul_action
variables [add_monoid ι] [gmonoid A]
/-- `graded_monoid.mk 0` is a `monoid_hom`, using the `graded_monoid.grade_zero.monoid` structure.
-/
def mk_zero_monoid_hom : A 0 →* (graded_monoid A) :=
{ to_fun := mk 0, map_one' := rfl, map_mul' := mk_zero_smul }
/-- Each grade `A i` derives a `A 0`-action structure from `gmonoid A`. -/
instance grade_zero.mul_action {i} : mul_action (A 0) (A i) :=
begin
letI := mul_action.comp_hom (graded_monoid A) (mk_zero_monoid_hom A),
exact function.injective.mul_action (mk i) sigma_mk_injective mk_zero_smul,
end
end mul_action
end grade_zero
end graded_monoid
/-! ### Dependent products of graded elements -/
section dprod
variables {α : Type*} {A : ι → Type*} [add_monoid ι] [graded_monoid.gmonoid A]
/-- The index used by `list.dprod`. Propositionally this is equal to `(l.map fι).sum`, but
definitionally it needs to have a different form to avoid introducing `eq.rec`s in `list.dprod`. -/
def list.dprod_index (l : list α) (fι : α → ι) : ι :=
l.foldr (λ i b, fι i + b) 0
@[simp] lemma list.dprod_index_nil (fι : α → ι) : ([] : list α).dprod_index fι = 0 := rfl
@[simp] lemma list.dprod_index_cons (a : α) (l : list α) (fι : α → ι) :
(a :: l).dprod_index fι = fι a + l.dprod_index fι := rfl
lemma list.dprod_index_eq_map_sum (l : list α) (fι : α → ι) :
l.dprod_index fι = (l.map fι).sum :=
begin
dunfold list.dprod_index,
induction l,
{ simp, },
{ simp [l_ih], },
end
/-- A dependent product for graded monoids represented by the indexed family of types `A i`.
This is a dependent version of `(l.map fA).prod`.
For a list `l : list α`, this computes the product of `fA a` over `a`, where each `fA` is of type
`A (fι a)`. -/
def list.dprod (l : list α) (fι : α → ι) (fA : Π a, A (fι a)) :
A (l.dprod_index fι) :=
l.foldr_rec_on _ _ graded_monoid.ghas_one.one (λ i x a ha, graded_monoid.ghas_mul.mul (fA a) x)
@[simp] lemma list.dprod_nil (fι : α → ι) (fA : Π a, A (fι a)) :
(list.nil : list α).dprod fι fA = graded_monoid.ghas_one.one := rfl
-- the `( : _)` in this lemma statement results in the type on the RHS not being unfolded, which
-- is nicer in the goal view.
@[simp] lemma list.dprod_cons (fι : α → ι) (fA : Π a, A (fι a)) (a : α) (l : list α) :
(a :: l).dprod fι fA = (graded_monoid.ghas_mul.mul (fA a) (l.dprod fι fA) : _) := rfl
lemma graded_monoid.mk_list_dprod (l : list α) (fι : α → ι) (fA : Π a, A (fι a)) :
graded_monoid.mk _ (l.dprod fι fA) = (l.map (λ a, graded_monoid.mk (fι a) (fA a))).prod :=
begin
induction l,
{ simp, refl },
{ simp [←l_ih, graded_monoid.mk_mul_mk, list.prod_cons],
refl, },
end
/-- A variant of `graded_monoid.mk_list_dprod` for rewriting in the other direction. -/
lemma graded_monoid.list_prod_map_eq_dprod (l : list α) (f : α → graded_monoid A) :
(l.map f).prod = graded_monoid.mk _ (l.dprod (λ i, (f i).1) (λ i, (f i).2)) :=
begin
rw [graded_monoid.mk_list_dprod, graded_monoid.mk],
simp_rw sigma.eta,
end
lemma graded_monoid.list_prod_of_fn_eq_dprod {n : ℕ} (f : fin n → graded_monoid A) :
(list.of_fn f).prod =
graded_monoid.mk _ ((list.fin_range n).dprod (λ i, (f i).1) (λ i, (f i).2)) :=
by rw [list.of_fn_eq_map, graded_monoid.list_prod_map_eq_dprod]
end dprod
/-! ### Concrete instances -/
section
variables (ι) {R : Type*}
@[simps one]
instance has_one.ghas_one [has_zero ι] [has_one R] : graded_monoid.ghas_one (λ i : ι, R) :=
{ one := 1 }
@[simps mul]
instance has_mul.ghas_mul [has_add ι] [has_mul R] : graded_monoid.ghas_mul (λ i : ι, R) :=
{ mul := λ i j, (*) }
/-- If all grades are the same type and themselves form a monoid, then there is a trivial grading
structure. -/
@[simps gnpow]
instance monoid.gmonoid [add_monoid ι] [monoid R] : graded_monoid.gmonoid (λ i : ι, R) :=
{ one_mul := λ a, sigma.ext (zero_add _) (heq_of_eq (one_mul _)),
mul_one := λ a, sigma.ext (add_zero _) (heq_of_eq (mul_one _)),
mul_assoc := λ a b c, sigma.ext (add_assoc _ _ _) (heq_of_eq (mul_assoc _ _ _)),
gnpow := λ n i a, a ^ n,
gnpow_zero' := λ a, sigma.ext (zero_nsmul _) (heq_of_eq (monoid.npow_zero' _)),
gnpow_succ' := λ n ⟨i, a⟩, sigma.ext (succ_nsmul _ _) (heq_of_eq (monoid.npow_succ' _ _)),
..has_one.ghas_one ι,
..has_mul.ghas_mul ι }
/-- If all grades are the same type and themselves form a commutative monoid, then there is a
trivial grading structure. -/
instance comm_monoid.gcomm_monoid [add_comm_monoid ι] [comm_monoid R] :
graded_monoid.gcomm_monoid (λ i : ι, R) :=
{ mul_comm := λ a b, sigma.ext (add_comm _ _) (heq_of_eq (mul_comm _ _)),
..monoid.gmonoid ι }
/-- When all the indexed types are the same, the dependent product is just the regular product. -/
@[simp] lemma list.dprod_monoid {α} [add_monoid ι] [monoid R] (l : list α) (fι : α → ι)
(fA : α → R) :
(l.dprod fι fA : (λ i : ι, R) _) = ((l.map fA).prod : _) :=
begin
induction l,
{ rw [list.dprod_nil, list.map_nil, list.prod_nil], refl },
{ rw [list.dprod_cons, list.map_cons, list.prod_cons, l_ih], refl },
end
end
/-! ### Shorthands for creating instance of the above typeclasses for collections of subobjects -/
section subobjects
variables {R : Type*}
/-- A version of `graded_monoid.ghas_one` for internally graded objects. -/
class set_like.has_graded_one {S : Type*} [set_like S R] [has_one R] [has_zero ι]
(A : ι → S) : Prop :=
(one_mem : (1 : R) ∈ A 0)
lemma set_like.one_mem_graded {S : Type*} [set_like S R] [has_one R] [has_zero ι] (A : ι → S)
[set_like.has_graded_one A] : (1 : R) ∈ A 0 := set_like.has_graded_one.one_mem
instance set_like.ghas_one {S : Type*} [set_like S R] [has_one R] [has_zero ι] (A : ι → S)
[set_like.has_graded_one A] : graded_monoid.ghas_one (λ i, A i) :=
{ one := ⟨1, set_like.one_mem_graded _⟩ }
@[simp] lemma set_like.coe_ghas_one {S : Type*} [set_like S R] [has_one R] [has_zero ι] (A : ι → S)
[set_like.has_graded_one A] : ↑(@graded_monoid.ghas_one.one _ (λ i, A i) _ _) = (1 : R) := rfl
/-- A version of `graded_monoid.ghas_one` for internally graded objects. -/
class set_like.has_graded_mul {S : Type*} [set_like S R] [has_mul R] [has_add ι]
(A : ι → S) : Prop :=
(mul_mem : ∀ ⦃i j⦄ {gi gj}, gi ∈ A i → gj ∈ A j → gi * gj ∈ A (i + j))
lemma set_like.mul_mem_graded {S : Type*} [set_like S R] [has_mul R] [has_add ι] {A : ι → S}
[set_like.has_graded_mul A] ⦃i j⦄ {gi gj} (hi : gi ∈ A i) (hj : gj ∈ A j) :
gi * gj ∈ A (i + j) :=
set_like.has_graded_mul.mul_mem hi hj
instance set_like.ghas_mul {S : Type*} [set_like S R] [has_mul R] [has_add ι] (A : ι → S)
[set_like.has_graded_mul A] :
graded_monoid.ghas_mul (λ i, A i) :=
{ mul := λ i j a b, ⟨(a * b : R), set_like.mul_mem_graded a.prop b.prop⟩ }
@[simp] lemma set_like.coe_ghas_mul {S : Type*} [set_like S R] [has_mul R] [has_add ι] (A : ι → S)
[set_like.has_graded_mul A] {i j : ι} (x : A i) (y : A j) :
↑(@graded_monoid.ghas_mul.mul _ (λ i, A i) _ _ _ _ x y) = (x * y : R) := rfl
/-- A version of `graded_monoid.gmonoid` for internally graded objects. -/
class set_like.graded_monoid {S : Type*} [set_like S R] [monoid R] [add_monoid ι]
(A : ι → S) extends set_like.has_graded_one A, set_like.has_graded_mul A : Prop
namespace set_like
variables {S : Type*} [set_like S R] [monoid R] [add_monoid ι]
variables {A : ι → S} [set_like.graded_monoid A]
lemma pow_mem_graded (n : ℕ) {r : R} {i : ι} (h : r ∈ A i) : r ^ n ∈ A (n • i) :=
begin
induction n,
{ rw [pow_zero, zero_nsmul], exact one_mem_graded _ },
{ rw [pow_succ', succ_nsmul'], exact mul_mem_graded n_ih h },
end
lemma list_prod_map_mem_graded {ι'} (l : list ι') (i : ι' → ι) (r : ι' → R)
(h : ∀ j ∈ l, r j ∈ A (i j)) :
(l.map r).prod ∈ A (l.map i).sum :=
begin
induction l,
{ rw [list.map_nil, list.map_nil, list.prod_nil, list.sum_nil],
exact one_mem_graded _ },
{ rw [list.map_cons, list.map_cons, list.prod_cons, list.sum_cons],
exact mul_mem_graded
(h _ $ list.mem_cons_self _ _) (l_ih $ λ j hj, h _ $ list.mem_cons_of_mem _ hj) },
end
lemma list_prod_of_fn_mem_graded {n} (i : fin n → ι) (r : fin n → R) (h : ∀ j, r j ∈ A (i j)) :
(list.of_fn r).prod ∈ A (list.of_fn i).sum :=
begin
rw [list.of_fn_eq_map, list.of_fn_eq_map],
exact list_prod_map_mem_graded _ _ _ (λ _ _, h _),
end
end set_like
/-- Build a `gmonoid` instance for a collection of subobjects. -/
instance set_like.gmonoid {S : Type*} [set_like S R] [monoid R] [add_monoid ι] (A : ι → S)
[set_like.graded_monoid A] :
graded_monoid.gmonoid (λ i, A i) :=
{ one_mul := λ ⟨i, a, h⟩, sigma.subtype_ext (zero_add _) (one_mul _),
mul_one := λ ⟨i, a, h⟩, sigma.subtype_ext (add_zero _) (mul_one _),
mul_assoc := λ ⟨i, a, ha⟩ ⟨j, b, hb⟩ ⟨k, c, hc⟩,
sigma.subtype_ext (add_assoc _ _ _) (mul_assoc _ _ _),
gnpow := λ n i a, ⟨a ^ n, set_like.pow_mem_graded n a.prop⟩,
gnpow_zero' := λ n, sigma.subtype_ext (zero_nsmul _) (pow_zero _),
gnpow_succ' := λ n a, sigma.subtype_ext (succ_nsmul _ _) (pow_succ _ _),
..set_like.ghas_one A,
..set_like.ghas_mul A }
@[simp] lemma set_like.coe_gnpow {S : Type*} [set_like S R] [monoid R] [add_monoid ι] (A : ι → S)
[set_like.graded_monoid A] {i : ι} (x : A i) (n : ℕ) :
↑(@graded_monoid.gmonoid.gnpow _ (λ i, A i) _ _ n _ x) = (x ^ n : R) := rfl
/-- Build a `gcomm_monoid` instance for a collection of subobjects. -/
instance set_like.gcomm_monoid {S : Type*} [set_like S R] [comm_monoid R] [add_comm_monoid ι]
(A : ι → S) [set_like.graded_monoid A] :
graded_monoid.gcomm_monoid (λ i, A i) :=
{ mul_comm := λ ⟨i, a, ha⟩ ⟨j, b, hb⟩, sigma.subtype_ext (add_comm _ _) (mul_comm _ _),
..set_like.gmonoid A}
section dprod
open set_like set_like.graded_monoid
variables {α S : Type*} [set_like S R] [monoid R] [add_monoid ι]
/-- Coercing a dependent product of subtypes is the same as taking the regular product of the
coercions. -/
@[simp] lemma set_like.coe_list_dprod (A : ι → S) [set_like.graded_monoid A]
(fι : α → ι) (fA : Π a, A (fι a)) (l : list α) :
↑(l.dprod fι fA : (λ i, ↥(A i)) _) = (list.prod (l.map (λ a, fA a)) : R) :=
begin
induction l,
{ rw [list.dprod_nil, coe_ghas_one, list.map_nil, list.prod_nil] },
{ rw [list.dprod_cons, coe_ghas_mul, list.map_cons, list.prod_cons, l_ih], },
end
include R
/-- A version of `list.coe_dprod_set_like` with `subtype.mk`. -/
lemma set_like.list_dprod_eq (A : ι → S) [set_like.graded_monoid A]
(fι : α → ι) (fA : Π a, A (fι a)) (l : list α) :
(l.dprod fι fA : (λ i, ↥(A i)) _) =
⟨list.prod (l.map (λ a, fA a)), (l.dprod_index_eq_map_sum fι).symm ▸
list_prod_map_mem_graded l _ _ (λ i hi, (fA i).prop)⟩ :=
subtype.ext $ set_like.coe_list_dprod _ _ _ _
end dprod
end subobjects
section homogeneous_elements
variables {R S : Type*} [set_like S R]
/-- An element `a : R` is said to be homogeneous if there is some `i : ι` such that `a ∈ A i`. -/
def set_like.is_homogeneous (A : ι → S) (a : R) : Prop := ∃ i, a ∈ A i
@[simp] lemma set_like.is_homogeneous_coe {A : ι → S} {i} (x : A i) :
set_like.is_homogeneous A (x : R) :=
⟨i, x.prop⟩
lemma set_like.is_homogeneous_one [has_zero ι] [has_one R]
(A : ι → S) [set_like.has_graded_one A] : set_like.is_homogeneous A (1 : R) :=
⟨0, set_like.one_mem_graded _⟩
lemma set_like.is_homogeneous.mul [has_add ι] [has_mul R] {A : ι → S}
[set_like.has_graded_mul A] {a b : R} :
set_like.is_homogeneous A a → set_like.is_homogeneous A b → set_like.is_homogeneous A (a * b)
| ⟨i, hi⟩ ⟨j, hj⟩ := ⟨i + j, set_like.mul_mem_graded hi hj⟩
/-- When `A` is a `set_like.graded_monoid A`, then the homogeneous elements forms a submonoid. -/
def set_like.homogeneous_submonoid [add_monoid ι] [monoid R]
(A : ι → S) [set_like.graded_monoid A] : submonoid R :=
{ carrier := { a | set_like.is_homogeneous A a },
one_mem' := set_like.is_homogeneous_one A,
mul_mem' := λ a b, set_like.is_homogeneous.mul }
end homogeneous_elements
|
23990ebf1082008ac150203d5c21ddf4f3068b3e | c777c32c8e484e195053731103c5e52af26a25d1 | /src/topology/instances/complex.lean | bf183b83e7a8871bc7adc17df545b1be82a68934 | [
"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 | 4,779 | lean | /-
Copyright (c) 2022 Xavier Roblot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Xavier Roblot
-/
import analysis.complex.basic
import field_theory.intermediate_field
import topology.algebra.uniform_ring
/-!
# Some results about the topology of ℂ
-/
section complex_subfield
open complex set
open_locale complex_conjugate
/-- The only closed subfields of `ℂ` are `ℝ` and `ℂ`. -/
lemma complex.subfield_eq_of_closed {K : subfield ℂ} (hc : is_closed (K : set ℂ)) :
K = of_real.field_range ∨ K = ⊤ :=
begin
suffices : range (coe : ℝ → ℂ) ⊆ K,
{ rw [range_subset_iff, ← coe_algebra_map] at this,
have := (subalgebra.is_simple_order_of_finrank finrank_real_complex).eq_bot_or_eq_top
(subfield.to_intermediate_field K this).to_subalgebra,
simp_rw ← set_like.coe_set_eq at this ⊢,
convert this using 2,
simpa only [ring_hom.coe_field_range, algebra.coe_bot, coe_algebra_map], },
suffices : range (coe : ℝ → ℂ) ⊆ closure (set.range ((coe : ℝ → ℂ) ∘ (coe : ℚ → ℝ))),
{ refine subset_trans this _,
rw ← is_closed.closure_eq hc,
apply closure_mono,
rintros _ ⟨_, rfl⟩,
simp only [function.comp_app, of_real_rat_cast, set_like.mem_coe, subfield_class.coe_rat_mem] },
nth_rewrite 1 range_comp,
refine subset_trans _ (image_closure_subset_closure_image continuous_of_real),
rw dense_range.closure_range rat.dense_embedding_coe_real.dense,
simp only [image_univ],
end
/-- Let `K` a subfield of `ℂ` and let `ψ : K →+* ℂ` a ring homomorphism. Assume that `ψ` is uniform
continuous, then `ψ` is either the inclusion map or the composition of the inclusion map with the
complex conjugation. -/
lemma complex.uniform_continuous_ring_hom_eq_id_or_conj (K : subfield ℂ) {ψ : K →+* ℂ}
(hc : uniform_continuous ψ) : ψ.to_fun = K.subtype ∨ ψ.to_fun = conj ∘ K.subtype :=
begin
letI : topological_division_ring ℂ := topological_division_ring.mk,
letI : topological_ring K.topological_closure :=
subring.topological_ring K.topological_closure.to_subring,
set ι : K → K.topological_closure := subfield.inclusion K.le_topological_closure,
have ui : uniform_inducing ι :=
⟨ by { erw [uniformity_subtype, uniformity_subtype, filter.comap_comap], congr, } ⟩,
let di := ui.dense_inducing _,
{ -- extψ : closure(K) →+* ℂ is the extension of ψ : K →+* ℂ
let extψ := dense_inducing.extend_ring_hom ui di.dense hc,
haveI := (uniform_continuous_uniformly_extend ui di.dense hc).continuous,
cases complex.subfield_eq_of_closed (subfield.is_closed_topological_closure K),
{ left,
let j := ring_equiv.subfield_congr h,
-- ψ₁ is the continuous ring hom `ℝ →+* ℂ` constructed from `j : closure (K) ≃+* ℝ`
-- and `extψ : closure (K) →+* ℂ`
let ψ₁ := ring_hom.comp extψ (ring_hom.comp j.symm.to_ring_hom of_real.range_restrict),
ext1 x,
rsuffices ⟨r, hr⟩ : ∃ r : ℝ, of_real.range_restrict r = j (ι x),
{ have := ring_hom.congr_fun
(ring_hom_eq_of_real_of_continuous (by continuity! : continuous ψ₁)) r,
rw [ring_hom.comp_apply, ring_hom.comp_apply, hr, ring_equiv.to_ring_hom_eq_coe] at this,
convert this using 1,
{ exact (dense_inducing.extend_eq di hc.continuous _).symm, },
{ rw [← of_real.coe_range_restrict, hr], refl, }},
obtain ⟨r, hr⟩ := set_like.coe_mem (j (ι x)),
exact ⟨r, subtype.ext hr⟩, },
{ -- ψ₁ is the continuous ring hom `ℂ →+* ℂ` constructed from `closure (K) ≃+* ℂ`
-- and `extψ : closure (K) →+* ℂ`
let ψ₁ := ring_hom.comp extψ (ring_hom.comp (ring_equiv.subfield_congr h).symm.to_ring_hom
(@subfield.top_equiv ℂ _).symm.to_ring_hom),
cases ring_hom_eq_id_or_conj_of_continuous (by continuity! : continuous ψ₁) with h h,
{ left, ext1 z,
convert (ring_hom.congr_fun h z) using 1,
exact (dense_inducing.extend_eq di hc.continuous z).symm, },
{ right, ext1 z,
convert (ring_hom.congr_fun h z) using 1,
exact (dense_inducing.extend_eq di hc.continuous z).symm, }}},
{ let j : { x // x ∈ closure (id '' {x | (K : set ℂ) x })} → (K.topological_closure : set ℂ) :=
λ x, ⟨x, by { convert x.prop, simpa only [id.def, set.image_id'], }⟩,
convert dense_range.comp (function.surjective.dense_range _)
(dense_embedding.subtype (dense_embedding_id) (K : set ℂ)).dense
(by continuity : continuous j),
rintros ⟨y, hy⟩,
use ⟨y, by { convert hy, simpa only [id.def, set.image_id'], }⟩,
simp only [subtype.mk_eq_mk, subtype.coe_mk], }
end
end complex_subfield
|
b65d2147ff9674e9fd2f9021b51edcc96d6ed0e9 | 626e312b5c1cb2d88fca108f5933076012633192 | /src/ring_theory/ideal/operations.lean | b0e25c9498fe6198fb82e30c3aa6f33dd7f007a4 | [
"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 | 74,113 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.algebra.operations
import algebra.algebra.tower
import data.equiv.ring
import data.nat.choose.sum
import ring_theory.ideal.basic
import ring_theory.non_zero_divisors
/-!
# More operations on modules and ideals
-/
universes u v w x
open_locale big_operators pointwise
namespace submodule
variables {R : Type u} {M : Type v}
variables [comm_ring R] [add_comm_group M] [module R M]
instance has_scalar' : has_scalar (ideal R) (submodule R M) :=
⟨λ I N, ⨆ r : I, N.map (r.1 • linear_map.id)⟩
/-- `N.annihilator` is the ideal of all elements `r : R` such that `r • N = 0`. -/
def annihilator (N : submodule R M) : ideal R :=
(linear_map.lsmul R N).ker
/-- `N.colon P` is the ideal of all elements `r : R` such that `r • P ⊆ N`. -/
def colon (N P : submodule R M) : ideal R :=
annihilator (P.map N.mkq)
variables {I J : ideal R} {N N₁ N₂ P P₁ P₂ : submodule R M}
theorem mem_annihilator {r} : r ∈ N.annihilator ↔ ∀ n ∈ N, r • n = (0:M) :=
⟨λ hr n hn, congr_arg subtype.val (linear_map.ext_iff.1 (linear_map.mem_ker.1 hr) ⟨n, hn⟩),
λ h, linear_map.mem_ker.2 $ linear_map.ext $ λ n, subtype.eq $ h n.1 n.2⟩
theorem mem_annihilator' {r} : r ∈ N.annihilator ↔ N ≤ comap (r • linear_map.id) ⊥ :=
mem_annihilator.trans ⟨λ H n hn, (mem_bot R).2 $ H n hn, λ H n hn, (mem_bot R).1 $ H hn⟩
theorem annihilator_bot : (⊥ : submodule R M).annihilator = ⊤ :=
(ideal.eq_top_iff_one _).2 $ mem_annihilator'.2 bot_le
theorem annihilator_eq_top_iff : N.annihilator = ⊤ ↔ N = ⊥ :=
⟨λ H, eq_bot_iff.2 $ λ (n:M) hn, (mem_bot R).2 $
one_smul R n ▸ mem_annihilator.1 ((ideal.eq_top_iff_one _).1 H) n hn,
λ H, H.symm ▸ annihilator_bot⟩
theorem annihilator_mono (h : N ≤ P) : P.annihilator ≤ N.annihilator :=
λ r hrp, mem_annihilator.2 $ λ n hn, mem_annihilator.1 hrp n $ h hn
theorem annihilator_supr (ι : Sort w) (f : ι → submodule R M) :
(annihilator ⨆ i, f i) = ⨅ i, annihilator (f i) :=
le_antisymm (le_infi $ λ i, annihilator_mono $ le_supr _ _)
(λ r H, mem_annihilator'.2 $ supr_le $ λ i,
have _ := (mem_infi _).1 H i, mem_annihilator'.1 this)
theorem mem_colon {r} : r ∈ N.colon P ↔ ∀ p ∈ P, r • p ∈ N :=
mem_annihilator.trans ⟨λ H p hp, (quotient.mk_eq_zero N).1 (H (quotient.mk p) (mem_map_of_mem hp)),
λ H m ⟨p, hp, hpm⟩, hpm ▸ (N.mkq).map_smul r p ▸ (quotient.mk_eq_zero N).2 $ H p hp⟩
theorem mem_colon' {r} : r ∈ N.colon P ↔ P ≤ comap (r • linear_map.id) N :=
mem_colon
theorem colon_mono (hn : N₁ ≤ N₂) (hp : P₁ ≤ P₂) : N₁.colon P₂ ≤ N₂.colon P₁ :=
λ r hrnp, mem_colon.2 $ λ p₁ hp₁, hn $ mem_colon.1 hrnp p₁ $ hp hp₁
theorem infi_colon_supr (ι₁ : Sort w) (f : ι₁ → submodule R M)
(ι₂ : Sort x) (g : ι₂ → submodule R M) :
(⨅ i, f i).colon (⨆ j, g j) = ⨅ i j, (f i).colon (g j) :=
le_antisymm (le_infi $ λ i, le_infi $ λ j, colon_mono (infi_le _ _) (le_supr _ _))
(λ r H, mem_colon'.2 $ supr_le $ λ j, map_le_iff_le_comap.1 $ le_infi $ λ i,
map_le_iff_le_comap.2 $ mem_colon'.1 $ have _ := ((mem_infi _).1 H i),
have _ := ((mem_infi _).1 this j), this)
theorem smul_mem_smul {r} {n} (hr : r ∈ I) (hn : n ∈ N) : r • n ∈ I • N :=
(le_supr _ ⟨r, hr⟩ : _ ≤ I • N) ⟨n, hn, rfl⟩
theorem smul_le {P : submodule R M} : I • N ≤ P ↔ ∀ (r ∈ I) (n ∈ N), r • n ∈ P :=
⟨λ H r hr n hn, H $ smul_mem_smul hr hn,
λ H, supr_le $ λ r, map_le_iff_le_comap.2 $ λ n hn, H r.1 r.2 n hn⟩
@[elab_as_eliminator]
theorem smul_induction_on {p : M → Prop} {x} (H : x ∈ I • N)
(Hb : ∀ (r ∈ I) (n ∈ N), p (r • n)) (H0 : p 0)
(H1 : ∀ x y, p x → p y → p (x + y))
(H2 : ∀ (c:R) n, p n → p (c • n)) : p x :=
(@smul_le _ _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hb H
theorem mem_smul_span_singleton {I : ideal R} {m : M} {x : M} :
x ∈ I • span R ({m} : set M) ↔ ∃ y ∈ I, y • m = x :=
⟨λ hx, smul_induction_on hx
(λ r hri n hnm,
let ⟨s, hs⟩ := mem_span_singleton.1 hnm in ⟨r * s, I.mul_mem_right _ hri, hs ▸ mul_smul r s m⟩)
⟨0, I.zero_mem, by rw [zero_smul]⟩
(λ m1 m2 ⟨y1, hyi1, hy1⟩ ⟨y2, hyi2, hy2⟩,
⟨y1 + y2, I.add_mem hyi1 hyi2, by rw [add_smul, hy1, hy2]⟩)
(λ c r ⟨y, hyi, hy⟩, ⟨c * y, I.mul_mem_left _ hyi, by rw [mul_smul, hy]⟩),
λ ⟨y, hyi, hy⟩, hy ▸ smul_mem_smul hyi (subset_span $ set.mem_singleton m)⟩
theorem smul_le_right : I • N ≤ N :=
smul_le.2 $ λ r hr n, N.smul_mem r
theorem smul_mono (hij : I ≤ J) (hnp : N ≤ P) : I • N ≤ J • P :=
smul_le.2 $ λ r hr n hn, smul_mem_smul (hij hr) (hnp hn)
theorem smul_mono_left (h : I ≤ J) : I • N ≤ J • N :=
smul_mono h (le_refl N)
theorem smul_mono_right (h : N ≤ P) : I • N ≤ I • P :=
smul_mono (le_refl I) h
variables (I J N P)
@[simp] theorem smul_bot : I • (⊥ : submodule R M) = ⊥ :=
eq_bot_iff.2 $ smul_le.2 $ λ r hri s hsb,
(submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hsb).symm ▸ smul_zero r
@[simp] theorem bot_smul : (⊥ : ideal R) • N = ⊥ :=
eq_bot_iff.2 $ smul_le.2 $ λ r hrb s hsi,
(submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hrb).symm ▸ zero_smul _ s
@[simp] theorem top_smul : (⊤ : ideal R) • N = N :=
le_antisymm smul_le_right $ λ r hri, one_smul R r ▸ smul_mem_smul mem_top hri
theorem smul_sup : I • (N ⊔ P) = I • N ⊔ I • P :=
le_antisymm (smul_le.2 $ λ r hri m hmnp, let ⟨n, hn, p, hp, hnpm⟩ := mem_sup.1 hmnp in
mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hri hp, hnpm ▸ (smul_add _ _ _).symm⟩)
(sup_le (smul_mono_right le_sup_left)
(smul_mono_right le_sup_right))
theorem sup_smul : (I ⊔ J) • N = I • N ⊔ J • N :=
le_antisymm (smul_le.2 $ λ r hrij n hn, let ⟨ri, hri, rj, hrj, hrijr⟩ := mem_sup.1 hrij in
mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hrj hn, hrijr ▸ (add_smul _ _ _).symm⟩)
(sup_le (smul_mono_left le_sup_left)
(smul_mono_left le_sup_right))
protected theorem smul_assoc : (I • J) • N = I • (J • N) :=
le_antisymm (smul_le.2 $ λ rs hrsij t htn,
smul_induction_on hrsij
(λ r hr s hs,
(@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ smul_mem_smul hr (smul_mem_smul hs htn))
((zero_smul R t).symm ▸ submodule.zero_mem _)
(λ x y, (add_smul x y t).symm ▸ submodule.add_mem _)
(λ r s h, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ submodule.smul_mem _ _ h))
(smul_le.2 $ λ r hr sn hsn, suffices J • N ≤ submodule.comap (r • linear_map.id) ((I • J) • N),
from this hsn,
smul_le.2 $ λ s hs n hn, show r • (s • n) ∈ (I • J) • N,
from mul_smul r s n ▸ smul_mem_smul (smul_mem_smul hr hs) hn)
variables (S : set R) (T : set M)
theorem span_smul_span : (ideal.span S) • (span R T) =
span R (⋃ (s ∈ S) (t ∈ T), {s • t}) :=
le_antisymm (smul_le.2 $ λ r hrS n hnT, span_induction hrS
(λ r hrS, span_induction hnT
(λ n hnT, subset_span $ set.mem_bUnion hrS $
set.mem_bUnion hnT $ set.mem_singleton _)
((smul_zero r : r • 0 = (0:M)).symm ▸ submodule.zero_mem _)
(λ x y, (smul_add r x y).symm ▸ submodule.add_mem _)
(λ c m, by rw [smul_smul, mul_comm, mul_smul]; exact submodule.smul_mem _ _))
((zero_smul R n).symm ▸ submodule.zero_mem _)
(λ r s, (add_smul r s n).symm ▸ submodule.add_mem _)
(λ c r, by rw [smul_eq_mul, mul_smul]; exact submodule.smul_mem _ _)) $
span_le.2 $ set.bUnion_subset $ λ r hrS, set.bUnion_subset $ λ n hnT, set.singleton_subset_iff.2 $
smul_mem_smul (subset_span hrS) (subset_span hnT)
variables {M' : Type w} [add_comm_group M'] [module R M']
theorem map_smul'' (f : M →ₗ[R] M') : (I • N).map f = I • N.map f :=
le_antisymm (map_le_iff_le_comap.2 $ smul_le.2 $ λ r hr n hn, show f (r • n) ∈ I • N.map f,
from (f.map_smul r n).symm ▸ smul_mem_smul hr (mem_map_of_mem hn)) $
smul_le.2 $ λ r hr n hn, let ⟨p, hp, hfp⟩ := mem_map.1 hn in
hfp ▸ f.map_smul r p ▸ mem_map_of_mem (smul_mem_smul hr hp)
end submodule
namespace ideal
section chinese_remainder
variables {R : Type u} [comm_ring R] {ι : Type v}
theorem exists_sub_one_mem_and_mem (s : finset ι) {f : ι → ideal R}
(hf : ∀ i ∈ s, ∀ j ∈ s, i ≠ j → f i ⊔ f j = ⊤) (i : ι) (his : i ∈ s) :
∃ r : R, r - 1 ∈ f i ∧ ∀ j ∈ s, j ≠ i → r ∈ f j :=
begin
have : ∀ j ∈ s, j ≠ i → ∃ r : R, ∃ H : r - 1 ∈ f i, r ∈ f j,
{ intros j hjs hji, specialize hf i his j hjs hji.symm,
rw [eq_top_iff_one, submodule.mem_sup] at hf,
rcases hf with ⟨r, hri, s, hsj, hrs⟩, refine ⟨1 - r, _, _⟩,
{ rw [sub_right_comm, sub_self, zero_sub], exact (f i).neg_mem hri },
{ rw [← hrs, add_sub_cancel'], exact hsj } },
classical,
have : ∃ g : ι → R, (∀ j, g j - 1 ∈ f i) ∧ ∀ j ∈ s, j ≠ i → g j ∈ f j,
{ choose g hg1 hg2,
refine ⟨λ j, if H : j ∈ s ∧ j ≠ i then g j H.1 H.2 else 1, λ j, _, λ j, _⟩,
{ split_ifs with h, { apply hg1 }, rw sub_self, exact (f i).zero_mem },
{ intros hjs hji, rw dif_pos, { apply hg2 }, exact ⟨hjs, hji⟩ } },
rcases this with ⟨g, hgi, hgj⟩, use (∏ x in s.erase i, g x), split,
{ rw [← quotient.eq, ring_hom.map_one, ring_hom.map_prod],
apply finset.prod_eq_one, intros, rw [← ring_hom.map_one, quotient.eq], apply hgi },
intros j hjs hji, rw [← quotient.eq_zero_iff_mem, ring_hom.map_prod],
refine finset.prod_eq_zero (finset.mem_erase_of_ne_of_mem hji hjs) _,
rw quotient.eq_zero_iff_mem, exact hgj j hjs hji
end
theorem exists_sub_mem [fintype ι] {f : ι → ideal R}
(hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) (g : ι → R) :
∃ r : R, ∀ i, r - g i ∈ f i :=
begin
have : ∃ φ : ι → R, (∀ i, φ i - 1 ∈ f i) ∧ (∀ i j, i ≠ j → φ i ∈ f j),
{ have := exists_sub_one_mem_and_mem (finset.univ : finset ι) (λ i _ j _ hij, hf i j hij),
choose φ hφ,
existsi λ i, φ i (finset.mem_univ i),
exact ⟨λ i, (hφ i _).1, λ i j hij, (hφ i _).2 j (finset.mem_univ j) hij.symm⟩ },
rcases this with ⟨φ, hφ1, hφ2⟩,
use ∑ i, g i * φ i,
intros i,
rw [← quotient.eq, ring_hom.map_sum],
refine eq.trans (finset.sum_eq_single i _ _) _,
{ intros j _ hji, rw quotient.eq_zero_iff_mem, exact (f i).mul_mem_left _ (hφ2 j i hji) },
{ intros hi, exact (hi $ finset.mem_univ i).elim },
specialize hφ1 i, rw [← quotient.eq, ring_hom.map_one] at hφ1,
rw [ring_hom.map_mul, hφ1, mul_one]
end
/-- The homomorphism from `R/(⋂ i, f i)` to `∏ i, (R / f i)` featured in the Chinese
Remainder Theorem. It is bijective if the ideals `f i` are comaximal. -/
def quotient_inf_to_pi_quotient (f : ι → ideal R) :
(⨅ i, f i).quotient →+* Π i, (f i).quotient :=
quotient.lift (⨅ i, f i)
(pi.ring_hom (λ i : ι, (quotient.mk (f i) : _))) $
λ r hr, begin
rw submodule.mem_infi at hr,
ext i,
exact quotient.eq_zero_iff_mem.2 (hr i)
end
theorem quotient_inf_to_pi_quotient_bijective [fintype ι] {f : ι → ideal R}
(hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) :
function.bijective (quotient_inf_to_pi_quotient f) :=
⟨λ x y, quotient.induction_on₂' x y $ λ r s hrs, quotient.eq.2 $
(submodule.mem_infi _).2 $ λ i, quotient.eq.1 $
show quotient_inf_to_pi_quotient f (quotient.mk' r) i = _, by rw hrs; refl,
λ g, let ⟨r, hr⟩ := exists_sub_mem hf (λ i, quotient.out' (g i)) in
⟨quotient.mk _ r, funext $ λ i, quotient.out_eq' (g i) ▸ quotient.eq.2 (hr i)⟩⟩
/-- Chinese Remainder Theorem. Eisenbud Ex.2.6. Similar to Atiyah-Macdonald 1.10 and Stacks 00DT -/
noncomputable def quotient_inf_ring_equiv_pi_quotient [fintype ι] (f : ι → ideal R)
(hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) :
(⨅ i, f i).quotient ≃+* Π i, (f i).quotient :=
{ .. equiv.of_bijective _ (quotient_inf_to_pi_quotient_bijective hf),
.. quotient_inf_to_pi_quotient f }
end chinese_remainder
section mul_and_radical
variables {R : Type u} {ι : Type*} [comm_ring R]
variables {I J K L : ideal R}
instance : has_mul (ideal R) := ⟨(•)⟩
@[simp] lemma add_eq_sup : I + J = I ⊔ J := rfl
@[simp] lemma zero_eq_bot : (0 : ideal R) = ⊥ := rfl
@[simp] lemma one_eq_top : (1 : ideal R) = ⊤ :=
by erw [submodule.one_eq_range, linear_map.range_id]
theorem mul_mem_mul {r s} (hr : r ∈ I) (hs : s ∈ J) : r * s ∈ I * J :=
submodule.smul_mem_smul hr hs
theorem mul_mem_mul_rev {r s} (hr : r ∈ I) (hs : s ∈ J) : s * r ∈ I * J :=
mul_comm r s ▸ mul_mem_mul hr hs
lemma pow_mem_pow {x : R} (hx : x ∈ I) (n : ℕ) : x ^ n ∈ I ^ n :=
begin
induction n with n ih, { simp only [pow_zero, ideal.one_eq_top], },
simpa only [pow_succ] using mul_mem_mul hx ih,
end
theorem mul_le : I * J ≤ K ↔ ∀ (r ∈ I) (s ∈ J), r * s ∈ K :=
submodule.smul_le
lemma mul_le_left : I * J ≤ J :=
ideal.mul_le.2 (λ r hr s, J.mul_mem_left _)
lemma mul_le_right : I * J ≤ I :=
ideal.mul_le.2 (λ r hr s hs, I.mul_mem_right _ hr)
@[simp] lemma sup_mul_right_self : I ⊔ (I * J) = I :=
sup_eq_left.2 ideal.mul_le_right
@[simp] lemma sup_mul_left_self : I ⊔ (J * I) = I :=
sup_eq_left.2 ideal.mul_le_left
@[simp] lemma mul_right_self_sup : (I * J) ⊔ I = I :=
sup_eq_right.2 ideal.mul_le_right
@[simp] lemma mul_left_self_sup : (J * I) ⊔ I = I :=
sup_eq_right.2 ideal.mul_le_left
variables (I J K)
protected theorem mul_comm : I * J = J * I :=
le_antisymm (mul_le.2 $ λ r hrI s hsJ, mul_mem_mul_rev hsJ hrI)
(mul_le.2 $ λ r hrJ s hsI, mul_mem_mul_rev hsI hrJ)
protected theorem mul_assoc : (I * J) * K = I * (J * K) :=
submodule.smul_assoc I J K
theorem span_mul_span (S T : set R) : span S * span T =
span ⋃ (s ∈ S) (t ∈ T), {s * t} :=
submodule.span_smul_span S T
variables {I J K}
lemma span_mul_span' (S T : set R) : span S * span T = span (S*T) :=
by { unfold span, rw submodule.span_mul_span, }
lemma span_singleton_mul_span_singleton (r s : R) :
span {r} * span {s} = (span {r * s} : ideal R) :=
by { unfold span, rw [submodule.span_mul_span, set.singleton_mul_singleton], }
lemma span_singleton_pow (s : R) (n : ℕ):
span {s} ^ n = (span {s ^ n} : ideal R) :=
begin
induction n with n ih, { simp [set.singleton_one], },
simp only [pow_succ, ih, span_singleton_mul_span_singleton],
end
lemma mem_mul_span_singleton {x y : R} {I : ideal R} :
x ∈ I * span {y} ↔ ∃ z ∈ I, z * y = x :=
submodule.mem_smul_span_singleton
lemma mem_span_singleton_mul {x y : R} {I : ideal R} :
x ∈ span {y} * I ↔ ∃ z ∈ I, y * z = x :=
by simp only [mul_comm, mem_mul_span_singleton]
lemma le_span_singleton_mul_iff {x : R} {I J : ideal R} :
I ≤ span {x} * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI :=
show (∀ {zI} (hzI : zI ∈ I), zI ∈ span {x} * J) ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI,
by simp only [mem_span_singleton_mul]
lemma span_singleton_mul_le_iff {x : R} {I J : ideal R} :
span {x} * I ≤ J ↔ ∀ z ∈ I, x * z ∈ J :=
begin
simp only [mul_le, mem_span_singleton_mul, mem_span_singleton],
split,
{ intros h zI hzI,
exact h x (dvd_refl x) zI hzI },
{ rintros h _ ⟨z, rfl⟩ zI hzI,
rw [mul_comm x z, mul_assoc],
exact J.mul_mem_left _ (h zI hzI) },
end
lemma span_singleton_mul_le_span_singleton_mul {x y : R} {I J : ideal R} :
span {x} * I ≤ span {y} * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zI = y * zJ :=
by simp only [span_singleton_mul_le_iff, mem_span_singleton_mul, eq_comm]
lemma eq_span_singleton_mul {x : R} (I J : ideal R) :
I = span {x} * J ↔ ((∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI) ∧ (∀ z ∈ J, x * z ∈ I)) :=
by simp only [le_antisymm_iff, le_span_singleton_mul_iff, span_singleton_mul_le_iff]
lemma span_singleton_mul_eq_span_singleton_mul {x y : R} (I J : ideal R) :
span {x} * I = span {y} * J ↔
((∀ zI ∈ I, ∃ zJ ∈ J, x * zI = y * zJ) ∧
(∀ zJ ∈ J, ∃ zI ∈ I, x * zI = y * zJ)) :=
by simp only [le_antisymm_iff, span_singleton_mul_le_span_singleton_mul, eq_comm]
theorem mul_le_inf : I * J ≤ I ⊓ J :=
mul_le.2 $ λ r hri s hsj, ⟨I.mul_mem_right s hri, J.mul_mem_left r hsj⟩
theorem multiset_prod_le_inf {s : multiset (ideal R)} :
s.prod ≤ s.inf :=
begin
classical, refine s.induction_on _ _,
{ rw [multiset.inf_zero], exact le_top },
intros a s ih,
rw [multiset.prod_cons, multiset.inf_cons],
exact le_trans mul_le_inf (inf_le_inf (le_refl _) ih)
end
theorem prod_le_inf {s : finset ι} {f : ι → ideal R} : s.prod f ≤ s.inf f :=
multiset_prod_le_inf
theorem mul_eq_inf_of_coprime (h : I ⊔ J = ⊤) : I * J = I ⊓ J :=
le_antisymm mul_le_inf $ λ r ⟨hri, hrj⟩,
let ⟨s, hsi, t, htj, hst⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in
mul_one r ▸ hst ▸ (mul_add r s t).symm ▸ ideal.add_mem (I * J) (mul_mem_mul_rev hsi hrj)
(mul_mem_mul hri htj)
variables (I)
theorem mul_bot : I * ⊥ = ⊥ :=
submodule.smul_bot I
theorem bot_mul : ⊥ * I = ⊥ :=
submodule.bot_smul I
theorem mul_top : I * ⊤ = I :=
ideal.mul_comm ⊤ I ▸ submodule.top_smul I
theorem top_mul : ⊤ * I = I :=
submodule.top_smul I
variables {I}
theorem mul_mono (hik : I ≤ K) (hjl : J ≤ L) : I * J ≤ K * L :=
submodule.smul_mono hik hjl
theorem mul_mono_left (h : I ≤ J) : I * K ≤ J * K :=
submodule.smul_mono_left h
theorem mul_mono_right (h : J ≤ K) : I * J ≤ I * K :=
submodule.smul_mono_right h
variables (I J K)
theorem mul_sup : I * (J ⊔ K) = I * J ⊔ I * K :=
submodule.smul_sup I J K
theorem sup_mul : (I ⊔ J) * K = I * K ⊔ J * K :=
submodule.sup_smul I J K
variables {I J K}
lemma pow_le_pow {m n : ℕ} (h : m ≤ n) :
I^n ≤ I^m :=
begin
cases nat.exists_eq_add_of_le h with k hk,
rw [hk, pow_add],
exact le_trans (mul_le_inf) (inf_le_left)
end
lemma mul_eq_bot {R : Type*} [integral_domain R] {I J : ideal R} :
I * J = ⊥ ↔ I = ⊥ ∨ J = ⊥ :=
⟨λ hij, or_iff_not_imp_left.mpr (λ I_ne_bot, J.eq_bot_iff.mpr (λ j hj,
let ⟨i, hi, ne0⟩ := I.ne_bot_iff.mp I_ne_bot in
or.resolve_left (mul_eq_zero.mp ((I * J).eq_bot_iff.mp hij _ (mul_mem_mul hi hj))) ne0)),
λ h, by cases h; rw [← ideal.mul_bot, h, ideal.mul_comm]⟩
instance {R : Type*} [integral_domain R] : no_zero_divisors (ideal R) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ I J, mul_eq_bot.1 }
/-- A product of ideals in an integral domain is zero if and only if one of the terms is zero. -/
lemma prod_eq_bot {R : Type*} [integral_domain R]
{s : multiset (ideal R)} : s.prod = ⊥ ↔ ∃ I ∈ s, I = ⊥ :=
prod_zero_iff_exists_zero
/-- The radical of an ideal `I` consists of the elements `r` such that `r^n ∈ I` for some `n`. -/
def radical (I : ideal R) : ideal R :=
{ carrier := { r | ∃ n : ℕ, r ^ n ∈ I },
zero_mem' := ⟨1, (pow_one (0:R)).symm ▸ I.zero_mem⟩,
add_mem' := λ x y ⟨m, hxmi⟩ ⟨n, hyni⟩, ⟨m + n,
(add_pow x y (m + n)).symm ▸ I.sum_mem $
show ∀ c ∈ finset.range (nat.succ (m + n)),
x ^ c * y ^ (m + n - c) * (nat.choose (m + n) c) ∈ I,
from λ c hc, or.cases_on (le_total c m)
(λ hcm, I.mul_mem_right _ $ I.mul_mem_left _ $ nat.add_comm n m ▸
(nat.add_sub_assoc hcm n).symm ▸
(pow_add y n (m-c)).symm ▸ I.mul_mem_right _ hyni)
(λ hmc, I.mul_mem_right _ $ I.mul_mem_right _ $ nat.add_sub_cancel' hmc ▸
(pow_add x m (c-m)).symm ▸ I.mul_mem_right _ hxmi)⟩,
smul_mem' := λ r s ⟨n, hsni⟩, ⟨n, (mul_pow r s n).symm ▸ I.mul_mem_left (r^n) hsni⟩ }
theorem le_radical : I ≤ radical I :=
λ r hri, ⟨1, (pow_one r).symm ▸ hri⟩
variables (R)
theorem radical_top : (radical ⊤ : ideal R) = ⊤ :=
(eq_top_iff_one _).2 ⟨0, submodule.mem_top⟩
variables {R}
theorem radical_mono (H : I ≤ J) : radical I ≤ radical J :=
λ r ⟨n, hrni⟩, ⟨n, H hrni⟩
variables (I)
@[simp] theorem radical_idem : radical (radical I) = radical I :=
le_antisymm (λ r ⟨n, k, hrnki⟩, ⟨n * k, (pow_mul r n k).symm ▸ hrnki⟩) le_radical
variables {I}
theorem radical_le_radical_iff : radical I ≤ radical J ↔ I ≤ radical J :=
⟨λ h, le_trans le_radical h, λ h, radical_idem J ▸ radical_mono h⟩
theorem radical_eq_top : radical I = ⊤ ↔ I = ⊤ :=
⟨λ h, (eq_top_iff_one _).2 $ let ⟨n, hn⟩ := (eq_top_iff_one _).1 h in
@one_pow R _ n ▸ hn, λ h, h.symm ▸ radical_top R⟩
theorem is_prime.radical (H : is_prime I) : radical I = I :=
le_antisymm (λ r ⟨n, hrni⟩, H.mem_of_pow_mem n hrni) le_radical
variables (I J)
theorem radical_sup : radical (I ⊔ J) = radical (radical I ⊔ radical J) :=
le_antisymm (radical_mono $ sup_le_sup le_radical le_radical) $
λ r ⟨n, hrnij⟩, let ⟨s, hs, t, ht, hst⟩ := submodule.mem_sup.1 hrnij in
@radical_idem _ _ (I ⊔ J) ▸ ⟨n, hst ▸ ideal.add_mem _
(radical_mono le_sup_left hs) (radical_mono le_sup_right ht)⟩
theorem radical_inf : radical (I ⊓ J) = radical I ⊓ radical J :=
le_antisymm (le_inf (radical_mono inf_le_left) (radical_mono inf_le_right))
(λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ I.mul_mem_right _ hrm,
(pow_add r m n).symm ▸ J.mul_mem_left _ hrn⟩)
theorem radical_mul : radical (I * J) = radical I ⊓ radical J :=
le_antisymm (radical_inf I J ▸ radical_mono $ @mul_le_inf _ _ I J)
(λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ mul_mem_mul hrm hrn⟩)
variables {I J}
theorem is_prime.radical_le_iff (hj : is_prime J) :
radical I ≤ J ↔ I ≤ J :=
⟨le_trans le_radical, λ hij r ⟨n, hrni⟩, hj.mem_of_pow_mem n $ hij hrni⟩
theorem radical_eq_Inf (I : ideal R) :
radical I = Inf { J : ideal R | I ≤ J ∧ is_prime J } :=
le_antisymm (le_Inf $ λ J hJ, hJ.2.radical_le_iff.2 hJ.1) $
λ r hr, classical.by_contradiction $ λ hri,
let ⟨m, (hrm : r ∉ radical m), him, hm⟩ := zorn.zorn_nonempty_partial_order₀
{K : ideal R | r ∉ radical K}
(λ c hc hcc y hyc, ⟨Sup c, λ ⟨n, hrnc⟩, let ⟨y, hyc, hrny⟩ :=
(submodule.mem_Sup_of_directed ⟨y, hyc⟩ hcc.directed_on).1 hrnc in hc hyc ⟨n, hrny⟩,
λ z, le_Sup⟩) I hri in
have ∀ x ∉ m, r ∈ radical (m ⊔ span {x}) := λ x hxm, classical.by_contradiction $ λ hrmx, hxm $
hm (m ⊔ span {x}) hrmx le_sup_left ▸ (le_sup_right : _ ≤ m ⊔ span {x})
(subset_span $ set.mem_singleton _),
have is_prime m, from ⟨by rintro rfl; rw radical_top at hrm; exact hrm trivial,
λ x y hxym, or_iff_not_imp_left.2 $ λ hxm, classical.by_contradiction $ λ hym,
let ⟨n, hrn⟩ := this _ hxm,
⟨p, hpm, q, hq, hpqrn⟩ := submodule.mem_sup.1 hrn,
⟨c, hcxq⟩ := mem_span_singleton'.1 hq in
let ⟨k, hrk⟩ := this _ hym,
⟨f, hfm, g, hg, hfgrk⟩ := submodule.mem_sup.1 hrk,
⟨d, hdyg⟩ := mem_span_singleton'.1 hg in
hrm ⟨n + k, by rw [pow_add, ← hpqrn, ← hcxq, ← hfgrk, ← hdyg, add_mul, mul_add (c*x),
mul_assoc c x (d*y), mul_left_comm x, ← mul_assoc];
refine m.add_mem (m.mul_mem_right _ hpm) (m.add_mem (m.mul_mem_left _ hfm)
(m.mul_mem_left _ hxym))⟩⟩,
hrm $ this.radical.symm ▸ (Inf_le ⟨him, this⟩ : Inf {J : ideal R | I ≤ J ∧ is_prime J} ≤ m) hr
@[simp] lemma radical_bot_of_integral_domain {R : Type u} [integral_domain R] :
radical (⊥ : ideal R) = ⊥ :=
eq_bot_iff.2 (λ x hx, hx.rec_on (λ n hn, pow_eq_zero hn))
instance : comm_semiring (ideal R) := submodule.comm_semiring
variables (R)
theorem top_pow (n : ℕ) : (⊤ ^ n : ideal R) = ⊤ :=
nat.rec_on n one_eq_top $ λ n ih, by rw [pow_succ, ih, top_mul]
variables {R}
variables (I)
theorem radical_pow (n : ℕ) (H : n > 0) : radical (I^n) = radical I :=
nat.rec_on n (not.elim dec_trivial) (λ n ih H,
or.cases_on (lt_or_eq_of_le $ nat.le_of_lt_succ H)
(λ H, calc radical (I^(n+1))
= radical I ⊓ radical (I^n) : by { rw pow_succ, exact radical_mul _ _ }
... = radical I ⊓ radical I : by rw ih H
... = radical I : inf_idem)
(λ H, H ▸ (pow_one I).symm ▸ rfl)) H
theorem is_prime.mul_le {I J P : ideal R} (hp : is_prime P) :
I * J ≤ P ↔ I ≤ P ∨ J ≤ P :=
⟨λ h, or_iff_not_imp_left.2 $ λ hip j hj, let ⟨i, hi, hip⟩ := set.not_subset.1 hip in
(hp.mem_or_mem $ h $ mul_mem_mul hi hj).resolve_left hip,
λ h, or.cases_on h (le_trans $ le_trans mul_le_inf inf_le_left)
(le_trans $ le_trans mul_le_inf inf_le_right)⟩
theorem is_prime.inf_le {I J P : ideal R} (hp : is_prime P) :
I ⊓ J ≤ P ↔ I ≤ P ∨ J ≤ P :=
⟨λ h, hp.mul_le.1 $ le_trans mul_le_inf h,
λ h, or.cases_on h (le_trans inf_le_left) (le_trans inf_le_right)⟩
theorem is_prime.multiset_prod_le {s : multiset (ideal R)} {P : ideal R}
(hp : is_prime P) (hne : s ≠ 0) :
s.prod ≤ P ↔ ∃ I ∈ s, I ≤ P :=
suffices s.prod ≤ P → ∃ I ∈ s, I ≤ P,
from ⟨this, λ ⟨i, his, hip⟩, le_trans multiset_prod_le_inf $
le_trans (multiset.inf_le his) hip⟩,
begin
classical,
obtain ⟨b, hb⟩ : ∃ b, b ∈ s := multiset.exists_mem_of_ne_zero hne,
obtain ⟨t, rfl⟩ : ∃ t, s = b ::ₘ t,
from ⟨s.erase b, (multiset.cons_erase hb).symm⟩,
refine t.induction_on _ _,
{ simp only [exists_prop, ←multiset.singleton_eq_cons, multiset.prod_singleton,
multiset.mem_singleton, exists_eq_left, imp_self] },
intros a s ih h,
rw [multiset.cons_swap, multiset.prod_cons, hp.mul_le] at h,
rw multiset.cons_swap,
cases h,
{ exact ⟨a, multiset.mem_cons_self a _, h⟩ },
obtain ⟨I, hI, ih⟩ : ∃ I ∈ b ::ₘ s, I ≤ P := ih h,
exact ⟨I, multiset.mem_cons_of_mem hI, ih⟩
end
theorem is_prime.multiset_prod_map_le {s : multiset ι} (f : ι → ideal R) {P : ideal R}
(hp : is_prime P) (hne : s ≠ 0) :
(s.map f).prod ≤ P ↔ ∃ i ∈ s, f i ≤ P :=
begin
rw hp.multiset_prod_le (mt multiset.map_eq_zero.mp hne),
simp_rw [exists_prop, multiset.mem_map, exists_exists_and_eq_and],
end
theorem is_prime.prod_le {s : finset ι} {f : ι → ideal R} {P : ideal R}
(hp : is_prime P) (hne : s.nonempty) :
s.prod f ≤ P ↔ ∃ i ∈ s, f i ≤ P :=
hp.multiset_prod_map_le f (mt finset.val_eq_zero.mp hne.ne_empty)
theorem is_prime.inf_le' {s : finset ι} {f : ι → ideal R} {P : ideal R} (hp : is_prime P)
(hsne: s.nonempty) :
s.inf f ≤ P ↔ ∃ i ∈ s, f i ≤ P :=
⟨λ h, (hp.prod_le hsne).1 $ le_trans prod_le_inf h,
λ ⟨i, his, hip⟩, le_trans (finset.inf_le his) hip⟩
theorem subset_union {I J K : ideal R} : (I : set R) ⊆ J ∪ K ↔ I ≤ J ∨ I ≤ K :=
⟨λ h, or_iff_not_imp_left.2 $ λ hij s hsi,
let ⟨r, hri, hrj⟩ := set.not_subset.1 hij in classical.by_contradiction $ λ hsk,
or.cases_on (h $ I.add_mem hri hsi)
(λ hj, hrj $ add_sub_cancel r s ▸ J.sub_mem hj ((h hsi).resolve_right hsk))
(λ hk, hsk $ add_sub_cancel' r s ▸ K.sub_mem hk ((h hri).resolve_left hrj)),
λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset_union_left J K)
(λ h, set.subset.trans h $ set.subset_union_right J K)⟩
theorem subset_union_prime' {s : finset ι} {f : ι → ideal R} {a b : ι}
(hp : ∀ i ∈ s, is_prime (f i)) {I : ideal R} :
(I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) ↔ I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i :=
suffices (I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) →
I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i,
from ⟨this, λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans
(set.subset_union_left _ _) (set.subset_union_left _ _)) $
λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans
(set.subset_union_right _ _) (set.subset_union_left _ _)) $
λ ⟨i, his, hi⟩, by refine (set.subset.trans hi $ set.subset.trans _ $
set.subset_union_right _ _);
exact set.subset_bUnion_of_mem (finset.mem_coe.2 his)⟩,
begin
generalize hn : s.card = n, intros h,
unfreezingI { induction n with n ih generalizing a b s },
{ clear hp,
rw finset.card_eq_zero at hn, subst hn,
rw [finset.coe_empty, set.bUnion_empty, set.union_empty, subset_union] at h,
simpa only [exists_prop, finset.not_mem_empty, false_and, exists_false, or_false] },
classical,
replace hn : ∃ (i : ι) (t : finset ι), i ∉ t ∧ insert i t = s ∧ t.card = n :=
finset.card_eq_succ.1 hn,
unfreezingI { rcases hn with ⟨i, t, hit, rfl, hn⟩ },
replace hp : is_prime (f i) ∧ ∀ x ∈ t, is_prime (f x) := (t.forall_mem_insert _ _).1 hp,
by_cases Ht : ∃ j ∈ t, f j ≤ f i,
{ obtain ⟨j, hjt, hfji⟩ : ∃ j ∈ t, f j ≤ f i := Ht,
obtain ⟨u, hju, rfl⟩ : ∃ u, j ∉ u ∧ insert j u = t,
{ exact ⟨t.erase j, t.not_mem_erase j, finset.insert_erase hjt⟩ },
have hp' : ∀ k ∈ insert i u, is_prime (f k),
{ rw finset.forall_mem_insert at hp ⊢, exact ⟨hp.1, hp.2.2⟩ },
have hiu : i ∉ u := mt finset.mem_insert_of_mem hit,
have hn' : (insert i u).card = n,
{ rwa finset.card_insert_of_not_mem at hn ⊢, exacts [hiu, hju] },
have h' : (I : set R) ⊆ f a ∪ f b ∪ (⋃ k ∈ (↑(insert i u) : set ι), f k),
{ rw finset.coe_insert at h ⊢, rw finset.coe_insert at h,
simp only [set.bUnion_insert] at h ⊢,
rw [← set.union_assoc ↑(f i)] at h,
erw [set.union_eq_self_of_subset_right hfji] at h,
exact h },
specialize @ih a b (insert i u) hp' hn' h',
refine ih.imp id (or.imp id (exists_imp_exists $ λ k, _)), simp only [exists_prop],
exact and.imp (λ hk, finset.insert_subset_insert i (finset.subset_insert j u) hk) id },
by_cases Ha : f a ≤ f i,
{ have h' : (I : set R) ⊆ f i ∪ f b ∪ (⋃ j ∈ (↑t : set ι), f j),
{ rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc,
set.union_right_comm ↑(f a)] at h,
erw [set.union_eq_self_of_subset_left Ha] at h,
exact h },
specialize @ih i b t hp.2 hn h', right,
rcases ih with ih | ih | ⟨k, hkt, ih⟩,
{ exact or.inr ⟨i, finset.mem_insert_self i t, ih⟩ },
{ exact or.inl ih },
{ exact or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } },
by_cases Hb : f b ≤ f i,
{ have h' : (I : set R) ⊆ f a ∪ f i ∪ (⋃ j ∈ (↑t : set ι), f j),
{ rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc, set.union_assoc ↑(f a)] at h,
erw [set.union_eq_self_of_subset_left Hb] at h,
exact h },
specialize @ih a i t hp.2 hn h',
rcases ih with ih | ih | ⟨k, hkt, ih⟩,
{ exact or.inl ih },
{ exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, ih⟩) },
{ exact or.inr (or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩) } },
by_cases Hi : I ≤ f i,
{ exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, Hi⟩) },
have : ¬I ⊓ f a ⊓ f b ⊓ t.inf f ≤ f i,
{ rcases t.eq_empty_or_nonempty with (rfl | hsne),
{ rw [finset.inf_empty, inf_top_eq, hp.1.inf_le, hp.1.inf_le, not_or_distrib, not_or_distrib],
exact ⟨⟨Hi, Ha⟩, Hb⟩ },
simp only [hp.1.inf_le, hp.1.inf_le' hsne, not_or_distrib],
exact ⟨⟨⟨Hi, Ha⟩, Hb⟩, Ht⟩ },
rcases set.not_subset.1 this with ⟨r, ⟨⟨⟨hrI, hra⟩, hrb⟩, hr⟩, hri⟩,
by_cases HI : (I : set R) ⊆ f a ∪ f b ∪ ⋃ j ∈ (↑t : set ι), f j,
{ specialize ih hp.2 hn HI, rcases ih with ih | ih | ⟨k, hkt, ih⟩,
{ left, exact ih }, { right, left, exact ih },
{ right, right, exact ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } },
exfalso, rcases set.not_subset.1 HI with ⟨s, hsI, hs⟩,
rw [finset.coe_insert, set.bUnion_insert] at h,
have hsi : s ∈ f i := ((h hsI).resolve_left (mt or.inl hs)).resolve_right (mt or.inr hs),
rcases h (I.add_mem hrI hsI) with ⟨ha | hb⟩ | hi | ht,
{ exact hs (or.inl $ or.inl $ add_sub_cancel' r s ▸ (f a).sub_mem ha hra) },
{ exact hs (or.inl $ or.inr $ add_sub_cancel' r s ▸ (f b).sub_mem hb hrb) },
{ exact hri (add_sub_cancel r s ▸ (f i).sub_mem hi hsi) },
{ rw set.mem_bUnion_iff at ht, rcases ht with ⟨j, hjt, hj⟩,
simp only [finset.inf_eq_infi, set_like.mem_coe, submodule.mem_infi] at hr,
exact hs (or.inr $ set.mem_bUnion hjt $ add_sub_cancel' r s ▸ (f j).sub_mem hj $ hr j hjt) }
end
/-- Prime avoidance. Atiyah-Macdonald 1.11, Eisenbud 3.3, Stacks 00DS, Matsumura Ex.1.6. -/
theorem subset_union_prime {s : finset ι} {f : ι → ideal R} (a b : ι)
(hp : ∀ i ∈ s, i ≠ a → i ≠ b → is_prime (f i)) {I : ideal R} :
(I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) ↔ ∃ i ∈ s, I ≤ f i :=
suffices (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) → ∃ i, i ∈ s ∧ I ≤ f i,
from ⟨λ h, bex_def.2 $ this h, λ ⟨i, his, hi⟩, set.subset.trans hi $ set.subset_bUnion_of_mem $
show i ∈ (↑s : set ι), from his⟩,
assume h : (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i),
begin
classical, tactic.unfreeze_local_instances,
by_cases has : a ∈ s,
{ obtain ⟨t, hat, rfl⟩ : ∃ t, a ∉ t ∧ insert a t = s :=
⟨s.erase a, finset.not_mem_erase a s, finset.insert_erase has⟩,
by_cases hbt : b ∈ t,
{ obtain ⟨u, hbu, rfl⟩ : ∃ u, b ∉ u ∧ insert b u = t :=
⟨t.erase b, finset.not_mem_erase b t, finset.insert_erase hbt⟩,
have hp' : ∀ i ∈ u, is_prime (f i),
{ intros i hiu, refine hp i (finset.mem_insert_of_mem (finset.mem_insert_of_mem hiu)) _ _;
rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], },
rw [finset.coe_insert, finset.coe_insert, set.bUnion_insert, set.bUnion_insert,
← set.union_assoc, subset_union_prime' hp', bex_def] at h,
rwa [finset.exists_mem_insert, finset.exists_mem_insert] },
{ have hp' : ∀ j ∈ t, is_prime (f j),
{ intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _;
rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], },
rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f a : set R),
subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h,
rwa finset.exists_mem_insert } },
{ by_cases hbs : b ∈ s,
{ obtain ⟨t, hbt, rfl⟩ : ∃ t, b ∉ t ∧ insert b t = s :=
⟨s.erase b, finset.not_mem_erase b s, finset.insert_erase hbs⟩,
have hp' : ∀ j ∈ t, is_prime (f j),
{ intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _;
rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], },
rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f b : set R),
subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h,
rwa finset.exists_mem_insert },
cases s.eq_empty_or_nonempty with hse hsne,
{ subst hse, rw [finset.coe_empty, set.bUnion_empty, set.subset_empty_iff] at h,
have : (I : set R) ≠ ∅ := set.nonempty.ne_empty (set.nonempty_of_mem I.zero_mem),
exact absurd h this },
{ cases hsne.bex with i his,
obtain ⟨t, hit, rfl⟩ : ∃ t, i ∉ t ∧ insert i t = s :=
⟨s.erase i, finset.not_mem_erase i s, finset.insert_erase his⟩,
have hp' : ∀ j ∈ t, is_prime (f j),
{ intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _;
rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], },
rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f i : set R),
subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h,
rwa finset.exists_mem_insert } }
end
section dvd
/-- If `I` divides `J`, then `I` contains `J`.
In a Dedekind domain, to divide and contain are equivalent, see `ideal.dvd_iff_le`.
-/
lemma le_of_dvd {I J : ideal R} : I ∣ J → J ≤ I
| ⟨K, h⟩ := h.symm ▸ le_trans mul_le_inf inf_le_left
lemma is_unit_iff {I : ideal R} :
is_unit I ↔ I = ⊤ :=
is_unit_iff_dvd_one.trans ((@one_eq_top R _).symm ▸
⟨λ h, eq_top_iff.mpr (ideal.le_of_dvd h), λ h, ⟨⊤, by rw [mul_top, h]⟩⟩)
instance unique_units : unique (units (ideal R)) :=
{ default := 1,
uniq := λ u, units.ext
(show (u : ideal R) = 1, by rw [is_unit_iff.mp u.is_unit, one_eq_top]) }
end dvd
end mul_and_radical
section map_and_comap
variables {R : Type u} {S : Type v} [ring R] [ring S]
variables (f : R →+* S)
variables {I J : ideal R} {K L : ideal S}
/-- `I.map f` is the span of the image of the ideal `I` under `f`, which may be bigger than
the image itself. -/
def map (I : ideal R) : ideal S :=
span (f '' I)
/-- `I.comap f` is the preimage of `I` under `f`. -/
def comap (I : ideal S) : ideal R :=
{ carrier := f ⁻¹' I,
smul_mem' := λ c x hx, show f (c * x) ∈ I, by { rw f.map_mul, exact I.mul_mem_left _ hx },
.. I.to_add_submonoid.comap (f : R →+ S) }
variables {f}
theorem map_mono (h : I ≤ J) : map f I ≤ map f J :=
span_mono $ set.image_subset _ h
theorem mem_map_of_mem (f : R →+* S) {I : ideal R} {x : R} (h : x ∈ I) : f x ∈ map f I :=
subset_span ⟨x, h, rfl⟩
lemma apply_coe_mem_map (f : R →+* S) (I : ideal R) (x : I) : f x ∈ I.map f :=
mem_map_of_mem f x.prop
theorem map_le_iff_le_comap :
map f I ≤ K ↔ I ≤ comap f K :=
span_le.trans set.image_subset_iff
@[simp] theorem mem_comap {x} : x ∈ comap f K ↔ f x ∈ K := iff.rfl
theorem comap_mono (h : K ≤ L) : comap f K ≤ comap f L :=
set.preimage_mono (λ x hx, h hx)
variables (f)
theorem comap_ne_top (hK : K ≠ ⊤) : comap f K ≠ ⊤ :=
(ne_top_iff_one _).2 $ by rw [mem_comap, f.map_one];
exact (ne_top_iff_one _).1 hK
instance is_prime.comap [hK : K.is_prime] : (comap f K).is_prime :=
⟨comap_ne_top _ hK.1, λ x y,
by simp only [mem_comap, f.map_mul]; apply hK.2⟩
variables (I J K L)
theorem map_top : map f ⊤ = ⊤ :=
(eq_top_iff_one _).2 $ subset_span ⟨1, trivial, f.map_one⟩
variable (f)
lemma gc_map_comap : galois_connection (ideal.map f) (ideal.comap f) :=
λ I J, ideal.map_le_iff_le_comap
@[simp] lemma comap_id : I.comap (ring_hom.id R) = I :=
ideal.ext $ λ _, iff.rfl
@[simp] lemma map_id : I.map (ring_hom.id R) = I :=
(gc_map_comap (ring_hom.id R)).l_unique galois_connection.id comap_id
lemma comap_comap {T : Type*} [ring T] {I : ideal T} (f : R →+* S)
(g : S →+*T) : (I.comap g).comap f = I.comap (g.comp f) := rfl
lemma map_map {T : Type*} [ring T] {I : ideal R} (f : R →+* S)
(g : S →+*T) : (I.map f).map g = I.map (g.comp f) :=
((gc_map_comap f).compose _ _ _ _ (gc_map_comap g)).l_unique
(gc_map_comap (g.comp f)) (λ _, comap_comap _ _)
variables {f I J K L}
lemma map_le_of_le_comap : I ≤ K.comap f → I.map f ≤ K :=
(gc_map_comap f).l_le
lemma le_comap_of_map_le : I.map f ≤ K → I ≤ K.comap f :=
(gc_map_comap f).le_u
lemma le_comap_map : I ≤ (I.map f).comap f :=
(gc_map_comap f).le_u_l _
lemma map_comap_le : (K.comap f).map f ≤ K :=
(gc_map_comap f).l_u_le _
@[simp] lemma comap_top : (⊤ : ideal S).comap f = ⊤ :=
(gc_map_comap f).u_top
@[simp] lemma comap_eq_top_iff {I : ideal S} : I.comap f = ⊤ ↔ I = ⊤ :=
⟨ λ h, I.eq_top_iff_one.mpr (f.map_one ▸ mem_comap.mp ((I.comap f).eq_top_iff_one.mp h)),
λ h, by rw [h, comap_top] ⟩
@[simp] lemma map_bot : (⊥ : ideal R).map f = ⊥ :=
(gc_map_comap f).l_bot
variables (f I J K L)
@[simp] lemma map_comap_map : ((I.map f).comap f).map f = I.map f :=
congr_fun (gc_map_comap f).l_u_l_eq_l I
@[simp] lemma comap_map_comap : ((K.comap f).map f).comap f = K.comap f :=
congr_fun (gc_map_comap f).u_l_u_eq_u K
lemma map_sup : (I ⊔ J).map f = I.map f ⊔ J.map f :=
(gc_map_comap f).l_sup
theorem comap_inf : comap f (K ⊓ L) = comap f K ⊓ comap f L := rfl
variables {ι : Sort*}
lemma map_supr (K : ι → ideal R) : (supr K).map f = ⨆ i, (K i).map f :=
(gc_map_comap f).l_supr
lemma comap_infi (K : ι → ideal S) : (infi K).comap f = ⨅ i, (K i).comap f :=
(gc_map_comap f).u_infi
lemma map_Sup (s : set (ideal R)): (Sup s).map f = ⨆ I ∈ s, (I : ideal R).map f :=
(gc_map_comap f).l_Sup
lemma comap_Inf (s : set (ideal S)): (Inf s).comap f = ⨅ I ∈ s, (I : ideal S).comap f :=
(gc_map_comap f).u_Inf
lemma comap_Inf' (s : set (ideal S)) : (Inf s).comap f = ⨅ I ∈ (comap f '' s), I :=
trans (comap_Inf f s) (by rw infi_image)
theorem comap_is_prime [H : is_prime K] : is_prime (comap f K) :=
⟨comap_ne_top f H.ne_top,
λ x y h, H.mem_or_mem $ by rwa [mem_comap, ring_hom.map_mul] at h⟩
variables {I J K L}
theorem map_inf_le : map f (I ⊓ J) ≤ map f I ⊓ map f J :=
(gc_map_comap f).monotone_l.map_inf_le _ _
theorem le_comap_sup : comap f K ⊔ comap f L ≤ comap f (K ⊔ L) :=
(gc_map_comap f).monotone_u.le_map_sup _ _
section surjective
variables (hf : function.surjective f)
include hf
open function
theorem map_comap_of_surjective (I : ideal S) :
map f (comap f I) = I :=
le_antisymm (map_le_iff_le_comap.2 (le_refl _))
(λ s hsi, let ⟨r, hfrs⟩ := hf s in
hfrs ▸ (mem_map_of_mem f $ show f r ∈ I, from hfrs.symm ▸ hsi))
/-- `map` and `comap` are adjoint, and the composition `map f ∘ comap f` is the
identity -/
def gi_map_comap : galois_insertion (map f) (comap f) :=
galois_insertion.monotone_intro
((gc_map_comap f).monotone_u)
((gc_map_comap f).monotone_l)
(λ _, le_comap_map)
(map_comap_of_surjective _ hf)
lemma map_surjective_of_surjective : surjective (map f) :=
(gi_map_comap f hf).l_surjective
lemma comap_injective_of_surjective : injective (comap f) :=
(gi_map_comap f hf).u_injective
lemma map_sup_comap_of_surjective (I J : ideal S) : (I.comap f ⊔ J.comap f).map f = I ⊔ J :=
(gi_map_comap f hf).l_sup_u _ _
lemma map_supr_comap_of_surjective (K : ι → ideal S) : (⨆i, (K i).comap f).map f = supr K :=
(gi_map_comap f hf).l_supr_u _
lemma map_inf_comap_of_surjective (I J : ideal S) : (I.comap f ⊓ J.comap f).map f = I ⊓ J :=
(gi_map_comap f hf).l_inf_u _ _
lemma map_infi_comap_of_surjective (K : ι → ideal S) : (⨅i, (K i).comap f).map f = infi K :=
(gi_map_comap f hf).l_infi_u _
theorem mem_image_of_mem_map_of_surjective {I : ideal R} {y}
(H : y ∈ map f I) : y ∈ f '' I :=
submodule.span_induction H (λ _, id) ⟨0, I.zero_mem, f.map_zero⟩
(λ y1 y2 ⟨x1, hx1i, hxy1⟩ ⟨x2, hx2i, hxy2⟩,
⟨x1 + x2, I.add_mem hx1i hx2i, hxy1 ▸ hxy2 ▸ f.map_add _ _⟩)
(λ c y ⟨x, hxi, hxy⟩, let ⟨d, hdc⟩ := hf c in ⟨d • x, I.smul_mem _ hxi, hdc ▸ hxy ▸ f.map_mul _ _⟩)
lemma mem_map_iff_of_surjective {I : ideal R} {y} :
y ∈ map f I ↔ ∃ x, x ∈ I ∧ f x = y :=
⟨λ h, (set.mem_image _ _ _).2 (mem_image_of_mem_map_of_surjective f hf h),
λ ⟨x, hx⟩, hx.right ▸ (mem_map_of_mem f hx.left)⟩
theorem comap_map_of_surjective (I : ideal R) :
comap f (map f I) = I ⊔ comap f ⊥ :=
le_antisymm (assume r h, let ⟨s, hsi, hfsr⟩ := mem_image_of_mem_map_of_surjective f hf h in
submodule.mem_sup.2 ⟨s, hsi, r - s, (submodule.mem_bot S).2 $ by rw [f.map_sub, hfsr, sub_self],
add_sub_cancel'_right s r⟩)
(sup_le (map_le_iff_le_comap.1 (le_refl _)) (comap_mono bot_le))
lemma le_map_of_comap_le_of_surjective : comap f K ≤ I → K ≤ map f I :=
λ h, (map_comap_of_surjective f hf K) ▸ map_mono h
/-- Correspondence theorem -/
def rel_iso_of_surjective :
ideal S ≃o { p : ideal R // comap f ⊥ ≤ p } :=
{ to_fun := λ J, ⟨comap f J, comap_mono bot_le⟩,
inv_fun := λ I, map f I.1,
left_inv := λ J, map_comap_of_surjective f hf J,
right_inv := λ I, subtype.eq $ show comap f (map f I.1) = I.1,
from (comap_map_of_surjective f hf I).symm ▸ le_antisymm
(sup_le (le_refl _) I.2) le_sup_left,
map_rel_iff' := λ I1 I2, ⟨λ H, map_comap_of_surjective f hf I1 ▸
map_comap_of_surjective f hf I2 ▸ map_mono H, comap_mono⟩ }
/-- The map on ideals induced by a surjective map preserves inclusion. -/
def order_embedding_of_surjective : ideal S ↪o ideal R :=
(rel_iso_of_surjective f hf).to_rel_embedding.trans (subtype.rel_embedding _ _)
theorem map_eq_top_or_is_maximal_of_surjective (H : is_maximal I) :
(map f I) = ⊤ ∨ is_maximal (map f I) :=
begin
refine or_iff_not_imp_left.2 (λ ne_top, ⟨⟨λ h, ne_top h, λ J hJ, _⟩⟩),
{ refine (rel_iso_of_surjective f hf).injective
(subtype.ext_iff.2 (eq.trans (H.1.2 (comap f J) (lt_of_le_of_ne _ _)) comap_top.symm)),
{ exact (map_le_iff_le_comap).1 (le_of_lt hJ) },
{ exact λ h, hJ.right (le_map_of_comap_le_of_surjective f hf (le_of_eq h.symm)) } }
end
theorem comap_is_maximal_of_surjective [H : is_maximal K] : is_maximal (comap f K) :=
begin
refine ⟨⟨comap_ne_top _ H.1.1, λ J hJ, _⟩⟩,
suffices : map f J = ⊤,
{ replace this := congr_arg (comap f) this,
rw [comap_top, comap_map_of_surjective _ hf, eq_top_iff] at this,
rw eq_top_iff,
exact le_trans this (sup_le (le_of_eq rfl) (le_trans (comap_mono (bot_le)) (le_of_lt hJ))) },
refine H.1.2 (map f J) (lt_of_le_of_ne (le_map_of_comap_le_of_surjective _ hf (le_of_lt hJ))
(λ h, ne_of_lt hJ (trans (congr_arg (comap f) h) _))),
rw [comap_map_of_surjective _ hf, sup_eq_left],
exact le_trans (comap_mono bot_le) (le_of_lt hJ)
end
end surjective
/-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `map f (map f.symm) = I`. -/
@[simp]
lemma map_of_equiv (I : ideal R) (f : R ≃+* S) : (I.map (f : R →+* S)).map (f.symm : S →+* R) = I :=
by simp [← ring_equiv.to_ring_hom_eq_coe, map_map]
/-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `comap f.symm (comap f) = I`. -/
@[simp]
lemma comap_of_equiv (I : ideal R) (f : R ≃+* S) :
(I.comap (f.symm : S →+* R)).comap (f : R →+* S) = I :=
by simp [← ring_equiv.to_ring_hom_eq_coe, comap_comap]
/-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `map f I = comap f.symm I`. -/
lemma map_comap_of_equiv (I : ideal R) (f : R ≃+* S) : I.map (f : R →+* S) = I.comap f.symm :=
le_antisymm (le_comap_of_map_le (map_of_equiv I f).le)
(le_map_of_comap_le_of_surjective _ f.surjective (comap_of_equiv I f).le)
section injective
variables (hf : function.injective f)
include hf
open function
lemma comap_bot_le_of_injective : comap f ⊥ ≤ I :=
begin
refine le_trans (λ x hx, _) bot_le,
rw [mem_comap, submodule.mem_bot, ← ring_hom.map_zero f] at hx,
exact eq.symm (hf hx) ▸ (submodule.zero_mem ⊥)
end
end injective
section bijective
variables (hf : function.bijective f)
include hf
open function
/-- Special case of the correspondence theorem for isomorphic rings -/
def rel_iso_of_bijective : ideal S ≃o ideal R :=
{ to_fun := comap f,
inv_fun := map f,
left_inv := (rel_iso_of_surjective f hf.right).left_inv,
right_inv := λ J, subtype.ext_iff.1
((rel_iso_of_surjective f hf.right).right_inv ⟨J, comap_bot_le_of_injective f hf.left⟩),
map_rel_iff' := (rel_iso_of_surjective f hf.right).map_rel_iff' }
lemma comap_le_iff_le_map : comap f K ≤ I ↔ K ≤ map f I :=
⟨λ h, le_map_of_comap_le_of_surjective f hf.right h,
λ h, ((rel_iso_of_bijective f hf).right_inv I) ▸ comap_mono h⟩
theorem map.is_maximal (H : is_maximal I) : is_maximal (map f I) :=
by refine or_iff_not_imp_left.1
(map_eq_top_or_is_maximal_of_surjective f hf.right H) (λ h, H.1.1 _);
calc I = comap f (map f I) : ((rel_iso_of_bijective f hf).right_inv I).symm
... = comap f ⊤ : by rw h
... = ⊤ : by rw comap_top
end bijective
lemma ring_equiv.bot_maximal_iff (e : R ≃+* S) :
(⊥ : ideal R).is_maximal ↔ (⊥ : ideal S).is_maximal :=
⟨λ h, (@map_bot _ _ _ _ e.to_ring_hom) ▸ map.is_maximal e.to_ring_hom e.bijective h,
λ h, (@map_bot _ _ _ _ e.symm.to_ring_hom) ▸ map.is_maximal e.symm.to_ring_hom e.symm.bijective h⟩
end map_and_comap
section map_and_comap
variables {R : Type u} {S : Type v} [comm_ring R] [comm_ring S]
variables (f : R →+* S)
variables {I J : ideal R} {K L : ideal S}
lemma mem_quotient_iff_mem (hIJ : I ≤ J) {x : R} :
quotient.mk I x ∈ J.map (quotient.mk I) ↔ x ∈ J :=
begin
refine iff.trans (mem_map_iff_of_surjective _ quotient.mk_surjective) _,
split,
{ rintros ⟨x, x_mem, x_eq⟩,
simpa using J.add_mem (hIJ (quotient.eq.mp x_eq.symm)) x_mem },
{ intro x_mem,
exact ⟨x, x_mem, rfl⟩ }
end
variables (I J K L)
theorem map_mul : map f (I * J) = map f I * map f J :=
le_antisymm (map_le_iff_le_comap.2 $ mul_le.2 $ λ r hri s hsj,
show f (r * s) ∈ _, by rw f.map_mul;
exact mul_mem_mul (mem_map_of_mem f hri) (mem_map_of_mem f hsj))
(trans_rel_right _ (span_mul_span _ _) $ span_le.2 $
set.bUnion_subset $ λ i ⟨r, hri, hfri⟩,
set.bUnion_subset $ λ j ⟨s, hsj, hfsj⟩,
set.singleton_subset_iff.2 $ hfri ▸ hfsj ▸
by rw [← f.map_mul];
exact mem_map_of_mem f (mul_mem_mul hri hsj))
theorem comap_radical : comap f (radical K) = radical (comap f K) :=
le_antisymm (λ r ⟨n, hfrnk⟩, ⟨n, show f (r ^ n) ∈ K,
from (f.map_pow r n).symm ▸ hfrnk⟩)
(λ r ⟨n, hfrnk⟩, ⟨n, f.map_pow r n ▸ hfrnk⟩)
@[simp] lemma map_quotient_self :
map (quotient.mk I) I = ⊥ :=
eq_bot_iff.2 $ ideal.map_le_iff_le_comap.2 $ λ x hx,
(submodule.mem_bot I.quotient).2 $ ideal.quotient.eq_zero_iff_mem.2 hx
variables {I J K L}
theorem map_radical_le : map f (radical I) ≤ radical (map f I) :=
map_le_iff_le_comap.2 $ λ r ⟨n, hrni⟩, ⟨n, f.map_pow r n ▸ mem_map_of_mem f hrni⟩
theorem le_comap_mul : comap f K * comap f L ≤ comap f (K * L) :=
map_le_iff_le_comap.1 $ (map_mul f (comap f K) (comap f L)).symm ▸
mul_mono (map_le_iff_le_comap.2 $ le_refl _) (map_le_iff_le_comap.2 $ le_refl _)
end map_and_comap
section is_primary
variables {R : Type u} [comm_ring R]
/-- A proper ideal `I` is primary iff `xy ∈ I` implies `x ∈ I` or `y ∈ radical I`. -/
def is_primary (I : ideal R) : Prop :=
I ≠ ⊤ ∧ ∀ {x y : R}, x * y ∈ I → x ∈ I ∨ y ∈ radical I
theorem is_primary.to_is_prime (I : ideal R) (hi : is_prime I) : is_primary I :=
⟨hi.1, λ x y hxy, (hi.mem_or_mem hxy).imp id $ λ hyi, le_radical hyi⟩
theorem mem_radical_of_pow_mem {I : ideal R} {x : R} {m : ℕ} (hx : x ^ m ∈ radical I) :
x ∈ radical I :=
radical_idem I ▸ ⟨m, hx⟩
theorem is_prime_radical {I : ideal R} (hi : is_primary I) : is_prime (radical I) :=
⟨mt radical_eq_top.1 hi.1, λ x y ⟨m, hxy⟩, begin
rw mul_pow at hxy, cases hi.2 hxy,
{ exact or.inl ⟨m, h⟩ },
{ exact or.inr (mem_radical_of_pow_mem h) }
end⟩
theorem is_primary_inf {I J : ideal R} (hi : is_primary I) (hj : is_primary J)
(hij : radical I = radical J) : is_primary (I ⊓ J) :=
⟨ne_of_lt $ lt_of_le_of_lt inf_le_left (lt_top_iff_ne_top.2 hi.1), λ x y ⟨hxyi, hxyj⟩,
begin
rw [radical_inf, hij, inf_idem],
cases hi.2 hxyi with hxi hyi, cases hj.2 hxyj with hxj hyj,
{ exact or.inl ⟨hxi, hxj⟩ },
{ exact or.inr hyj },
{ rw hij at hyi, exact or.inr hyi }
end⟩
end is_primary
end ideal
namespace ring_hom
variables {R : Type u} {S : Type v}
section ring
variables [ring R] [ring S] (f : R →+* S)
/-- Kernel of a ring homomorphism as an ideal of the domain. -/
def ker : ideal R := ideal.comap f ⊥
/-- An element is in the kernel if and only if it maps to zero.-/
lemma mem_ker {r} : r ∈ ker f ↔ f r = 0 :=
by rw [ker, ideal.mem_comap, submodule.mem_bot]
lemma ker_eq : ((ker f) : set R) = set.preimage f {0} := rfl
lemma ker_eq_comap_bot (f : R →+* S) : f.ker = ideal.comap f ⊥ := rfl
lemma injective_iff_ker_eq_bot : function.injective f ↔ ker f = ⊥ :=
by { rw [set_like.ext'_iff, ker_eq, set.ext_iff], exact f.injective_iff' }
lemma ker_eq_bot_iff_eq_zero : ker f = ⊥ ↔ ∀ x, f x = 0 → x = 0 :=
by { rw [← f.injective_iff, injective_iff_ker_eq_bot] }
/-- If the target is not the zero ring, then one is not in the kernel.-/
lemma not_one_mem_ker [nontrivial S] (f : R →+* S) : (1:R) ∉ ker f :=
by { rw [mem_ker, f.map_one], exact one_ne_zero }
@[simp] lemma ker_coe_equiv (f : R ≃+* S) : ker (f : R →+* S) = ⊥ :=
by simpa only [←injective_iff_ker_eq_bot] using f.injective
end ring
section comm_ring
variables [comm_ring R] [comm_ring S] (f : R →+* S)
/-- The induced map from the quotient by the kernel to the codomain.
This is an isomorphism if `f` has a right inverse (`quotient_ker_equiv_of_right_inverse`) /
is surjective (`quotient_ker_equiv_of_surjective`).
-/
def ker_lift (f : R →+* S) : f.ker.quotient →+* S :=
ideal.quotient.lift _ f $ λ r, f.mem_ker.mp
@[simp]
lemma ker_lift_mk (f : R →+* S) (r : R) : ker_lift f (ideal.quotient.mk f.ker r) = f r :=
ideal.quotient.lift_mk _ _ _
/-- The induced map from the quotient by the kernel is injective. -/
lemma ker_lift_injective (f : R →+* S) : function.injective (ker_lift f) :=
assume a b, quotient.induction_on₂' a b $
assume a b (h : f a = f b), quotient.sound' $
show a - b ∈ ker f, by rw [mem_ker, map_sub, h, sub_self]
variable {f}
/-- The first isomorphism theorem for commutative rings, computable version. -/
def quotient_ker_equiv_of_right_inverse
{g : S → R} (hf : function.right_inverse g f) :
f.ker.quotient ≃+* S :=
{ to_fun := ker_lift f,
inv_fun := (ideal.quotient.mk f.ker) ∘ g,
left_inv := begin
rintro ⟨x⟩,
apply ker_lift_injective,
simp [hf (f x)],
end,
right_inv := hf,
..ker_lift f}
@[simp]
lemma quotient_ker_equiv_of_right_inverse.apply {g : S → R} (hf : function.right_inverse g f)
(x : f.ker.quotient) : quotient_ker_equiv_of_right_inverse hf x = ker_lift f x := rfl
@[simp]
lemma quotient_ker_equiv_of_right_inverse.symm.apply {g : S → R} (hf : function.right_inverse g f)
(x : S) : (quotient_ker_equiv_of_right_inverse hf).symm x = ideal.quotient.mk f.ker (g x) := rfl
/-- The first isomorphism theorem for commutative rings. -/
noncomputable def quotient_ker_equiv_of_surjective (hf : function.surjective f) :
f.ker.quotient ≃+* S :=
quotient_ker_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse)
end comm_ring
/-- The kernel of a homomorphism to an integral domain is a prime ideal. -/
lemma ker_is_prime [ring R] [integral_domain S] (f : R →+* S) :
(ker f).is_prime :=
⟨by { rw [ne.def, ideal.eq_top_iff_one], exact not_one_mem_ker f },
λ x y, by simpa only [mem_ker, f.map_mul] using @eq_zero_or_eq_zero_of_mul_eq_zero S _ _ _ _ _⟩
/-- The kernel of a homomorphism to a field is a maximal ideal. -/
lemma ker_is_maximal_of_surjective {R K : Type*} [ring R] [field K]
(f : R →+* K) (hf : function.surjective f) :
f.ker.is_maximal :=
begin
refine ideal.is_maximal_iff.mpr
⟨λ h1, @one_ne_zero K _ _ $ f.map_one ▸ f.mem_ker.mp h1,
λ J x hJ hxf hxJ, _⟩,
obtain ⟨y, hy⟩ := hf (f x)⁻¹,
have H : 1 = y * x - (y * x - 1) := (sub_sub_cancel _ _).symm,
rw H,
refine J.sub_mem (J.mul_mem_left _ hxJ) (hJ _),
rw f.mem_ker,
simp only [hy, ring_hom.map_sub, ring_hom.map_one, ring_hom.map_mul,
inv_mul_cancel (mt f.mem_ker.mpr hxf), sub_self],
end
end ring_hom
namespace ideal
variables {R : Type*} {S : Type*}
section ring
variables [ring R] [ring S]
lemma map_eq_bot_iff_le_ker {I : ideal R} (f : R →+* S) : I.map f = ⊥ ↔ I ≤ f.ker :=
by rw [ring_hom.ker, eq_bot_iff, map_le_iff_le_comap]
lemma ker_le_comap {K : ideal S} (f : R →+* S) : f.ker ≤ comap f K :=
λ x hx, mem_comap.2 (((ring_hom.mem_ker f).1 hx).symm ▸ K.zero_mem)
lemma map_Inf {A : set (ideal R)} {f : R →+* S} (hf : function.surjective f) :
(∀ J ∈ A, ring_hom.ker f ≤ J) → map f (Inf A) = Inf (map f '' A) :=
begin
refine λ h, le_antisymm (le_Inf _) _,
{ intros j hj y hy,
cases (mem_map_iff_of_surjective f hf).1 hy with x hx,
cases (set.mem_image _ _ _).mp hj with J hJ,
rw [← hJ.right, ← hx.right],
exact mem_map_of_mem f (Inf_le_of_le hJ.left (le_of_eq rfl) hx.left) },
{ intros y hy,
cases hf y with x hx,
refine hx ▸ (mem_map_of_mem f _),
have : ∀ I ∈ A, y ∈ map f I, by simpa using hy,
rw [submodule.mem_Inf],
intros J hJ,
rcases (mem_map_iff_of_surjective f hf).1 (this J hJ) with ⟨x', hx', rfl⟩,
have : x - x' ∈ J,
{ apply h J hJ,
rw [ring_hom.mem_ker, ring_hom.map_sub, hx, sub_self] },
simpa only [sub_add_cancel] using J.add_mem this hx' }
end
theorem map_is_prime_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R}
[H : is_prime I] (hk : ring_hom.ker f ≤ I) : is_prime (map f I) :=
begin
refine ⟨λ h, H.ne_top (eq_top_iff.2 _), λ x y, _⟩,
{ replace h := congr_arg (comap f) h,
rw [comap_map_of_surjective _ hf, comap_top] at h,
exact h ▸ sup_le (le_of_eq rfl) hk },
{ refine λ hxy, (hf x).rec_on (λ a ha, (hf y).rec_on (λ b hb, _)),
rw [← ha, ← hb, ← ring_hom.map_mul, mem_map_iff_of_surjective _ hf] at hxy,
rcases hxy with ⟨c, hc, hc'⟩,
rw [← sub_eq_zero, ← ring_hom.map_sub] at hc',
have : a * b ∈ I,
{ convert I.sub_mem hc (hk (hc' : c - a * b ∈ f.ker)),
abel },
exact (H.mem_or_mem this).imp (λ h, ha ▸ mem_map_of_mem f h) (λ h, hb ▸ mem_map_of_mem f h) }
end
theorem map_is_prime_of_equiv (f : R ≃+* S) {I : ideal R} [is_prime I] :
is_prime (map (f : R →+* S) I) :=
map_is_prime_of_surjective f.surjective $ by simp
end ring
section comm_ring
variables [comm_ring R] [comm_ring S]
@[simp] lemma mk_ker {I : ideal R} : (quotient.mk I).ker = I :=
by ext; rw [ring_hom.ker, mem_comap, submodule.mem_bot, quotient.eq_zero_iff_mem]
lemma map_mk_eq_bot_of_le {I J : ideal R} (h : I ≤ J) : I.map (J^.quotient.mk) = ⊥ :=
by { rw [map_eq_bot_iff_le_ker, mk_ker], exact h }
lemma ker_quotient_lift {S : Type v} [comm_ring S] {I : ideal R} (f : R →+* S) (H : I ≤ f.ker) :
(ideal.quotient.lift I f H).ker = (f.ker).map I^.quotient.mk :=
begin
ext x,
split,
{ intro hx,
obtain ⟨y, hy⟩ := quotient.mk_surjective x,
rw [ring_hom.mem_ker, ← hy, ideal.quotient.lift_mk, ← ring_hom.mem_ker] at hx,
rw [← hy, mem_map_iff_of_surjective I^.quotient.mk quotient.mk_surjective],
exact ⟨y, hx, rfl⟩ },
{ intro hx,
rw mem_map_iff_of_surjective I^.quotient.mk quotient.mk_surjective at hx,
obtain ⟨y, hy⟩ := hx,
rw [ring_hom.mem_ker, ← hy.right, ideal.quotient.lift_mk, ← (ring_hom.mem_ker f)],
exact hy.left },
end
theorem map_eq_iff_sup_ker_eq_of_surjective {I J : ideal R} (f : R →+* S)
(hf : function.surjective f) : map f I = map f J ↔ I ⊔ f.ker = J ⊔ f.ker :=
by rw [← (comap_injective_of_surjective f hf).eq_iff, comap_map_of_surjective f hf,
comap_map_of_surjective f hf, ring_hom.ker_eq_comap_bot]
theorem map_radical_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R}
(h : ring_hom.ker f ≤ I) : map f (I.radical) = (map f I).radical :=
begin
rw [radical_eq_Inf, radical_eq_Inf],
have : ∀ J ∈ {J : ideal R | I ≤ J ∧ J.is_prime}, f.ker ≤ J := λ J hJ, le_trans h hJ.left,
convert map_Inf hf this,
refine funext (λ j, propext ⟨_, _⟩),
{ rintros ⟨hj, hj'⟩,
haveI : j.is_prime := hj',
exact ⟨comap f j, ⟨⟨map_le_iff_le_comap.1 hj, comap_is_prime f j⟩,
map_comap_of_surjective f hf j⟩⟩ },
{ rintro ⟨J, ⟨hJ, hJ'⟩⟩,
haveI : J.is_prime := hJ.right,
refine ⟨hJ' ▸ map_mono hJ.left, hJ' ▸ map_is_prime_of_surjective hf (le_trans h hJ.left)⟩ },
end
@[simp] lemma bot_quotient_is_maximal_iff (I : ideal R) :
(⊥ : ideal I.quotient).is_maximal ↔ I.is_maximal :=
⟨λ hI, (@mk_ker _ _ I) ▸
@comap_is_maximal_of_surjective _ _ _ _ (quotient.mk I) ⊥ quotient.mk_surjective hI,
λ hI, @bot_is_maximal _ (@field.to_division_ring _ (@quotient.field _ _ I hI)) ⟩
section quotient_algebra
variables (R) {A : Type*} [comm_ring A] [algebra R A]
/-- The `R`-algebra structure on `A/I` for an `R`-algebra `A` -/
instance {I : ideal A} : algebra R (ideal.quotient I) :=
(ring_hom.comp (ideal.quotient.mk I) (algebra_map R A)).to_algebra
/-- The canonical morphism `A →ₐ[R] I.quotient` as morphism of `R`-algebras, for `I` an ideal of
`A`, where `A` is an `R`-algebra. -/
def quotient.mkₐ (I : ideal A) : A →ₐ[R] I.quotient :=
⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl, λ _, rfl⟩
lemma quotient.alg_map_eq (I : ideal A) :
algebra_map R I.quotient = (algebra_map A I.quotient).comp (algebra_map R A) :=
by simp only [ring_hom.algebra_map_to_algebra, ring_hom.comp_id]
instance [algebra S A] [algebra S R] [is_scalar_tower S R A]
{I : ideal A} : is_scalar_tower S R (ideal.quotient I) :=
is_scalar_tower.of_algebra_map_eq' $ by
rw [quotient.alg_map_eq R, quotient.alg_map_eq S, ring_hom.comp_assoc,
is_scalar_tower.algebra_map_eq S R A]
lemma quotient.mkₐ_to_ring_hom (I : ideal A) :
(quotient.mkₐ R I).to_ring_hom = ideal.quotient.mk I := rfl
@[simp] lemma quotient.mkₐ_eq_mk (I : ideal A) :
⇑(quotient.mkₐ R I) = ideal.quotient.mk I := rfl
/-- The canonical morphism `A →ₐ[R] I.quotient` is surjective. -/
lemma quotient.mkₐ_surjective (I : ideal A) : function.surjective (quotient.mkₐ R I) :=
surjective_quot_mk _
/-- The kernel of `A →ₐ[R] I.quotient` is `I`. -/
@[simp]
lemma quotient.mkₐ_ker (I : ideal A) : (quotient.mkₐ R I : A →+* I.quotient).ker = I :=
ideal.mk_ker
variables {R} {B : Type*} [comm_ring B] [algebra R B]
lemma ker_lift.map_smul (f : A →ₐ[R] B) (r : R) (x : f.to_ring_hom.ker.quotient) :
f.to_ring_hom.ker_lift (r • x) = r • f.to_ring_hom.ker_lift x :=
begin
obtain ⟨a, rfl⟩ := quotient.mkₐ_surjective R _ x,
rw [← alg_hom.map_smul, quotient.mkₐ_eq_mk, ring_hom.ker_lift_mk],
exact f.map_smul _ _
end
/-- The induced algebras morphism from the quotient by the kernel to the codomain.
This is an isomorphism if `f` has a right inverse (`quotient_ker_alg_equiv_of_right_inverse`) /
is surjective (`quotient_ker_alg_equiv_of_surjective`).
-/
def ker_lift_alg (f : A →ₐ[R] B) : f.to_ring_hom.ker.quotient →ₐ[R] B :=
alg_hom.mk' f.to_ring_hom.ker_lift (λ _ _, ker_lift.map_smul f _ _)
@[simp]
lemma ker_lift_alg_mk (f : A →ₐ[R] B) (a : A) :
ker_lift_alg f (quotient.mk f.to_ring_hom.ker a) = f a := rfl
@[simp]
lemma ker_lift_alg_to_ring_hom (f : A →ₐ[R] B) :
(ker_lift_alg f).to_ring_hom = ring_hom.ker_lift f := rfl
/-- The induced algebra morphism from the quotient by the kernel is injective. -/
lemma ker_lift_alg_injective (f : A →ₐ[R] B) : function.injective (ker_lift_alg f) :=
ring_hom.ker_lift_injective f
/-- The first isomorphism theorem for agebras, computable version. -/
def quotient_ker_alg_equiv_of_right_inverse
{f : A →ₐ[R] B} {g : B → A} (hf : function.right_inverse g f) :
f.to_ring_hom.ker.quotient ≃ₐ[R] B :=
{ ..ring_hom.quotient_ker_equiv_of_right_inverse (λ x, show f.to_ring_hom (g x) = x, from hf x),
..ker_lift_alg f}
@[simp]
lemma quotient_ker_alg_equiv_of_right_inverse.apply {f : A →ₐ[R] B} {g : B → A}
(hf : function.right_inverse g f) (x : f.to_ring_hom.ker.quotient) :
quotient_ker_alg_equiv_of_right_inverse hf x = ker_lift_alg f x := rfl
@[simp]
lemma quotient_ker_alg_equiv_of_right_inverse_symm.apply {f : A →ₐ[R] B} {g : B → A}
(hf : function.right_inverse g f) (x : B) :
(quotient_ker_alg_equiv_of_right_inverse hf).symm x = quotient.mkₐ R f.to_ring_hom.ker (g x) :=
rfl
/-- The first isomorphism theorem for algebras. -/
noncomputable def quotient_ker_alg_equiv_of_surjective
{f : A →ₐ[R] B} (hf : function.surjective f) : f.to_ring_hom.ker.quotient ≃ₐ[R] B :=
quotient_ker_alg_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse)
/-- The ring hom `R/I →+* S/J` induced by a ring hom `f : R →+* S` with `I ≤ f⁻¹(J)` -/
def quotient_map {I : ideal R} (J : ideal S) (f : R →+* S) (hIJ : I ≤ J.comap f) :
I.quotient →+* J.quotient :=
(quotient.lift I ((quotient.mk J).comp f) (λ _ ha,
by simpa [function.comp_app, ring_hom.coe_comp, quotient.eq_zero_iff_mem] using hIJ ha))
@[simp]
lemma quotient_map_mk {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f}
{x : R} : quotient_map I f H (quotient.mk J x) = quotient.mk I (f x) :=
quotient.lift_mk J _ _
lemma quotient_map_comp_mk {J : ideal R} {I : ideal S} {f : R →+* S} (H : J ≤ I.comap f) :
(quotient_map I f H).comp (quotient.mk J) = (quotient.mk I).comp f :=
ring_hom.ext (λ x, by simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient_map_mk])
/-- The ring equiv `R/I ≃+* S/J` induced by a ring equiv `f : R ≃+** S`, where `J = f(I)`. -/
@[simps]
def quotient_equiv (I : ideal R) (J : ideal S) (f : R ≃+* S) (hIJ : J = I.map (f : R →+* S)) :
I.quotient ≃+* J.quotient :=
{ inv_fun := quotient_map I ↑f.symm (by {rw hIJ, exact le_of_eq (map_comap_of_equiv I f)}),
left_inv := by {rintro ⟨r⟩, simp },
right_inv := by {rintro ⟨s⟩, simp },
..quotient_map J ↑f (by {rw hIJ, exact @le_comap_map _ S _ _ _ _}) }
/-- `H` and `h` are kept as separate hypothesis since H is used in constructing the quotient map. -/
lemma quotient_map_injective' {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f}
(h : I.comap f ≤ J) : function.injective (quotient_map I f H) :=
begin
refine (quotient_map I f H).injective_iff.2 (λ a ha, _),
obtain ⟨r, rfl⟩ := quotient.mk_surjective a,
rw [quotient_map_mk, quotient.eq_zero_iff_mem] at ha,
exact (quotient.eq_zero_iff_mem).mpr (h ha),
end
/-- If we take `J = I.comap f` then `quotient_map` is injective automatically. -/
lemma quotient_map_injective {I : ideal S} {f : R →+* S} :
function.injective (quotient_map I f le_rfl) :=
quotient_map_injective' le_rfl
lemma quotient_map_surjective {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f}
(hf : function.surjective f) : function.surjective (quotient_map I f H) :=
λ x, let ⟨x, hx⟩ := quotient.mk_surjective x in
let ⟨y, hy⟩ := hf x in ⟨(quotient.mk J) y, by simp [hx, hy]⟩
/-- Commutativity of a square is preserved when taking quotients by an ideal. -/
lemma comp_quotient_map_eq_of_comp_eq {R' S' : Type*} [comm_ring R'] [comm_ring S']
{f : R →+* S} {f' : R' →+* S'} {g : R →+* R'} {g' : S →+* S'} (hfg : f'.comp g = g'.comp f)
(I : ideal S') : (quotient_map I g' le_rfl).comp (quotient_map (I.comap g') f le_rfl) =
(quotient_map I f' le_rfl).comp (quotient_map (I.comap f') g
(le_of_eq (trans (comap_comap f g') (hfg ▸ (comap_comap g f'))))) :=
begin
refine ring_hom.ext (λ a, _),
obtain ⟨r, rfl⟩ := quotient.mk_surjective a,
simp only [ring_hom.comp_apply, quotient_map_mk],
exact congr_arg (quotient.mk I) (trans (g'.comp_apply f r).symm (hfg ▸ (f'.comp_apply g r))),
end
variables {I : ideal R} {J: ideal S} [algebra R S]
/-- The algebra hom `A/I →+* S/J` induced by an algebra hom `f : A →ₐ[R] S` with `I ≤ f⁻¹(J)`. -/
def quotient_mapₐ {I : ideal A} (J : ideal S) (f : A →ₐ[R] S) (hIJ : I ≤ J.comap f) :
I.quotient →ₐ[R] J.quotient :=
{ commutes' := λ r,
begin
have h : (algebra_map R I.quotient) r = (quotient.mk I) (algebra_map R A r) := rfl,
simpa [h]
end
..quotient_map J ↑f hIJ }
@[simp]
lemma quotient_map_mkₐ {I : ideal A} (J : ideal S) (f : A →ₐ[R] S) (H : I ≤ J.comap f)
{x : A} : quotient_mapₐ J f H (quotient.mk I x) = quotient.mkₐ R J (f x) := rfl
lemma quotient_map_comp_mkₐ {I : ideal A} (J : ideal S) (f : A →ₐ[R] S) (H : I ≤ J.comap f) :
(quotient_mapₐ J f H).comp (quotient.mkₐ R I) = (quotient.mkₐ R J).comp f :=
alg_hom.ext (λ x, by simp only [quotient_map_mkₐ, quotient.mkₐ_eq_mk, alg_hom.comp_apply])
/-- The algebra equiv `A/I ≃ₐ[R] S/J` induced by an algebra equiv `f : A ≃ₐ[R] S`,
where`J = f(I)`. -/
def quotient_equiv_alg (I : ideal A) (J : ideal S) (f : A ≃ₐ[R] S) (hIJ : J = I.map (f : A →+* S)) :
I.quotient ≃ₐ[R] J.quotient :=
{ commutes' := λ r,
begin
have h : (algebra_map R I.quotient) r = (quotient.mk I) (algebra_map R A r) := rfl,
simpa [h]
end,
..quotient_equiv I J (f : A ≃+* S) hIJ }
@[priority 100]
instance quotient_algebra : algebra (J.comap (algebra_map R S)).quotient J.quotient :=
(quotient_map J (algebra_map R S) (le_of_eq rfl)).to_algebra
lemma algebra_map_quotient_injective :
function.injective (algebra_map (J.comap (algebra_map R S)).quotient J.quotient) :=
begin
rintros ⟨a⟩ ⟨b⟩ hab,
replace hab := quotient.eq.mp hab,
rw ← ring_hom.map_sub at hab,
exact quotient.eq.mpr hab
end
end quotient_algebra
end comm_ring
end ideal
namespace submodule
variables {R : Type u} {M : Type v}
variables [comm_ring R] [add_comm_group M] [module R M]
-- TODO: show `[algebra R A] : algebra (ideal R) A` too
instance module_submodule : module (ideal R) (submodule R M) :=
{ smul_add := smul_sup,
add_smul := sup_smul,
mul_smul := submodule.smul_assoc,
one_smul := by simp,
zero_smul := bot_smul,
smul_zero := smul_bot }
end submodule
namespace ring_hom
variables {A B C : Type*} [ring A] [ring B] [ring C]
variables (f : A →+* B) (f_inv : B → A)
/-- Auxiliary definition used to define `lift_of_right_inverse` -/
def lift_of_right_inverse_aux
(hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) :
B →+* C :=
{ to_fun := λ b, g (f_inv b),
map_one' :=
begin
rw [← g.map_one, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker],
apply hg,
rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_one],
exact hf 1
end,
map_mul' :=
begin
intros x y,
rw [← g.map_mul, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker],
apply hg,
rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_mul],
simp only [hf _],
end,
.. add_monoid_hom.lift_of_right_inverse f.to_add_monoid_hom f_inv hf ⟨g.to_add_monoid_hom, hg⟩ }
@[simp] lemma lift_of_right_inverse_aux_comp_apply
(hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) (a : A) :
(f.lift_of_right_inverse_aux f_inv hf g hg) (f a) = g a :=
f.to_add_monoid_hom.lift_of_right_inverse_comp_apply f_inv hf ⟨g.to_add_monoid_hom, hg⟩ a
/-- `lift_of_right_inverse f hf g hg` is the unique ring homomorphism `φ`
* such that `φ.comp f = g` (`ring_hom.lift_of_right_inverse_comp`),
* where `f : A →+* B` is has a right_inverse `f_inv` (`hf`),
* and `g : B →+* C` satisfies `hg : f.ker ≤ g.ker`.
See `ring_hom.eq_lift_of_right_inverse` for the uniqueness lemma.
```
A .
| \
f | \ g
| \
v \⌟
B ----> C
∃!φ
```
-/
def lift_of_right_inverse
(hf : function.right_inverse f_inv f) : {g : A →+* C // f.ker ≤ g.ker} ≃ (B →+* C) :=
{ to_fun := λ g, f.lift_of_right_inverse_aux f_inv hf g.1 g.2,
inv_fun := λ φ, ⟨φ.comp f, λ x hx, (mem_ker _).mpr $ by simp [(mem_ker _).mp hx]⟩,
left_inv := λ g, by {
ext,
simp only [comp_apply, lift_of_right_inverse_aux_comp_apply, subtype.coe_mk,
subtype.val_eq_coe], },
right_inv := λ φ, by {
ext b,
simp [lift_of_right_inverse_aux, hf b], } }
/-- A non-computable version of `ring_hom.lift_of_right_inverse` for when no computable right
inverse is available, that uses `function.surj_inv`. -/
@[simp]
noncomputable abbreviation lift_of_surjective
(hf : function.surjective f) : {g : A →+* C // f.ker ≤ g.ker} ≃ (B →+* C) :=
f.lift_of_right_inverse (function.surj_inv hf) (function.right_inverse_surj_inv hf)
lemma lift_of_right_inverse_comp_apply
(hf : function.right_inverse f_inv f) (g : {g : A →+* C // f.ker ≤ g.ker}) (x : A) :
(f.lift_of_right_inverse f_inv hf g) (f x) = g x :=
f.lift_of_right_inverse_aux_comp_apply f_inv hf g.1 g.2 x
lemma lift_of_right_inverse_comp (hf : function.right_inverse f_inv f)
(g : {g : A →+* C // f.ker ≤ g.ker}) :
(f.lift_of_right_inverse f_inv hf g).comp f = g :=
ring_hom.ext $ f.lift_of_right_inverse_comp_apply f_inv hf g
lemma eq_lift_of_right_inverse (hf : function.right_inverse f_inv f) (g : A →+* C)
(hg : f.ker ≤ g.ker) (h : B →+* C) (hh : h.comp f = g) :
h = (f.lift_of_right_inverse f_inv hf ⟨g, hg⟩) :=
begin
simp_rw ←hh,
exact ((f.lift_of_right_inverse f_inv hf).apply_symm_apply _).symm,
end
end ring_hom
namespace double_quot
open ideal
variables {R : Type u} [comm_ring R] (I J : ideal R)
/-- The obvious ring hom `R/I → R/(I ⊔ J)` -/
def quot_left_to_quot_sup : I.quotient →+* (I ⊔ J).quotient :=
ideal.quotient.factor I (I ⊔ J) le_sup_left
/-- The kernel of `quot_left_to_quot_sup` -/
lemma ker_quot_left_to_quot_sup :
(quot_left_to_quot_sup I J).ker = J.map (ideal.quotient.mk I) :=
by simp only [mk_ker, sup_idem, sup_comm, quot_left_to_quot_sup, quotient.factor, ker_quotient_lift,
map_eq_iff_sup_ker_eq_of_surjective I^.quotient.mk quotient.mk_surjective, ← sup_assoc]
/-- The ring homomorphism `(R/I)/J' -> R/(I ⊔ J)` induced by `quot_left_to_quot_sup` where `J'`
is the image of `J` in `R/I`-/
def quot_quot_to_quot_sup : (J.map (ideal.quotient.mk I)).quotient →+* (I ⊔ J).quotient :=
ideal.quotient.lift (ideal.map (ideal.quotient.mk I) J) (quot_left_to_quot_sup I J)
(ker_quot_left_to_quot_sup I J).symm.le
/-- The composite of the maps `R → (R/I)` and `(R/I) → (R/I)/J'` -/
def quot_quot_mk : R →+* (J.map I^.quotient.mk).quotient :=
((J.map I^.quotient.mk)^.quotient.mk).comp I^.quotient.mk
/-- The kernel of `quot_quot_mk` -/
lemma ker_quot_quot_mk : (quot_quot_mk I J).ker = I ⊔ J :=
by rw [ring_hom.ker_eq_comap_bot, quot_quot_mk, ← comap_comap, ← ring_hom.ker, mk_ker,
comap_map_of_surjective (ideal.quotient.mk I) (quotient.mk_surjective), ← ring_hom.ker, mk_ker,
sup_comm]
/-- The ring homomorphism `R/(I ⊔ J) → (R/I)/J' `induced by `quot_quot_mk` -/
def lift_sup_quot_quot_mk (I J : ideal R) : (I ⊔ J).quotient →+*
(J.map (ideal.quotient.mk I)).quotient :=
ideal.quotient.lift (I ⊔ J) (quot_quot_mk I J) (ker_quot_quot_mk I J).symm.le
/-- `quot_quot_to_quot_add` and `lift_sup_double_qot_mk` are inverse isomorphisms -/
def quot_quot_equiv_quot_sup : (J.map (ideal.quotient.mk I)).quotient ≃+* (I ⊔ J).quotient :=
ring_equiv.of_hom_inv (quot_quot_to_quot_sup I J) (lift_sup_quot_quot_mk I J)
(by { ext z, refl }) (by { ext z, refl })
end double_quot
|
8bd68573f24d1e9c33071aee016de3d37e645106 | c1a29ca460720df88ab68dc42d9a1a02e029d505 | /examples/basics/order_divisibility_2_4.lean | 8622d5aeeb2c1a3c22f86299081b29e26681f975 | [] | no_license | agusakov/mathematics_in_lean | acb5b3d659e4522ae4b4836ea550527f03f6546c | 2539562e4d91c858c73dbecb5b282ce1a7d38b6d | refs/heads/master | 1,665,963,365,241 | 1,592,080,022,000 | 1,592,080,022,000 | 272,078,062 | 0 | 0 | null | 1,592,078,772,000 | 1,592,078,772,000 | null | UTF-8 | Lean | false | false | 2,299 | lean | import data.real.basic
variables a b c d : ℝ
-- BEGIN
#check (min_le_left a b : min a b ≤ a)
#check (min_le_right a b : min a b ≤ b)
#check (le_min : c ≤ a → c ≤ b → c ≤ min a b)
-- ENDimport data.real.basic
variables a b : ℝ
-- BEGIN
example : min a b = min b a :=
begin
apply le_antisymm,
{ show min a b ≤ min b a,
apply le_min,
{ apply min_le_right },
apply min_le_left },
{ show min b a ≤ min a b,
apply le_min,
{ apply min_le_right },
apply min_le_left }
end
-- ENDimport data.real.basic
variables a b : ℝ
-- BEGIN
example : min a b = min b a :=
begin
have h : ∀ x y, min x y ≤ min y x,
{ intros x y,
apply le_min,
apply min_le_right,
apply min_le_left },
apply le_antisymm, apply h, apply h
end
-- ENDimport data.real.basic
variables a b : ℝ
-- BEGIN
example : min a b = min b a :=
begin
apply le_antisymm,
repeat {
apply le_min,
apply min_le_right,
apply min_le_left }
end
-- ENDimport data.real.basic
variables a b c : ℝ
-- BEGIN
example : max a b = max b a :=
begin
sorry
end
example : min (min a b) c = min a (min b c) :=
sorry
-- ENDimport data.real.basic
variables a b c : ℝ
-- BEGIN
lemma aux : min a b + c ≤ min (a + c) (b + c) :=
begin
sorry
end
example : min a b + c = min (a + c) (b + c) :=
begin
sorry
end
-- ENDimport data.real.basic
-- BEGIN
#check (abs_add : ∀ a b : ℝ, abs (a + b) ≤ abs a + abs b)
-- ENDimport data.real.basic
variables a b : ℝ
-- BEGIN
example : abs a - abs b ≤ abs (a - b) :=
begin
sorry
end
-- ENDimport data.nat.gcd
variables x y z : ℕ
example (h₀ : x ∣ y) (h₁ : y ∣ z) : x ∣ z :=
dvd_trans h₀ h₁
example : x ∣ y * x * z :=
begin
apply dvd_mul_of_dvd_left,
apply dvd_mul_left
end
example : x ∣ x^2 :=
begin
rw nat.pow_two,
apply dvd_mul_left
endimport data.nat.gcd
variables w x y z : ℕ
example (h : x ∣ w): x ∣ y * (x * z) + x^2 + w^2 :=
begin
sorry
endimport data.nat.gcd
open nat
variables n : ℕ
#check (gcd_zero_right n : gcd n 0 = n)
#check (gcd_zero_left n : gcd 0 n = n)
#check (lcm_zero_right n : lcm n 0 = 0)
#check (lcm_zero_left n : lcm 0 n = 0)import data.nat.gcd
open nat
variables m n : ℕ
-- BEGIN
example : gcd m n = gcd n m :=
begin
sorry
end
-- END |
b73f1e4072eef4b39e4a5b87062f5fc72ff24760 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/ring_theory/subring/basic.lean | 68334a8fdd49ddc0981a820fef3bf0263cc32285 | [
"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 | 47,564 | lean | /-
Copyright (c) 2020 Ashvni Narayanan. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ashvni Narayanan
-/
import group_theory.subgroup.basic
import ring_theory.subsemiring.basic
/-!
# Subrings
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Let `R` be a ring. This file defines the "bundled" subring type `subring R`, a type
whose terms correspond to subrings of `R`. This is the preferred way to talk
about subrings in mathlib. Unbundled subrings (`s : set R` and `is_subring s`)
are not in this file, and they will ultimately be deprecated.
We prove that subrings are a complete lattice, and that you can `map` (pushforward) and
`comap` (pull back) them along ring homomorphisms.
We define the `closure` construction from `set R` to `subring R`, sending a subset of `R`
to the subring it generates, and prove that it is a Galois insertion.
## Main definitions
Notation used here:
`(R : Type u) [ring R] (S : Type u) [ring S] (f g : R →+* S)`
`(A : subring R) (B : subring S) (s : set R)`
* `subring R` : the type of subrings of a ring `R`.
* `instance : complete_lattice (subring R)` : the complete lattice structure on the subrings.
* `subring.center` : the center of a ring `R`.
* `subring.closure` : subring closure of a set, i.e., the smallest subring that includes the set.
* `subring.gi` : `closure : set M → subring M` and coercion `coe : subring M → set M`
form a `galois_insertion`.
* `comap f B : subring A` : the preimage of a subring `B` along the ring homomorphism `f`
* `map f A : subring B` : the image of a subring `A` along the ring homomorphism `f`.
* `prod A B : subring (R × S)` : the product of subrings
* `f.range : subring B` : the range of the ring homomorphism `f`.
* `eq_locus f g : subring R` : given ring homomorphisms `f g : R →+* S`,
the subring of `R` where `f x = g x`
## Implementation notes
A subring is implemented as a subsemiring which is also an additive subgroup.
The initial PR was as a submonoid which is also an additive subgroup.
Lattice inclusion (e.g. `≤` and `⊓`) is used rather than set notation (`⊆` and `∩`), although
`∈` is defined as membership of a subring's underlying set.
## Tags
subring, subrings
-/
open_locale big_operators
universes u v w
variables {R : Type u} {S : Type v} {T : Type w} [ring R]
section subring_class
/-- `subring_class S R` states that `S` is a type of subsets `s ⊆ R` that
are both a multiplicative submonoid and an additive subgroup. -/
class subring_class (S : Type*) (R : Type u) [ring R] [set_like S R]
extends subsemiring_class S R, neg_mem_class S R : Prop
@[priority 100] -- See note [lower instance priority]
instance subring_class.add_subgroup_class (S : Type*) (R : Type u) [set_like S R]
[ring R] [h : subring_class S R] : add_subgroup_class S R :=
{ .. h }
variables [set_like S R] [hSR : subring_class S R] (s : S)
include hSR
lemma coe_int_mem (n : ℤ) : (n : R) ∈ s :=
by simp only [← zsmul_one, zsmul_mem, one_mem]
namespace subring_class
@[priority 75]
instance to_has_int_cast : has_int_cast s :=
⟨λ n, ⟨n, coe_int_mem s n⟩⟩
/-- A subring of a ring inherits a ring structure -/
@[priority 75] -- Prefer subclasses of `ring` over subclasses of `subring_class`.
instance to_ring : ring s :=
subtype.coe_injective.ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
(λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl)
omit hSR
/-- A subring of a `comm_ring` is a `comm_ring`. -/
@[priority 75] -- Prefer subclasses of `ring` over subclasses of `subring_class`.
instance to_comm_ring {R} [comm_ring R] [set_like S R] [subring_class S R] : comm_ring s :=
subtype.coe_injective.comm_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
(λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl)
/-- A subring of a domain is a domain. -/
@[priority 75] -- Prefer subclasses of `ring` over subclasses of `subring_class`.
instance {R} [ring R] [is_domain R] [set_like S R] [subring_class S R] : is_domain s :=
no_zero_divisors.to_is_domain _
/-- A subring of an `ordered_ring` is an `ordered_ring`. -/
@[priority 75] -- Prefer subclasses of `ring` over subclasses of `subring_class`.
instance to_ordered_ring {R} [ordered_ring R] [set_like S R] [subring_class S R] :
ordered_ring s :=
subtype.coe_injective.ordered_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
(λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl)
/-- A subring of an `ordered_comm_ring` is an `ordered_comm_ring`. -/
@[priority 75] -- Prefer subclasses of `ring` over subclasses of `subring_class`.
instance to_ordered_comm_ring {R} [ordered_comm_ring R] [set_like S R] [subring_class S R] :
ordered_comm_ring s :=
subtype.coe_injective.ordered_comm_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)
(λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl)
/-- A subring of a `linear_ordered_ring` is a `linear_ordered_ring`. -/
@[priority 75] -- Prefer subclasses of `ring` over subclasses of `subring_class`.
instance to_linear_ordered_ring {R} [linear_ordered_ring R] [set_like S R] [subring_class S R] :
linear_ordered_ring s :=
subtype.coe_injective.linear_ordered_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)
(λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl) (λ _ _, rfl)
(λ _ _, rfl)
/-- A subring of a `linear_ordered_comm_ring` is a `linear_ordered_comm_ring`. -/
@[priority 75] -- Prefer subclasses of `ring` over subclasses of `subring_class`.
instance to_linear_ordered_comm_ring {R} [linear_ordered_comm_ring R] [set_like S R]
[subring_class S R] : linear_ordered_comm_ring s :=
subtype.coe_injective.linear_ordered_comm_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)
(λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl) (λ _ _, rfl)
(λ _ _, rfl)
include hSR
/-- The natural ring hom from a subring of ring `R` to `R`. -/
def subtype (s : S) : s →+* R :=
{ to_fun := coe,
.. submonoid_class.subtype s,
.. add_subgroup_class.subtype s }
@[simp] theorem coe_subtype : (subtype s : s → R) = coe := rfl
@[simp, norm_cast] lemma coe_nat_cast (n : ℕ) : ((n : s) : R) = n := map_nat_cast (subtype s) n
@[simp, norm_cast] lemma coe_int_cast (n : ℤ) : ((n : s) : R) = n := map_int_cast (subtype s) n
end subring_class
end subring_class
variables [ring S] [ring T]
set_option old_structure_cmd true
/-- `subring R` is the type of subrings of `R`. A subring of `R` is a subset `s` that is a
multiplicative submonoid and an additive subgroup. Note in particular that it shares the
same 0 and 1 as R. -/
structure subring (R : Type u) [ring R] extends subsemiring R, add_subgroup R
/-- Reinterpret a `subring` as a `subsemiring`. -/
add_decl_doc subring.to_subsemiring
/-- Reinterpret a `subring` as an `add_subgroup`. -/
add_decl_doc subring.to_add_subgroup
namespace subring
/-- The underlying submonoid of a subring. -/
def to_submonoid (s : subring R) : submonoid R :=
{ carrier := s.carrier,
..s.to_subsemiring.to_submonoid }
instance : set_like (subring R) R :=
{ coe := subring.carrier,
coe_injective' := λ p q h, by cases p; cases q; congr' }
instance : subring_class (subring R) R :=
{ zero_mem := zero_mem',
add_mem := add_mem',
one_mem := one_mem',
mul_mem := mul_mem',
neg_mem := neg_mem' }
@[simp]
lemma mem_carrier {s : subring R} {x : R} : x ∈ s.carrier ↔ x ∈ s := iff.rfl
@[simp]
lemma mem_mk {S : set R} {x : R} (h₁ h₂ h₃ h₄ h₅) :
x ∈ (⟨S, h₁, h₂, h₃, h₄, h₅⟩ : subring R) ↔ x ∈ S := iff.rfl
@[simp] lemma coe_set_mk (S : set R) (h₁ h₂ h₃ h₄ h₅) :
((⟨S, h₁, h₂, h₃, h₄, h₅⟩ : subring R) : set R) = S := rfl
@[simp]
lemma mk_le_mk {S S' : set R} (h₁ h₂ h₃ h₄ h₅ h₁' h₂' h₃' h₄' h₅') :
(⟨S, h₁, h₂, h₃, h₄, h₅⟩ : subring R) ≤ (⟨S', h₁', h₂', h₃', h₄', h₅'⟩ : subring R) ↔ S ⊆ S' :=
iff.rfl
/-- Two subrings are equal if they have the same elements. -/
@[ext] theorem ext {S T : subring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h
/-- Copy of a subring with a new `carrier` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (S : subring R) (s : set R) (hs : s = ↑S) : subring R :=
{ carrier := s,
neg_mem' := λ _, hs.symm ▸ S.neg_mem',
..S.to_subsemiring.copy s hs }
@[simp] lemma coe_copy (S : subring R) (s : set R) (hs : s = ↑S) :
(S.copy s hs : set R) = s := rfl
lemma copy_eq (S : subring R) (s : set R) (hs : s = ↑S) : S.copy s hs = S :=
set_like.coe_injective hs
lemma to_subsemiring_injective : function.injective (to_subsemiring : subring R → subsemiring R)
| r s h := ext (set_like.ext_iff.mp h : _)
@[mono]
lemma to_subsemiring_strict_mono : strict_mono (to_subsemiring : subring R → subsemiring R) :=
λ _ _, id
@[mono]
lemma to_subsemiring_mono : monotone (to_subsemiring : subring R → subsemiring R) :=
to_subsemiring_strict_mono.monotone
lemma to_add_subgroup_injective : function.injective (to_add_subgroup : subring R → add_subgroup R)
| r s h := ext (set_like.ext_iff.mp h : _)
@[mono]
lemma to_add_subgroup_strict_mono : strict_mono (to_add_subgroup : subring R → add_subgroup R) :=
λ _ _, id
@[mono]
lemma to_add_subgroup_mono : monotone (to_add_subgroup : subring R → add_subgroup R) :=
to_add_subgroup_strict_mono.monotone
lemma to_submonoid_injective : function.injective (to_submonoid : subring R → submonoid R)
| r s h := ext (set_like.ext_iff.mp h : _)
@[mono]
lemma to_submonoid_strict_mono : strict_mono (to_submonoid : subring R → submonoid R) :=
λ _ _, id
@[mono]
lemma to_submonoid_mono : monotone (to_submonoid : subring R → submonoid R) :=
to_submonoid_strict_mono.monotone
/-- Construct a `subring R` from a set `s`, a submonoid `sm`, and an additive
subgroup `sa` such that `x ∈ s ↔ x ∈ sm ↔ x ∈ sa`. -/
protected def mk' (s : set R) (sm : submonoid R) (sa : add_subgroup R)
(hm : ↑sm = s) (ha : ↑sa = s) :
subring R :=
{ carrier := s,
zero_mem' := ha ▸ sa.zero_mem,
one_mem' := hm ▸ sm.one_mem,
add_mem' := λ x y, by simpa only [← ha] using sa.add_mem,
mul_mem' := λ x y, by simpa only [← hm] using sm.mul_mem,
neg_mem' := λ x, by simpa only [← ha] using sa.neg_mem, }
@[simp] lemma coe_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_subgroup R} (ha : ↑sa = s) :
(subring.mk' s sm sa hm ha : set R) = s := rfl
@[simp] lemma mem_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_subgroup R} (ha : ↑sa = s) {x : R} :
x ∈ subring.mk' s sm sa hm ha ↔ x ∈ s :=
iff.rfl
@[simp] lemma mk'_to_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_subgroup R} (ha : ↑sa = s) :
(subring.mk' s sm sa hm ha).to_submonoid = sm :=
set_like.coe_injective hm.symm
@[simp] lemma mk'_to_add_subgroup {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_subgroup R} (ha : ↑sa =s) :
(subring.mk' s sm sa hm ha).to_add_subgroup = sa :=
set_like.coe_injective ha.symm
end subring
/-- A `subsemiring` containing -1 is a `subring`. -/
def subsemiring.to_subring (s : subsemiring R) (hneg : (-1 : R) ∈ s) : subring R :=
{ neg_mem' := by { rintros x, rw <-neg_one_mul, apply subsemiring.mul_mem, exact hneg, }
..s.to_submonoid, ..s.to_add_submonoid }
namespace subring
variables (s : subring R)
/-- A subring contains the ring's 1. -/
protected theorem one_mem : (1 : R) ∈ s := one_mem _
/-- A subring contains the ring's 0. -/
protected theorem zero_mem : (0 : R) ∈ s := zero_mem _
/-- A subring is closed under multiplication. -/
protected theorem mul_mem {x y : R} : x ∈ s → y ∈ s → x * y ∈ s := mul_mem
/-- A subring is closed under addition. -/
protected theorem add_mem {x y : R} : x ∈ s → y ∈ s → x + y ∈ s := add_mem
/-- A subring is closed under negation. -/
protected theorem neg_mem {x : R} : x ∈ s → -x ∈ s := neg_mem
/-- A subring is closed under subtraction -/
protected theorem sub_mem {x y : R} (hx : x ∈ s) (hy : y ∈ s) : x - y ∈ s := sub_mem hx hy
/-- Product of a list of elements in a subring is in the subring. -/
protected lemma list_prod_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.prod ∈ s := list_prod_mem
/-- Sum of a list of elements in a subring is in the subring. -/
protected lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s := list_sum_mem
/-- Product of a multiset of elements in a subring of a `comm_ring` is in the subring. -/
protected lemma multiset_prod_mem {R} [comm_ring R] (s : subring R) (m : multiset R) :
(∀a ∈ m, a ∈ s) → m.prod ∈ s :=
multiset_prod_mem _
/-- Sum of a multiset of elements in an `subring` of a `ring` is
in the `subring`. -/
protected lemma multiset_sum_mem {R} [ring R] (s : subring R) (m : multiset R) :
(∀a ∈ m, a ∈ s) → m.sum ∈ s :=
multiset_sum_mem _
/-- Product of elements of a subring of a `comm_ring` indexed by a `finset` is in the
subring. -/
protected lemma prod_mem {R : Type*} [comm_ring R] (s : subring R)
{ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) :
∏ i in t, f i ∈ s :=
prod_mem h
/-- Sum of elements in a `subring` of a `ring` indexed by a `finset`
is in the `subring`. -/
protected lemma sum_mem {R : Type*} [ring R] (s : subring R)
{ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) :
∑ i in t, f i ∈ s :=
sum_mem h
/-- A subring of a ring inherits a ring structure -/
instance to_ring : ring s :=
subtype.coe_injective.ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
(λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl)
protected lemma zsmul_mem {x : R} (hx : x ∈ s) (n : ℤ) : n • x ∈ s := zsmul_mem hx n
protected lemma pow_mem {x : R} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := pow_mem hx n
@[simp, norm_cast] lemma coe_add (x y : s) : (↑(x + y) : R) = ↑x + ↑y := rfl
@[simp, norm_cast] lemma coe_neg (x : s) : (↑(-x) : R) = -↑x := rfl
@[simp, norm_cast] lemma coe_mul (x y : s) : (↑(x * y) : R) = ↑x * ↑y := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : s) : R) = 1 := rfl
@[simp, norm_cast] lemma coe_pow (x : s) (n : ℕ) : (↑(x ^ n) : R) = x ^ n :=
submonoid_class.coe_pow x n
-- TODO: can be generalized to `add_submonoid_class`
@[simp] lemma coe_eq_zero_iff {x : s} : (x : R) = 0 ↔ x = 0 :=
⟨λ h, subtype.ext (trans h s.coe_zero.symm),
λ h, h.symm ▸ s.coe_zero⟩
/-- A subring of a `comm_ring` is a `comm_ring`. -/
instance to_comm_ring {R} [comm_ring R] (s : subring R) : comm_ring s :=
subtype.coe_injective.comm_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
(λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl)
/-- A subring of a non-trivial ring is non-trivial. -/
instance {R} [ring R] [nontrivial R] (s : subring R) : nontrivial s :=
s.to_subsemiring.nontrivial
/-- A subring of a ring with no zero divisors has no zero divisors. -/
instance {R} [ring R] [no_zero_divisors R] (s : subring R) : no_zero_divisors s :=
s.to_subsemiring.no_zero_divisors
/-- A subring of a domain is a domain. -/
instance {R} [ring R] [is_domain R] (s : subring R) : is_domain s :=
no_zero_divisors.to_is_domain _
/-- A subring of an `ordered_ring` is an `ordered_ring`. -/
instance to_ordered_ring {R} [ordered_ring R] (s : subring R) : ordered_ring s :=
subtype.coe_injective.ordered_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl)
(λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl)
/-- A subring of an `ordered_comm_ring` is an `ordered_comm_ring`. -/
instance to_ordered_comm_ring {R} [ordered_comm_ring R] (s : subring R) : ordered_comm_ring s :=
subtype.coe_injective.ordered_comm_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)
(λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl)
/-- A subring of a `linear_ordered_ring` is a `linear_ordered_ring`. -/
instance to_linear_ordered_ring {R} [linear_ordered_ring R] (s : subring R) :
linear_ordered_ring s :=
subtype.coe_injective.linear_ordered_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)
(λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl) (λ _ _, rfl)
(λ _ _, rfl)
/-- A subring of a `linear_ordered_comm_ring` is a `linear_ordered_comm_ring`. -/
instance to_linear_ordered_comm_ring {R} [linear_ordered_comm_ring R] (s : subring R) :
linear_ordered_comm_ring s :=
subtype.coe_injective.linear_ordered_comm_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)
(λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl) (λ _ _, rfl)
(λ _ _, rfl)
/-- The natural ring hom from a subring of ring `R` to `R`. -/
def subtype (s : subring R) : s →+* R :=
{ to_fun := coe,
.. s.to_submonoid.subtype, .. s.to_add_subgroup.subtype }
@[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl
@[simp, norm_cast] lemma coe_nat_cast : ∀ n : ℕ, ((n : s) : R) = n := map_nat_cast s.subtype
@[simp, norm_cast] lemma coe_int_cast : ∀ n : ℤ, ((n : s) : R) = n := map_int_cast s.subtype
/-! ## Partial order -/
@[simp] lemma mem_to_submonoid {s : subring R} {x : R} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl
@[simp] lemma coe_to_submonoid (s : subring R) : (s.to_submonoid : set R) = s := rfl
@[simp] lemma mem_to_add_subgroup {s : subring R} {x : R} :
x ∈ s.to_add_subgroup ↔ x ∈ s := iff.rfl
@[simp] lemma coe_to_add_subgroup (s : subring R) : (s.to_add_subgroup : set R) = s := rfl
/-! ## top -/
/-- The subring `R` of the ring `R`. -/
instance : has_top (subring R) :=
⟨{ .. (⊤ : submonoid R), .. (⊤ : add_subgroup R) }⟩
@[simp] lemma mem_top (x : R) : x ∈ (⊤ : subring R) := set.mem_univ x
@[simp] lemma coe_top : ((⊤ : subring R) : set R) = set.univ := rfl
/-- The ring equiv between the top element of `subring R` and `R`. -/
@[simps]
def top_equiv : (⊤ : subring R) ≃+* R := subsemiring.top_equiv
/-! ## comap -/
/-- The preimage of a subring along a ring homomorphism is a subring. -/
def comap {R : Type u} {S : Type v} [ring R] [ring S]
(f : R →+* S) (s : subring S) : subring R :=
{ carrier := f ⁻¹' s.carrier,
.. s.to_submonoid.comap (f : R →* S),
.. s.to_add_subgroup.comap (f : R →+ S) }
@[simp] lemma coe_comap (s : subring S) (f : R →+* S) : (s.comap f : set R) = f ⁻¹' s := rfl
@[simp]
lemma mem_comap {s : subring S} {f : R →+* S} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl
lemma comap_comap (s : subring T) (g : S →+* T) (f : R →+* S) :
(s.comap g).comap f = s.comap (g.comp f) :=
rfl
/-! ## map -/
/-- The image of a subring along a ring homomorphism is a subring. -/
def map {R : Type u} {S : Type v} [ring R] [ring S]
(f : R →+* S) (s : subring R) : subring S :=
{ carrier := f '' s.carrier,
.. s.to_submonoid.map (f : R →* S),
.. s.to_add_subgroup.map (f : R →+ S) }
@[simp] lemma coe_map (f : R →+* S) (s : subring R) : (s.map f : set S) = f '' s := rfl
@[simp] lemma mem_map {f : R →+* S} {s : subring R} {y : S} :
y ∈ s.map f ↔ ∃ x ∈ s, f x = y :=
set.mem_image_iff_bex
@[simp] lemma map_id : s.map (ring_hom.id R) = s :=
set_like.coe_injective $ set.image_id _
lemma map_map (g : S →+* T) (f : R →+* S) : (s.map f).map g = s.map (g.comp f) :=
set_like.coe_injective $ set.image_image _ _ _
lemma map_le_iff_le_comap {f : R →+* S} {s : subring R} {t : subring S} :
s.map f ≤ t ↔ s ≤ t.comap f :=
set.image_subset_iff
lemma gc_map_comap (f : R →+* S) : galois_connection (map f) (comap f) :=
λ S T, map_le_iff_le_comap
/-- A subring is isomorphic to its image under an injective function -/
noncomputable def equiv_map_of_injective
(f : R →+* S) (hf : function.injective f) : s ≃+* s.map f :=
{ map_mul' := λ _ _, subtype.ext (f.map_mul _ _),
map_add' := λ _ _, subtype.ext (f.map_add _ _),
..equiv.set.image f s hf }
@[simp] lemma coe_equiv_map_of_injective_apply
(f : R →+* S) (hf : function.injective f) (x : s) :
(equiv_map_of_injective s f hf x : S) = f x := rfl
end subring
namespace ring_hom
variables (g : S →+* T) (f : R →+* S)
/-! ## range -/
/-- The range of a ring homomorphism, as a subring of the target. See Note [range copy pattern]. -/
def range {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) : subring S :=
((⊤ : subring R).map f).copy (set.range f) set.image_univ.symm
@[simp] lemma coe_range : (f.range : set S) = set.range f := rfl
@[simp] lemma mem_range {f : R →+* S} {y : S} : y ∈ f.range ↔ ∃ x, f x = y := iff.rfl
lemma range_eq_map (f : R →+* S) : f.range = subring.map f ⊤ :=
by { ext, simp }
lemma mem_range_self (f : R →+* S) (x : R) : f x ∈ f.range :=
mem_range.mpr ⟨x, rfl⟩
lemma map_range : f.range.map g = (g.comp f).range :=
by simpa only [range_eq_map] using (⊤ : subring R).map_map g f
/-- The range of a ring homomorphism is a fintype, if the domain is a fintype.
Note: this instance can form a diamond with `subtype.fintype` in the
presence of `fintype S`. -/
instance fintype_range [fintype R] [decidable_eq S] (f : R →+* S) : fintype (range f) :=
set.fintype_range f
end ring_hom
namespace subring
/-! ## bot -/
instance : has_bot (subring R) := ⟨(int.cast_ring_hom R).range⟩
instance : inhabited (subring R) := ⟨⊥⟩
lemma coe_bot : ((⊥ : subring R) : set R) = set.range (coe : ℤ → R) :=
ring_hom.coe_range (int.cast_ring_hom R)
lemma mem_bot {x : R} : x ∈ (⊥ : subring R) ↔ ∃ (n : ℤ), ↑n = x :=
ring_hom.mem_range
/-! ## inf -/
/-- The inf of two subrings is their intersection. -/
instance : has_inf (subring R) :=
⟨λ s t,
{ carrier := s ∩ t,
.. s.to_submonoid ⊓ t.to_submonoid,
.. s.to_add_subgroup ⊓ t.to_add_subgroup }⟩
@[simp] lemma coe_inf (p p' : subring R) : ((p ⊓ p' : subring R) : set R) = p ∩ p' := rfl
@[simp] lemma mem_inf {p p' : subring R} {x : R} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
instance : has_Inf (subring R) :=
⟨λ s, subring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, subring.to_submonoid t )
(⨅ t ∈ s, subring.to_add_subgroup t) (by simp) (by simp)⟩
@[simp, norm_cast] lemma coe_Inf (S : set (subring R)) :
((Inf S : subring R) : set R) = ⋂ s ∈ S, ↑s := rfl
lemma mem_Inf {S : set (subring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_Inter₂
@[simp, norm_cast] lemma coe_infi {ι : Sort*} {S : ι → subring R} :
(↑(⨅ i, S i) : set R) = ⋂ i, S i :=
by simp only [infi, coe_Inf, set.bInter_range]
lemma mem_infi {ι : Sort*} {S : ι → subring R} {x : R} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i :=
by simp only [infi, mem_Inf, set.forall_range_iff]
@[simp] lemma Inf_to_submonoid (s : set (subring R)) :
(Inf s).to_submonoid = ⨅ t ∈ s, subring.to_submonoid t := mk'_to_submonoid _ _
@[simp] lemma Inf_to_add_subgroup (s : set (subring R)) :
(Inf s).to_add_subgroup = ⨅ t ∈ s, subring.to_add_subgroup t := mk'_to_add_subgroup _ _
/-- Subrings of a ring form a complete lattice. -/
instance : complete_lattice (subring R) :=
{ bot := (⊥),
bot_le := λ s x hx, let ⟨n, hn⟩ := mem_bot.1 hx in hn ▸ coe_int_mem s n,
top := (⊤),
le_top := λ s x hx, trivial,
inf := (⊓),
inf_le_left := λ s t x, and.left,
inf_le_right := λ s t x, and.right,
le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩,
.. complete_lattice_of_Inf (subring R)
(λ s, is_glb.of_image (λ s t,
show (s : set R) ≤ t ↔ s ≤ t, from set_like.coe_subset_coe) is_glb_binfi)}
lemma eq_top_iff' (A : subring R) : A = ⊤ ↔ ∀ x : R, x ∈ A :=
eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩
/-! ## Center of a ring -/
section
variables (R)
/-- The center of a ring `R` is the set of elements that commute with everything in `R` -/
def center : subring R :=
{ carrier := set.center R,
neg_mem' := λ a, set.neg_mem_center,
.. subsemiring.center R }
lemma coe_center : ↑(center R) = set.center R := rfl
@[simp] lemma center_to_subsemiring : (center R).to_subsemiring = subsemiring.center R := rfl
variables {R}
lemma mem_center_iff {z : R} : z ∈ center R ↔ ∀ g, g * z = z * g :=
iff.rfl
instance decidable_mem_center [decidable_eq R] [fintype R] : decidable_pred (∈ center R) :=
λ _, decidable_of_iff' _ mem_center_iff
@[simp] lemma center_eq_top (R) [comm_ring R] : center R = ⊤ :=
set_like.coe_injective (set.center_eq_univ R)
/-- The center is commutative. -/
instance : comm_ring (center R) :=
{ ..subsemiring.center.comm_semiring,
..(center R).to_ring}
end
section division_ring
variables {K : Type u} [division_ring K]
instance : field (center K) :=
{ inv := λ a, ⟨a⁻¹, set.inv_mem_center₀ a.prop⟩,
mul_inv_cancel := λ ⟨a, ha⟩ h, subtype.ext $ mul_inv_cancel $ subtype.coe_injective.ne h,
div := λ a b, ⟨a / b, set.div_mem_center₀ a.prop b.prop⟩,
div_eq_mul_inv := λ a b, subtype.ext $ div_eq_mul_inv _ _,
inv_zero := subtype.ext inv_zero,
..(center K).nontrivial,
..center.comm_ring }
@[simp]
lemma center.coe_inv (a : center K) : ((a⁻¹ : center K) : K) = (a : K)⁻¹ := rfl
@[simp]
lemma center.coe_div (a b : center K) : ((a / b : center K) : K) = (a : K) / (b : K) := rfl
end division_ring
/-! ## subring closure of a subset -/
/-- The `subring` generated by a set. -/
def closure (s : set R) : subring R := Inf {S | s ⊆ S}
lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : subring R, s ⊆ S → x ∈ S :=
mem_Inf
/-- The subring generated by a set includes the set. -/
@[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx
lemma not_mem_of_not_mem_closure {s : set R} {P : R} (hP : P ∉ closure s) : P ∉ s :=
λ h, hP (subset_closure h)
/-- A subring `t` includes `closure s` if and only if it includes `s`. -/
@[simp]
lemma closure_le {s : set R} {t : subring R} : closure s ≤ t ↔ s ⊆ t :=
⟨set.subset.trans subset_closure, λ h, Inf_le h⟩
/-- Subring closure of a set is monotone in its argument: if `s ⊆ t`,
then `closure s ≤ closure t`. -/
lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t :=
closure_le.2 $ set.subset.trans h subset_closure
lemma closure_eq_of_le {s : set R} {t : subring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) :
closure s = t :=
le_antisymm (closure_le.2 h₁) h₂
/-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements
of `s`, and is preserved under addition, negation, and multiplication, then `p` holds for all
elements of the closure of `s`. -/
@[elab_as_eliminator]
lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s)
(Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : p 1)
(Hadd : ∀ x y, p x → p y → p (x + y))
(Hneg : ∀ (x : R), p x → p (-x))
(Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
(@closure_le _ _ _ ⟨p, Hmul, H1, Hadd, H0, Hneg⟩).2 Hs h
/-- An induction principle for closure membership, for predicates with two arguments. -/
@[elab_as_eliminator]
lemma closure_induction₂ {s : set R} {p : R → R → Prop} {a b : R}
(ha : a ∈ closure s) (hb : b ∈ closure s)
(Hs : ∀ (x ∈ s) (y ∈ s), p x y)
(H0_left : ∀ x, p 0 x)
(H0_right : ∀ x, p x 0)
(H1_left : ∀ x, p 1 x)
(H1_right : ∀ x, p x 1)
(Hneg_left : ∀ x y, p x y → p (-x) y)
(Hneg_right : ∀ x y, p x y → p x (-y))
(Hadd_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ + x₂) y)
(Hadd_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ + y₂))
(Hmul_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ * x₂) y)
(Hmul_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ * y₂)) : p a b :=
begin
refine closure_induction hb _ (H0_right _) (H1_right _)
(Hadd_right a) (Hneg_right a) (Hmul_right a),
refine closure_induction ha Hs (λ x _, H0_left x) (λ x _, H1_left x) _ _ _,
{ exact (λ x y H₁ H₂ z zs, Hadd_left x y z (H₁ z zs) (H₂ z zs)) },
{ exact (λ x hx z zs, Hneg_left x z (hx z zs)) },
{ exact (λ x y H₁ H₂ z zs, Hmul_left x y z (H₁ z zs) (H₂ z zs)) }
end
lemma mem_closure_iff {s : set R} {x} :
x ∈ closure s ↔ x ∈ add_subgroup.closure (submonoid.closure s : set R) :=
⟨λ h, closure_induction h (λ x hx, add_subgroup.subset_closure $ submonoid.subset_closure hx)
(add_subgroup.zero_mem _)
(add_subgroup.subset_closure ( submonoid.one_mem (submonoid.closure s)) )
(λ x y hx hy, add_subgroup.add_mem _ hx hy )
(λ x hx, add_subgroup.neg_mem _ hx )
(λ x y hx hy, add_subgroup.closure_induction hy
(λ q hq, add_subgroup.closure_induction hx
(λ p hp, add_subgroup.subset_closure ((submonoid.closure s).mul_mem hp hq))
(begin rw zero_mul q, apply add_subgroup.zero_mem _, end)
(λ p₁ p₂ ihp₁ ihp₂, begin rw add_mul p₁ p₂ q, apply add_subgroup.add_mem _ ihp₁ ihp₂, end)
(λ x hx, begin have f : -x * q = -(x*q) :=
by simp, rw f, apply add_subgroup.neg_mem _ hx, end))
(begin rw mul_zero x, apply add_subgroup.zero_mem _, end)
(λ q₁ q₂ ihq₁ ihq₂, begin rw mul_add x q₁ q₂, apply add_subgroup.add_mem _ ihq₁ ihq₂ end)
(λ z hz, begin have f : x * -z = -(x*z) := by simp,
rw f, apply add_subgroup.neg_mem _ hz, end)),
λ h, add_subgroup.closure_induction h
(λ x hx, submonoid.closure_induction hx
(λ x hx, subset_closure hx)
(one_mem _)
(λ x y hx hy, mul_mem hx hy))
(zero_mem _)
(λ x y hx hy, add_mem hx hy)
(λ x hx, neg_mem hx)⟩
/-- If all elements of `s : set A` commute pairwise, then `closure s` is a commutative ring. -/
def closure_comm_ring_of_comm {s : set R} (hcomm : ∀ (a ∈ s) (b ∈ s), a * b = b * a) :
comm_ring (closure s) :=
{ mul_comm := λ x y,
begin
ext,
simp only [subring.coe_mul],
refine closure_induction₂ x.prop y.prop
hcomm
(λ x, by simp only [mul_zero, zero_mul])
(λ x, by simp only [mul_zero, zero_mul])
(λ x, by simp only [mul_one, one_mul])
(λ x, by simp only [mul_one, one_mul])
(λ x y hxy, by simp only [mul_neg, neg_mul, hxy])
(λ x y hxy, by simp only [mul_neg, neg_mul, hxy])
(λ x₁ x₂ y h₁ h₂, by simp only [add_mul, mul_add, h₁, h₂])
(λ x₁ x₂ y h₁ h₂, by simp only [add_mul, mul_add, h₁, h₂])
(λ x₁ x₂ y h₁ h₂, by rw [←mul_assoc, ←h₁, mul_assoc x₁ y x₂, ←h₂, mul_assoc])
(λ x₁ x₂ y h₁ h₂, by rw [←mul_assoc, h₁, mul_assoc, h₂, ←mul_assoc])
end,
..(closure s).to_ring }
theorem exists_list_of_mem_closure {s : set R} {x : R} (h : x ∈ closure s) :
(∃ L : list (list R), (∀ t ∈ L, ∀ y ∈ t, y ∈ s ∨ y = (-1:R)) ∧ (L.map list.prod).sum = x) :=
add_subgroup.closure_induction (mem_closure_iff.1 h)
(λ x hx, let ⟨l, hl, h⟩ :=submonoid.exists_list_of_mem_closure hx in ⟨[l], by simp [h];
clear_aux_decl; tauto!⟩)
⟨[], by simp⟩
(λ x y ⟨l, hl1, hl2⟩ ⟨m, hm1, hm2⟩, ⟨l ++ m, λ t ht, (list.mem_append.1 ht).elim (hl1 t) (hm1 t),
by simp [hl2, hm2]⟩)
(λ x ⟨L, hL⟩, ⟨L.map (list.cons (-1)), list.forall_mem_map_iff.2 $ λ j hj, list.forall_mem_cons.2
⟨or.inr rfl, hL.1 j hj⟩, hL.2 ▸ list.rec_on L (by simp)
(by simp [list.map_cons, add_comm] {contextual := tt})⟩)
variable (R)
/-- `closure` forms a Galois insertion with the coercion to set. -/
protected def gi : galois_insertion (@closure R _) coe :=
{ choice := λ s _, closure s,
gc := λ s t, closure_le,
le_l_u := λ s, subset_closure,
choice_eq := λ s h, rfl }
variable {R}
/-- Closure of a subring `S` equals `S`. -/
lemma closure_eq (s : subring R) : closure (s : set R) = s := (subring.gi R).l_u_eq s
@[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (subring.gi R).gc.l_bot
@[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤
lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t :=
(subring.gi R).gc.l_sup
lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) :=
(subring.gi R).gc.l_supr
lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t :=
(subring.gi R).gc.l_Sup
lemma map_sup (s t : subring R) (f : R →+* S) : (s ⊔ t).map f = s.map f ⊔ t.map f :=
(gc_map_comap f).l_sup
lemma map_supr {ι : Sort*} (f : R →+* S) (s : ι → subring R) :
(supr s).map f = ⨆ i, (s i).map f :=
(gc_map_comap f).l_supr
lemma comap_inf (s t : subring S) (f : R →+* S) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f :=
(gc_map_comap f).u_inf
lemma comap_infi {ι : Sort*} (f : R →+* S) (s : ι → subring S) :
(infi s).comap f = ⨅ i, (s i).comap f :=
(gc_map_comap f).u_infi
@[simp] lemma map_bot (f : R →+* S) : (⊥ : subring R).map f = ⊥ :=
(gc_map_comap f).l_bot
@[simp] lemma comap_top (f : R →+* S) : (⊤ : subring S).comap f = ⊤ :=
(gc_map_comap f).u_top
/-- Given `subring`s `s`, `t` of rings `R`, `S` respectively, `s.prod t` is `s ×̂ t`
as a subring of `R × S`. -/
def prod (s : subring R) (t : subring S) : subring (R × S) :=
{ carrier := s ×ˢ t,
.. s.to_submonoid.prod t.to_submonoid, .. s.to_add_subgroup.prod t.to_add_subgroup}
@[norm_cast]
lemma coe_prod (s : subring R) (t : subring S) : (s.prod t : set (R × S)) = s ×ˢ t := rfl
lemma mem_prod {s : subring R} {t : subring S} {p : R × S} :
p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl
@[mono] lemma prod_mono ⦃s₁ s₂ : subring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : subring S⦄
(ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ :=
set.prod_mono hs ht
lemma prod_mono_right (s : subring R) : monotone (λ t : subring S, s.prod t) :=
prod_mono (le_refl s)
lemma prod_mono_left (t : subring S) : monotone (λ s : subring R, s.prod t) :=
λ s₁ s₂ hs, prod_mono hs (le_refl t)
lemma prod_top (s : subring R) :
s.prod (⊤ : subring S) = s.comap (ring_hom.fst R S) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst]
lemma top_prod (s : subring S) :
(⊤ : subring R).prod s = s.comap (ring_hom.snd R S) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd]
@[simp]
lemma top_prod_top : (⊤ : subring R).prod (⊤ : subring S) = ⊤ :=
(top_prod _).trans $ comap_top _
/-- Product of subrings is isomorphic to their product as rings. -/
def prod_equiv (s : subring R) (t : subring S) : s.prod t ≃+* s × t :=
{ map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t }
/-- The underlying set of a non-empty directed Sup of subrings is just a union of the subrings.
Note that this fails without the directedness assumption (the union of two subrings is
typically not a subring) -/
lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S)
{x : R} :
x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i :=
begin
refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩,
let U : subring R := subring.mk' (⋃ i, (S i : set R))
(⨆ i, (S i).to_submonoid) (⨆ i, (S i).to_add_subgroup)
(submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id))
(add_subgroup.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)),
suffices : (⨆ i, S i) ≤ U, by simpa using @this x,
exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩),
end
lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S) :
((⨆ i, S i : subring R) : set R) = ⋃ i, ↑(S i) :=
set.ext $ λ x, by simp [mem_supr_of_directed hS]
lemma mem_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty)
(hS : directed_on (≤) S) {x : R} :
x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s :=
begin
haveI : nonempty S := Sne.to_subtype,
simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk]
end
lemma coe_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) :
(↑(Sup S) : set R) = ⋃ s ∈ S, ↑s :=
set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS]
lemma mem_map_equiv {f : R ≃+* S} {K : subring R} {x : S} :
x ∈ K.map (f : R →+* S) ↔ f.symm x ∈ K :=
@set.mem_image_equiv _ _ ↑K f.to_equiv x
lemma map_equiv_eq_comap_symm (f : R ≃+* S) (K : subring R) :
K.map (f : R →+* S) = K.comap f.symm :=
set_like.coe_injective (f.to_equiv.image_eq_preimage K)
lemma comap_equiv_eq_map_symm (f : R ≃+* S) (K : subring S) :
K.comap (f : R →+* S) = K.map f.symm :=
(map_equiv_eq_comap_symm f.symm K).symm
end subring
namespace ring_hom
variables {s : subring R}
open subring
/-- Restriction of a ring homomorphism to its range interpreted as a subsemiring.
This is the bundled version of `set.range_factorization`. -/
def range_restrict (f : R →+* S) : R →+* f.range :=
f.cod_restrict f.range $ λ x, ⟨x, rfl⟩
@[simp] lemma coe_range_restrict (f : R →+* S) (x : R) : (f.range_restrict x : S) = f x := rfl
lemma range_restrict_surjective (f : R →+* S) : function.surjective f.range_restrict :=
λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_range.mp hy in ⟨x, subtype.ext hx⟩
lemma range_top_iff_surjective {f : R →+* S} :
f.range = (⊤ : subring S) ↔ function.surjective f :=
set_like.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective
/-- The range of a surjective ring homomorphism is the whole of the codomain. -/
lemma range_top_of_surjective (f : R →+* S) (hf : function.surjective f) :
f.range = (⊤ : subring S) :=
range_top_iff_surjective.2 hf
/-- The subring of elements `x : R` such that `f x = g x`, i.e.,
the equalizer of f and g as a subring of R -/
def eq_locus (f g : R →+* S) : subring R :=
{ carrier := {x | f x = g x}, .. (f : R →* S).eq_mlocus g, .. (f : R →+ S).eq_locus g }
@[simp] lemma eq_locus_same (f : R →+* S) : f.eq_locus f = ⊤ :=
set_like.ext $ λ _, eq_self_iff_true _
/-- If two ring homomorphisms are equal on a set, then they are equal on its subring closure. -/
lemma eq_on_set_closure {f g : R →+* S} {s : set R} (h : set.eq_on f g s) :
set.eq_on f g (closure s) :=
show closure s ≤ f.eq_locus g, from closure_le.2 h
lemma eq_of_eq_on_set_top {f g : R →+* S} (h : set.eq_on f g (⊤ : subring R)) :
f = g :=
ext $ λ x, h trivial
lemma eq_of_eq_on_set_dense {s : set R} (hs : closure s = ⊤) {f g : R →+* S} (h : s.eq_on f g) :
f = g :=
eq_of_eq_on_set_top $ hs ▸ eq_on_set_closure h
lemma closure_preimage_le (f : R →+* S) (s : set S) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx
/-- The image under a ring homomorphism of the subring generated by a set equals
the subring generated by the image of the set. -/
lemma map_closure (f : R →+* S) (s : set R) :
(closure s).map f = closure (f '' s) :=
le_antisymm
(map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _)
(closure_preimage_le _ _))
(closure_le.2 $ set.image_subset _ subset_closure)
end ring_hom
namespace subring
open ring_hom
/-- The ring homomorphism associated to an inclusion of subrings. -/
def inclusion {S T : subring R} (h : S ≤ T) : S →+* T :=
S.subtype.cod_restrict _ (λ x, h x.2)
@[simp] lemma range_subtype (s : subring R) : s.subtype.range = s :=
set_like.coe_injective $ (coe_srange _).trans subtype.range_coe
@[simp]
lemma range_fst : (fst R S).srange = ⊤ :=
(fst R S).srange_top_of_surjective $ prod.fst_surjective
@[simp]
lemma range_snd : (snd R S).srange = ⊤ :=
(snd R S).srange_top_of_surjective $ prod.snd_surjective
@[simp]
lemma prod_bot_sup_bot_prod (s : subring R) (t : subring S) :
(s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t :=
le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $
assume p hp, prod.fst_mul_snd p ▸ mul_mem
((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set_like.mem_coe.2 $ one_mem ⊥⟩)
((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set_like.mem_coe.2 $ one_mem ⊥, hp.2⟩)
end subring
namespace ring_equiv
variables {s t : subring R}
/-- Makes the identity isomorphism from a proof two subrings of a multiplicative
monoid are equal. -/
def subring_congr (h : s = t) : s ≃+* t :=
{ map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h }
/-- Restrict a ring homomorphism with a left inverse to a ring isomorphism to its
`ring_hom.range`. -/
def of_left_inverse {g : S → R} {f : R →+* S} (h : function.left_inverse g f) :
R ≃+* f.range :=
{ to_fun := λ x, f.range_restrict x,
inv_fun := λ x, (g ∘ f.range.subtype) x,
left_inv := h,
right_inv := λ x, subtype.ext $
let ⟨x', hx'⟩ := ring_hom.mem_range.mp x.prop in
show f (g x) = x, by rw [←hx', h x'],
..f.range_restrict }
@[simp] lemma of_left_inverse_apply
{g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : R) :
↑(of_left_inverse h x) = f x := rfl
@[simp] lemma of_left_inverse_symm_apply
{g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : f.range) :
(of_left_inverse h).symm x = g x := rfl
/-- Given an equivalence `e : R ≃+* S` of rings and a subring `s` of `R`,
`subring_equiv_map e s` is the induced equivalence between `s` and `s.map e` -/
@[simps] def subring_map (e : R ≃+* S) :
s ≃+* s.map e.to_ring_hom :=
e.subsemiring_map s.to_subsemiring
end ring_equiv
namespace subring
variables {s : set R}
local attribute [reducible] closure
@[elab_as_eliminator]
protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s)
(h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n))
(ha : ∀ {x y}, C x → C y → C (x + y)) : C x :=
begin
have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1,
rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx,
induction L with hd tl ih, { exact h0 },
rw list.forall_mem_cons at HL,
suffices : C (list.prod hd),
{ rw [list.map_cons, list.sum_cons],
exact ha this (ih HL.2) },
replace HL := HL.1, clear ih tl,
rsuffices ⟨L, HL', HP | HP⟩ : ∃ L : list R, (∀ x ∈ L, x ∈ s) ∧
(list.prod hd = list.prod L ∨ list.prod hd = -list.prod L),
{ rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 },
rw list.forall_mem_cons at HL',
rw list.prod_cons,
exact hs _ HL'.1 _ (ih HL'.2) },
{ rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 },
rw [list.prod_cons, neg_mul_eq_mul_neg],
rw list.forall_mem_cons at HL',
exact hs _ HL'.1 _ (ih HL'.2) },
induction hd with hd tl ih,
{ exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ },
rw list.forall_mem_cons at HL,
rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd,
{ exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $
by rw [list.prod_cons, list.prod_cons, HP]⟩ },
{ exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ },
{ exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $
by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ },
{ exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ }
end
lemma closure_preimage_le (f : R →+* S) (s : set S) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx
end subring
lemma add_subgroup.int_mul_mem {G : add_subgroup R} (k : ℤ) {g : R} (h : g ∈ G) :
(k : R) * g ∈ G :=
by { convert add_subgroup.zsmul_mem G h k, simp }
/-! ## Actions by `subring`s
These are just copies of the definitions about `subsemiring` starting from
`subsemiring.mul_action`.
When `R` is commutative, `algebra.of_subring` provides a stronger result than those found in
this file, which uses the same scalar action.
-/
section actions
namespace subring
variables {α β : Type*}
/-- The action by a subring is the action by the underlying ring. -/
instance [has_smul R α] (S : subring R) : has_smul S α := S.to_subsemiring.has_smul
lemma smul_def [has_smul R α] {S : subring R} (g : S) (m : α) : g • m = (g : R) • m := rfl
instance smul_comm_class_left
[has_smul R β] [has_smul α β] [smul_comm_class R α β] (S : subring R) :
smul_comm_class S α β :=
S.to_subsemiring.smul_comm_class_left
instance smul_comm_class_right
[has_smul α β] [has_smul R β] [smul_comm_class α R β] (S : subring R) :
smul_comm_class α S β :=
S.to_subsemiring.smul_comm_class_right
/-- Note that this provides `is_scalar_tower S R R` which is needed by `smul_mul_assoc`. -/
instance
[has_smul α β] [has_smul R α] [has_smul R β] [is_scalar_tower R α β] (S : subring R) :
is_scalar_tower S α β :=
S.to_subsemiring.is_scalar_tower
instance [has_smul R α] [has_faithful_smul R α] (S : subring R) :
has_faithful_smul S α :=
S.to_subsemiring.has_faithful_smul
/-- The action by a subring is the action by the underlying ring. -/
instance [mul_action R α] (S : subring R) : mul_action S α :=
S.to_subsemiring.mul_action
/-- The action by a subring is the action by the underlying ring. -/
instance [add_monoid α] [distrib_mul_action R α] (S : subring R) : distrib_mul_action S α :=
S.to_subsemiring.distrib_mul_action
/-- The action by a subring is the action by the underlying ring. -/
instance [monoid α] [mul_distrib_mul_action R α] (S : subring R) : mul_distrib_mul_action S α :=
S.to_subsemiring.mul_distrib_mul_action
/-- The action by a subring is the action by the underlying ring. -/
instance [has_zero α] [smul_with_zero R α] (S : subring R) : smul_with_zero S α :=
S.to_subsemiring.smul_with_zero
/-- The action by a subring is the action by the underlying ring. -/
instance [has_zero α] [mul_action_with_zero R α] (S : subring R) : mul_action_with_zero S α :=
S.to_subsemiring.mul_action_with_zero
/-- The action by a subring is the action by the underlying ring. -/
instance [add_comm_monoid α] [module R α] (S : subring R) : module S α :=
S.to_subsemiring.module
/-- The action by a subsemiring is the action by the underlying ring. -/
instance [semiring α] [mul_semiring_action R α] (S : subring R) : mul_semiring_action S α :=
S.to_submonoid.mul_semiring_action
/-- The center of a semiring acts commutatively on that semiring. -/
instance center.smul_comm_class_left : smul_comm_class (center R) R R :=
subsemiring.center.smul_comm_class_left
/-- The center of a semiring acts commutatively on that semiring. -/
instance center.smul_comm_class_right : smul_comm_class R (center R) R :=
subsemiring.center.smul_comm_class_right
end subring
end actions
-- while this definition is not about subrings, this is the earliest we have
-- both ordered ring structures and submonoids available
/-- The subgroup of positive units of a linear ordered semiring. -/
def units.pos_subgroup (R : Type*) [linear_ordered_semiring R] :
subgroup Rˣ :=
{ carrier := {x | (0 : R) < x},
inv_mem' := λ x, units.inv_pos.mpr,
..(pos_submonoid R).comap (units.coe_hom R)}
@[simp] lemma units.mem_pos_subgroup {R : Type*} [linear_ordered_semiring R]
(u : Rˣ) : u ∈ units.pos_subgroup R ↔ (0 : R) < u := iff.rfl
|
c5db70d68a73f639e22a01074fd4c9916a226928 | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/t1.lean | eb88fc206149e04d7680154849a94254d90df940 | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 185 | lean |
(*
print("testing...")
local env = get_env()
env = add_decl(env, mk_var_decl("x", Prop))
assert(env:find("x"))
set_env(env)
*)
(*
local env = get_env()
print(env:find("x"):type())
*)
|
2c13774ad7fd0dd20776099693c53ed24e246ff9 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebra/hom/non_unital_alg.lean | 8d9221d46a2d8708ae5bc9244608ab615a88db48 | [
"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 | 11,472 | 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.algebra.basic
/-!
# Morphisms of non-unital algebras
This file defines morphisms between two types, each of which carries:
* an addition,
* an additive zero,
* a multiplication,
* a scalar action.
The multiplications are not assumed to be associative or unital, or even to be compatible with the
scalar actions. In a typical application, the operations will satisfy compatibility conditions
making them into algebras (albeit possibly non-associative and/or non-unital) but such conditions
are not required to make this definition.
This notion of morphism should be useful for any category of non-unital algebras. The motivating
application at the time it was introduced was to be able to state the adjunction property for
magma algebras. These are non-unital, non-associative algebras obtained by applying the
group-algebra construction except where we take a type carrying just `has_mul` instead of `group`.
For a plausible future application, one could take the non-unital algebra of compactly-supported
functions on a non-compact topological space. A proper map between a pair of such spaces
(contravariantly) induces a morphism between their algebras of compactly-supported functions which
will be a `non_unital_alg_hom`.
TODO: add `non_unital_alg_equiv` when needed.
## Main definitions
* `non_unital_alg_hom`
* `alg_hom.to_non_unital_alg_hom`
## Tags
non-unital, algebra, morphism
-/
universes u v w w₁ w₂ w₃
variables (R : Type u) (A : Type v) (B : Type w) (C : Type w₁)
set_option old_structure_cmd true
/-- A morphism respecting addition, multiplication, and scalar multiplication. When these arise from
algebra structures, this is the same as a not-necessarily-unital morphism of algebras. -/
structure non_unital_alg_hom [monoid R]
[non_unital_non_assoc_semiring A] [distrib_mul_action R A]
[non_unital_non_assoc_semiring B] [distrib_mul_action R B]
extends A →+[R] B, A →ₙ* B
infixr ` →ₙₐ `:25 := non_unital_alg_hom _
notation A ` →ₙₐ[`:25 R `] ` B := non_unital_alg_hom R A B
attribute [nolint doc_blame] non_unital_alg_hom.to_distrib_mul_action_hom
attribute [nolint doc_blame] non_unital_alg_hom.to_mul_hom
/-- `non_unital_alg_hom_class F R A B` asserts `F` is a type of bundled algebra homomorphisms
from `A` to `B`. -/
class non_unital_alg_hom_class (F : Type*) (R : out_param Type*) (A : out_param Type*)
(B : out_param Type*) [monoid R]
[non_unital_non_assoc_semiring A] [non_unital_non_assoc_semiring B]
[distrib_mul_action R A] [distrib_mul_action R B]
extends distrib_mul_action_hom_class F R A B, mul_hom_class F A B
-- `R` becomes a metavariable but that's fine because it's an `out_param`
attribute [nolint dangerous_instance] non_unital_alg_hom_class.to_mul_hom_class
namespace non_unital_alg_hom_class
variables [semiring R]
[non_unital_non_assoc_semiring A] [module R A]
[non_unital_non_assoc_semiring B] [module R B]
@[priority 100] -- see Note [lower instance priority]
instance {F : Type*} [non_unital_alg_hom_class F R A B] : linear_map_class F R A B :=
{ map_smulₛₗ := distrib_mul_action_hom_class.map_smul,
..‹non_unital_alg_hom_class F R A B› }
end non_unital_alg_hom_class
namespace non_unital_alg_hom
variables {R A B C} [monoid R]
variables [non_unital_non_assoc_semiring A] [distrib_mul_action R A]
variables [non_unital_non_assoc_semiring B] [distrib_mul_action R B]
variables [non_unital_non_assoc_semiring C] [distrib_mul_action R C]
/-- see Note [function coercion] -/
instance : has_coe_to_fun (A →ₙₐ[R] B) (λ _, A → B) := ⟨to_fun⟩
@[simp] lemma to_fun_eq_coe (f : A →ₙₐ[R] B) : f.to_fun = ⇑f := rfl
initialize_simps_projections non_unital_alg_hom (to_fun → apply)
lemma coe_injective :
@function.injective (A →ₙₐ[R] B) (A → B) coe_fn :=
by rintro ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩; congr
instance : non_unital_alg_hom_class (A →ₙₐ[R] B) R A B :=
{ coe := to_fun,
coe_injective' := coe_injective,
map_smul := λ f, f.map_smul',
map_add := λ f, f.map_add',
map_zero := λ f, f.map_zero',
map_mul := λ f, f.map_mul' }
@[ext] lemma ext {f g : A →ₙₐ[R] B} (h : ∀ x, f x = g x) : f = g :=
coe_injective $ funext h
lemma ext_iff {f g : A →ₙₐ[R] B} : f = g ↔ ∀ x, f x = g x :=
⟨by { rintro rfl x, refl }, ext⟩
lemma congr_fun {f g : A →ₙₐ[R] B} (h : f = g) (x : A) : f x = g x := h ▸ rfl
@[simp] lemma coe_mk (f : A → B) (h₁ h₂ h₃ h₄) :
((⟨f, h₁, h₂, h₃, h₄⟩ : A →ₙₐ[R] B) : A → B) = f :=
rfl
@[simp] lemma mk_coe (f : A →ₙₐ[R] B) (h₁ h₂ h₃ h₄) :
(⟨f, h₁, h₂, h₃, h₄⟩ : A →ₙₐ[R] B) = f :=
by { ext, refl, }
instance : has_coe (A →ₙₐ[R] B) (A →+[R] B) :=
⟨to_distrib_mul_action_hom⟩
instance : has_coe (A →ₙₐ[R] B) (A →ₙ* B) := ⟨to_mul_hom⟩
@[simp] lemma to_distrib_mul_action_hom_eq_coe (f : A →ₙₐ[R] B) :
f.to_distrib_mul_action_hom = ↑f :=
rfl
@[simp] lemma to_mul_hom_eq_coe (f : A →ₙₐ[R] B) : f.to_mul_hom = ↑f :=
rfl
@[simp, norm_cast] lemma coe_to_distrib_mul_action_hom (f : A →ₙₐ[R] B) :
((f : A →+[R] B) : A → B) = f :=
rfl
@[simp, norm_cast] lemma coe_to_mul_hom (f : A →ₙₐ[R] B) :
((f : A →ₙ* B) : A → B) = f :=
rfl
lemma to_distrib_mul_action_hom_injective {f g : A →ₙₐ[R] B}
(h : (f : A →+[R] B) = (g : A →+[R] B)) : f = g :=
by { ext a, exact distrib_mul_action_hom.congr_fun h a, }
lemma to_mul_hom_injective {f g : A →ₙₐ[R] B}
(h : (f : A →ₙ* B) = (g : A →ₙ* B)) : f = g :=
by { ext a, exact mul_hom.congr_fun h a, }
@[norm_cast] lemma coe_distrib_mul_action_hom_mk (f : A →ₙₐ[R] B) (h₁ h₂ h₃ h₄) :
((⟨f, h₁, h₂, h₃, h₄⟩ : A →ₙₐ[R] B) : A →+[R] B) =
⟨f, h₁, h₂, h₃⟩ :=
by { ext, refl, }
@[norm_cast] lemma coe_mul_hom_mk (f : A →ₙₐ[R] B) (h₁ h₂ h₃ h₄) :
((⟨f, h₁, h₂, h₃, h₄⟩ : A →ₙₐ[R] B) : A →ₙ* B) = ⟨f, h₄⟩ :=
by { ext, refl, }
@[simp] protected lemma map_smul (f : A →ₙₐ[R] B) (c : R) (x : A) :
f (c • x) = c • f x := map_smul _ _ _
@[simp] protected lemma map_add (f : A →ₙₐ[R] B) (x y : A) :
f (x + y) = (f x) + (f y) := map_add _ _ _
@[simp] protected lemma map_mul (f : A →ₙₐ[R] B) (x y : A) :
f (x * y) = (f x) * (f y) := map_mul _ _ _
@[simp] protected lemma map_zero (f : A →ₙₐ[R] B) : f 0 = 0 := map_zero _
instance : has_zero (A →ₙₐ[R] B) :=
⟨{ map_mul' := by simp,
.. (0 : A →+[R] B) }⟩
instance : has_one (A →ₙₐ[R] A) :=
⟨{ map_mul' := by simp,
.. (1 : A →+[R] A) }⟩
@[simp] lemma coe_zero : ((0 : A →ₙₐ[R] B) : A → B) = 0 := rfl
@[simp] lemma coe_one : ((1 : A →ₙₐ[R] A) : A → A) = id := rfl
lemma zero_apply (a : A) : (0 : A →ₙₐ[R] B) a = 0 := rfl
lemma one_apply (a : A) : (1 : A →ₙₐ[R] A) a = a := rfl
instance : inhabited (A →ₙₐ[R] B) := ⟨0⟩
/-- The composition of morphisms is a morphism. -/
def comp (f : B →ₙₐ[R] C) (g : A →ₙₐ[R] B) : A →ₙₐ[R] C :=
{ .. (f : B →ₙ* C).comp (g : A →ₙ* B),
.. (f : B →+[R] C).comp (g : A →+[R] B) }
@[simp, norm_cast] lemma coe_comp (f : B →ₙₐ[R] C) (g : A →ₙₐ[R] B) :
(f.comp g : A → C) = (f : B → C) ∘ (g : A → B) :=
rfl
lemma comp_apply (f : B →ₙₐ[R] C) (g : A →ₙₐ[R] B) (x : A) :
f.comp g x = f (g x) :=
rfl
/-- The inverse of a bijective morphism is a morphism. -/
def inverse (f : A →ₙₐ[R] B) (g : B → A)
(h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) :
B →ₙₐ[R] A :=
{ .. (f : A →ₙ* B).inverse g h₁ h₂,
.. (f : A →+[R] B).inverse g h₁ h₂ }
@[simp] lemma coe_inverse (f : A →ₙₐ[R] B) (g : B → A)
(h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) :
(inverse f g h₁ h₂ : B → A) = g :=
rfl
/-! ### Operations on the product type
Note that much of this is copied from [`linear_algebra/prod`](../../linear_algebra/prod). -/
section prod
variables (R A B)
/-- The first projection of a product is a non-unital alg_hom. -/
@[simps]
def fst : A × B →ₙₐ[R] A :=
{ to_fun := prod.fst,
map_zero' := rfl, map_add' := λ x y, rfl, map_smul' := λ x y, rfl, map_mul' := λ x y, rfl }
/-- The second projection of a product is a non-unital alg_hom. -/
@[simps]
def snd : A × B →ₙₐ[R] B :=
{ to_fun := prod.snd,
map_zero' := rfl, map_add' := λ x y, rfl, map_smul' := λ x y, rfl, map_mul' := λ x y, rfl }
variables {R A B}
/-- The prod of two morphisms is a morphism. -/
@[simps] def prod (f : A →ₙₐ[R] B) (g : A →ₙₐ[R] C) : (A →ₙₐ[R] B × C) :=
{ to_fun := pi.prod f g,
map_zero' := by simp only [pi.prod, prod.zero_eq_mk, map_zero],
map_add' := λ x y, by simp only [pi.prod, prod.mk_add_mk, map_add],
map_mul' := λ x y, by simp only [pi.prod, prod.mk_mul_mk, map_mul],
map_smul' := λ c x, by simp only [pi.prod, prod.smul_mk, map_smul, ring_hom.id_apply] }
lemma coe_prod (f : A →ₙₐ[R] B) (g : A →ₙₐ[R] C) : ⇑(f.prod g) = pi.prod f g := rfl
@[simp] theorem fst_prod (f : A →ₙₐ[R] B) (g : A →ₙₐ[R] C) :
(fst R B C).comp (prod f g) = f := by ext; refl
@[simp] theorem snd_prod (f : A →ₙₐ[R] B) (g : A →ₙₐ[R] C) :
(snd R B C).comp (prod f g) = g := by ext; refl
@[simp] theorem prod_fst_snd : prod (fst R A B) (snd R A B) = 1 :=
coe_injective pi.prod_fst_snd
/-- Taking the product of two maps with the same domain is equivalent to taking the product of
their codomains. -/
@[simps] def prod_equiv : ((A →ₙₐ[R] B) × (A →ₙₐ[R] C)) ≃ (A →ₙₐ[R] B × C) :=
{ to_fun := λ f, f.1.prod f.2,
inv_fun := λ f, ((fst _ _ _).comp f, (snd _ _ _).comp f),
left_inv := λ f, by ext; refl,
right_inv := λ f, by ext; refl }
variables (R A B)
/-- The left injection into a product is a non-unital algebra homomorphism. -/
def inl : A →ₙₐ[R] A × B := prod 1 0
/-- The right injection into a product is a non-unital algebra homomorphism. -/
def inr : B →ₙₐ[R] A × B := prod 0 1
variables {R A B}
@[simp] theorem coe_inl : (inl R A B : A → A × B) = λ x, (x, 0) := rfl
theorem inl_apply (x : A) : inl R A B x = (x, 0) := rfl
@[simp] theorem coe_inr : (inr R A B : B → A × B) = prod.mk 0 := rfl
theorem inr_apply (x : B) : inr R A B x = (0, x) := rfl
end prod
end non_unital_alg_hom
/-! ### Interaction with `alg_hom` -/
namespace alg_hom
variables {R A B} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B]
@[priority 100] -- see Note [lower instance priority]
instance {F : Type*} [alg_hom_class F R A B] : non_unital_alg_hom_class F R A B :=
{ map_smul := map_smul,
..‹alg_hom_class F R A B› }
/-- A unital morphism of algebras is a `non_unital_alg_hom`. -/
def to_non_unital_alg_hom (f : A →ₐ[R] B) : A →ₙₐ[R] B :=
{ map_smul' := map_smul f, .. f, }
instance non_unital_alg_hom.has_coe : has_coe (A →ₐ[R] B) (A →ₙₐ[R] B) :=
⟨to_non_unital_alg_hom⟩
@[simp] lemma to_non_unital_alg_hom_eq_coe (f : A →ₐ[R] B) : f.to_non_unital_alg_hom = f :=
rfl
@[simp, norm_cast] lemma coe_to_non_unital_alg_hom (f : A →ₐ[R] B) :
((f : A →ₙₐ[R] B) : A → B) = f :=
rfl
end alg_hom
|
4ef9156af7613a5c33b6514e27886682e6a42e85 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Init/NotationExtra.lean | fb8a3498edad6023288caf485013c9ffabfce696 | [
"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 | 12,734 | 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
Extra notation that depends on Init/Meta
-/
prelude
import Init.Meta
import Init.Data.Array.Subarray
import Init.Data.ToString
namespace Lean
macro "Macro.trace[" id:ident "]" s:interpolatedStr(term) : term =>
`(Macro.trace $(quote id.getId.eraseMacroScopes) (s! $s))
-- Auxiliary parsers and functions for declaring notation with binders
syntax unbracketedExplicitBinders := binderIdent+ (" : " term)?
syntax bracketedExplicitBinders := "(" binderIdent+ " : " term ")"
syntax explicitBinders := bracketedExplicitBinders+ <|> unbracketedExplicitBinders
open TSyntax.Compat in
def expandExplicitBindersAux (combinator : Syntax) (idents : Array Syntax) (type? : Option Syntax) (body : Syntax) : MacroM Syntax :=
let rec loop (i : Nat) (acc : Syntax) := do
match i with
| 0 => pure acc
| i+1 =>
let ident := idents[i]![0]
let acc ← match ident.isIdent, type? with
| true, none => `($combinator fun $ident => $acc)
| true, some type => `($combinator fun $ident : $type => $acc)
| false, none => `($combinator fun _ => $acc)
| false, some type => `($combinator fun _ : $type => $acc)
loop i acc
loop idents.size body
def expandBrackedBindersAux (combinator : Syntax) (binders : Array Syntax) (body : Syntax) : MacroM Syntax :=
let rec loop (i : Nat) (acc : Syntax) := do
match i with
| 0 => pure acc
| i+1 =>
let idents := binders[i]![1].getArgs
let type := binders[i]![3]
loop i (← expandExplicitBindersAux combinator idents (some type) acc)
loop binders.size body
def expandExplicitBinders (combinatorDeclName : Name) (explicitBinders : Syntax) (body : Syntax) : MacroM Syntax := do
let combinator := mkIdentFrom (← getRef) combinatorDeclName
let explicitBinders := explicitBinders[0]
if explicitBinders.getKind == ``Lean.unbracketedExplicitBinders then
let idents := explicitBinders[0].getArgs
let type? := if explicitBinders[1].isNone then none else some explicitBinders[1][1]
expandExplicitBindersAux combinator idents type? body
else if explicitBinders.getArgs.all (·.getKind == ``Lean.bracketedExplicitBinders) then
expandBrackedBindersAux combinator explicitBinders.getArgs body
else
Macro.throwError "unexpected explicit binder"
def expandBrackedBinders (combinatorDeclName : Name) (bracketedExplicitBinders : Syntax) (body : Syntax) : MacroM Syntax := do
let combinator := mkIdentFrom (← getRef) combinatorDeclName
expandBrackedBindersAux combinator #[bracketedExplicitBinders] body
syntax unifConstraint := term (" =?= " <|> " ≟ ") term
syntax unifConstraintElem := colGe unifConstraint ", "?
syntax (docComment)? attrKind "unif_hint " (ident)? bracketedBinder* " where " withPosition(unifConstraintElem*) ("|-" <|> "⊢ ") unifConstraint : command
macro_rules
| `($[$doc?:docComment]? $kind:attrKind unif_hint $(n)? $bs* where $[$cs₁ ≟ $cs₂]* |- $t₁ ≟ $t₂) => do
let mut body ← `($t₁ = $t₂)
for (c₁, c₂) in cs₁.zip cs₂ |>.reverse do
body ← `($c₁ = $c₂ → $body)
let hint : Ident ← `(hint)
`($[$doc?:docComment]? @[$kind unificationHint] def $(n.getD hint) $bs* : Sort _ := $body)
end Lean
open Lean
macro "∃ " xs:explicitBinders ", " b:term : term => expandExplicitBinders ``Exists xs b
macro "exists" xs:explicitBinders ", " b:term : term => expandExplicitBinders ``Exists xs b
macro "Σ" xs:explicitBinders ", " b:term : term => expandExplicitBinders ``Sigma xs b
macro "Σ'" xs:explicitBinders ", " b:term : term => expandExplicitBinders ``PSigma xs b
macro:35 xs:bracketedExplicitBinders " × " b:term:35 : term => expandBrackedBinders ``Sigma xs b
macro:35 xs:bracketedExplicitBinders " ×' " b:term:35 : term => expandBrackedBinders ``PSigma xs b
-- enforce indentation of calc steps so we know when to stop parsing them
syntax calcStep := ppIndent(colGe term " := " withPosition(term))
/-- Step-wise reasoning over transitive relations.
```
calc
a = b := pab
b = c := pbc
...
y = z := pyz
```
proves `a = z` from the given step-wise proofs. `=` can be replaced with any
relation implementing the typeclass `Trans`. Instead of repeating the right-
hand sides, subsequent left-hand sides can be replaced with `_`.
`calc` has term mode and tactic mode variants. This is the term mode variant.
See [Theorem Proving in Lean 4][tpil4] for more information.
[tpil4]: https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#calculational-proofs
-/
syntax (name := calc) "calc" ppLine withPosition(calcStep) ppLine withPosition((calcStep ppLine)*) : term
/-- Step-wise reasoning over transitive relations.
```
calc
a = b := pab
b = c := pbc
...
y = z := pyz
```
proves `a = z` from the given step-wise proofs. `=` can be replaced with any
relation implementing the typeclass `Trans`. Instead of repeating the right-
hand sides, subsequent left-hand sides can be replaced with `_`.
`calc` has term mode and tactic mode variants. This is the tactic mode variant,
which supports an additional feature: it works even if the goal is `a = z'`
for some other `z'`; in this case it will not close the goal but will instead
leave a subgoal proving `z = z'`.
See [Theorem Proving in Lean 4][tpil4] for more information.
[tpil4]: https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#calculational-proofs
-/
syntax (name := calcTactic) "calc" ppLine withPosition(calcStep) ppLine withPosition((calcStep ppLine)*) : tactic
@[appUnexpander Unit.unit] def unexpandUnit : Lean.PrettyPrinter.Unexpander
| `($(_)) => `(())
@[appUnexpander List.nil] def unexpandListNil : Lean.PrettyPrinter.Unexpander
| `($(_)) => `([])
@[appUnexpander List.cons] def unexpandListCons : Lean.PrettyPrinter.Unexpander
| `($(_) $x []) => `([$x])
| `($(_) $x [$xs,*]) => `([$x, $xs,*])
| _ => throw ()
@[appUnexpander List.toArray] def unexpandListToArray : Lean.PrettyPrinter.Unexpander
| `($(_) [$xs,*]) => `(#[$xs,*])
| _ => throw ()
@[appUnexpander Prod.mk] def unexpandProdMk : Lean.PrettyPrinter.Unexpander
| `($(_) $x ($y, $ys,*)) => `(($x, $y, $ys,*))
| `($(_) $x $y) => `(($x, $y))
| _ => throw ()
@[appUnexpander ite] def unexpandIte : Lean.PrettyPrinter.Unexpander
| `($(_) $c $t $e) => `(if $c then $t else $e)
| _ => throw ()
@[appUnexpander sorryAx] def unexpandSorryAx : Lean.PrettyPrinter.Unexpander
| `($(_) _) => `(sorry)
| `($(_) _ _) => `(sorry)
| _ => throw ()
@[appUnexpander Eq.ndrec] def unexpandEqNDRec : Lean.PrettyPrinter.Unexpander
| `($(_) $m $h) => `($h ▸ $m)
| _ => throw ()
@[appUnexpander Eq.rec] def unexpandEqRec : Lean.PrettyPrinter.Unexpander
| `($(_) $m $h) => `($h ▸ $m)
| _ => throw ()
@[appUnexpander Exists] def unexpandExists : Lean.PrettyPrinter.Unexpander
| `($(_) fun $x:ident => ∃ $xs:binderIdent*, $b) => `(∃ $x:ident $xs:binderIdent*, $b)
| `($(_) fun $x:ident => $b) => `(∃ $x:ident, $b)
| `($(_) fun ($x:ident : $t) => $b) => `(∃ ($x:ident : $t), $b)
| _ => throw ()
@[appUnexpander Sigma] def unexpandSigma : Lean.PrettyPrinter.Unexpander
| `($(_) fun ($x:ident : $t) => $b) => `(($x:ident : $t) × $b)
| _ => throw ()
@[appUnexpander PSigma] def unexpandPSigma : Lean.PrettyPrinter.Unexpander
| `($(_) fun ($x:ident : $t) => $b) => `(($x:ident : $t) ×' $b)
| _ => throw ()
@[appUnexpander Subtype] def unexpandSubtype : Lean.PrettyPrinter.Unexpander
| `($(_) fun ($x:ident : $type) => $p) => `({ $x : $type // $p })
| `($(_) fun $x:ident => $p) => `({ $x // $p })
| _ => throw ()
@[appUnexpander TSyntax] def unexpandTSyntax : Lean.PrettyPrinter.Unexpander
| `($f [$k]) => `($f $k)
| _ => throw ()
@[appUnexpander TSyntaxArray] def unexpandTSyntaxArray : Lean.PrettyPrinter.Unexpander
| `($f [$k]) => `($f $k)
| _ => throw ()
@[appUnexpander Syntax.TSepArray] def unexpandTSepArray : Lean.PrettyPrinter.Unexpander
| `($f [$k] $sep) => `($f $k $sep)
| _ => throw ()
@[appUnexpander GetElem.getElem] def unexpandGetElem : Lean.PrettyPrinter.Unexpander
| `($_ $array $index $_) => `($array[$index])
| _ => throw ()
@[appUnexpander getElem!] def unexpandGetElem! : Lean.PrettyPrinter.Unexpander
| `($_ $array $index) => `($array[$index]!)
| _ => throw ()
@[appUnexpander getElem?] def unexpandGetElem? : Lean.PrettyPrinter.Unexpander
| `($_ $array $index) => `($array[$index]?)
| _ => throw ()
@[appUnexpander getElem'] def unexpandGetElem' : Lean.PrettyPrinter.Unexpander
| `($_ $array $index $h) => `($array[$index]'$h)
| _ => throw ()
/--
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.
Patterns can be used like in the `intro` tactic. Example, given a goal
```
|- ((fun x : Nat × Bool => ...) = (fun x => ...))
```
`funext (a, b)` applies `funext` once and performs pattern matching on the newly introduced pair.
-/
syntax "funext " (colGt term:max)+ : tactic
macro_rules
| `(tactic|funext $x) => `(tactic| apply funext; intro $x:term)
| `(tactic|funext $x $xs*) => `(tactic| apply funext; intro $x:term; funext $xs*)
macro_rules
| `(%[ $[$x],* | $k ]) =>
if x.size < 8 then
x.foldrM (β := Term) (init := k) fun x k =>
`(List.cons $x $k)
else
let m := x.size / 2
let y := x[m:]
let z := x[:m]
`(let y := %[ $[$y],* | $k ]
%[ $[$z],* | y ])
/--
Expands
```
class abbrev C <params> := D_1, ..., D_n
```
into
```
class C <params> extends D_1, ..., D_n
attribute [instance] C.mk
```
-/
syntax (name := Lean.Parser.Command.classAbbrev)
declModifiers "class " "abbrev " declId bracketedBinder* (":" term)?
":=" withPosition(group(colGe term ","?)*) : command
macro_rules
| `($mods:declModifiers class abbrev $id $params* $[: $ty]? := $[ $parents $[,]? ]*) =>
let ctor := mkIdentFrom id <| id.raw[0].getId.modifyBase (. ++ `mk)
`($mods:declModifiers class $id $params* extends $parents,* $[: $ty]?
attribute [instance] $ctor)
section
open Lean.Parser.Tactic
/-- `· tac` focuses on the main goal and tries to solve it using `tac`, or else fails. -/
syntax ("·" <|> ".") ppHardSpace many1Indent(tactic ";"? ppLine) : tactic
macro_rules
| `(tactic| ·%$dot $[$tacs $[;%$sc]?]*) => do
let tacs ← tacs.zip sc |>.mapM fun
| (tac, none) => pure tac
| (tac, some sc) => `(tactic| ($tac; with_annotate_state $sc skip))
`(tactic| { with_annotate_state $dot skip; $[$tacs]* })
end
/--
Similar to `first`, but succeeds only if one the given tactics solves the current goal.
-/
syntax (name := solve) "solve " withPosition((colGe "|" tacticSeq)+) : tactic
macro_rules
| `(tactic| solve $[| $ts]* ) => `(tactic| focus first $[| ($ts); done]*)
namespace Lean
/-! # `repeat` and `while` notation -/
inductive Loop where
| mk
@[inline]
partial def Loop.forIn {β : Type u} {m : Type u → Type v} [Monad m] (_ : Loop) (init : β) (f : Unit → β → m (ForInStep β)) : m β :=
let rec @[specialize] loop (b : β) : m β := do
match ← f () b with
| ForInStep.done b => pure b
| ForInStep.yield b => loop b
loop init
instance : ForIn m Loop Unit where
forIn := Loop.forIn
syntax "repeat " doSeq : doElem
macro_rules
| `(doElem| repeat $seq) => `(doElem| for _ in Loop.mk do $seq)
syntax "while " ident " : " termBeforeDo " do " doSeq : doElem
macro_rules
| `(doElem| while $h : $cond do $seq) => `(doElem| repeat if $h : $cond then $seq else break)
syntax "while " termBeforeDo " do " doSeq : doElem
macro_rules
| `(doElem| while $cond do $seq) => `(doElem| repeat if $cond then $seq else break)
syntax "repeat " doSeq " until " term : doElem
macro_rules
| `(doElem| repeat $seq until $cond) => `(doElem| repeat do $seq:doSeq; if $cond then break)
macro:50 e:term:51 " matches " p:sepBy1(term:51, "|") : term =>
`(((match $e:term with | $[$p:term]|* => true | _ => false) : Bool))
end Lean
|
c59f20740d7f3b9d245b90552f411d4ccb675388 | f2fbd9ce3f46053c664b74a5294d7d2f584e72d3 | /src/for_mathlib/completion.lean | a0ebb4e3d62a21ce53bebdcf1f36da366ac43995 | [
"Apache-2.0"
] | permissive | jcommelin/lean-perfectoid-spaces | c656ae26a2338ee7a0072dab63baf577f079ca12 | d5ed816bcc116fd4cde5ce9aaf03905d00ee391c | refs/heads/master | 1,584,610,432,107 | 1,538,491,594,000 | 1,538,491,594,000 | 136,299,168 | 0 | 0 | null | 1,528,274,452,000 | 1,528,274,452,000 | null | UTF-8 | Lean | false | false | 15,040 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
Hausdorff completions of uniform spaces.
The goal is to construct a left-adjoint to the inclusion of complete Hausdorff uniform spaces
into all uniform spaces. Any uniform space `α` gets a completion `completion α` and a morphism
(ie. uniformly continuous map) `to_completion : α → completion α` which solves the universal
mapping problem of factorizing morphisms from `α` to any complete Hausdorff uniform space `β`.
It means any uniformly continuous `f : α → β` gives rise to a unique morphism
`completion.map f : completion α → β` such that `f = completion_extension f ∘ to_completion α`.
Actually `completion_extension f` is defined for all maps from `α` to `β` but it has the desired
properties only if `f` is uniformly continuous.
Beware that `to_completion α` is not injective if `α` is not Hausdorff. But its image is always
dense.
The adjoint functor acting on morphisms is then constructed by the usual abstract nonsense.
For every uniform spaces `α` and `β`, if turns `f : α → β` into
a morphism `completion.map f : completion α → completion β` such that
`(to_completion β) ∘ f = (completion.map f) ∘ to_completion α` provided `f` is uniformly continuous.
This construction is compatible with composition.
This formalization is mostly based on N. Bourbaki: /General Topology/ but from a slightly
different perspective in order to reuse material in analysis.topology.uniform_space.
-/
import analysis.topology.uniform_space
import analysis.topology.continuity
import data.set.function
import for_mathlib.uniform_space
import for_mathlib.data.set.basic
local attribute [instance, priority 0] classical.prop_decidable
local attribute [instance] separation_setoid
open Cauchy set
namespace uniform_space
variables (α : Type*) [uniform_space α]
variables {β : Type*} [uniform_space β]
variables {γ : Type*} [uniform_space γ]
/-- Hausdorff completion of `α` -/
def completion := quotient (separation_setoid $ Cauchy α)
@[priority 50]
instance completion_uniform_space : uniform_space (completion α) := by unfold completion ; apply_instance
instance completion_complete : complete_space (completion α) := complete_space_separation
instance completion_separated : separated (completion α) := separated_separation
instance completion_t2 : t2_space (completion α) := separated_t2
instance completion_regular : regular_space (completion α) := separated_regular
/-- Canonical map. Not always injective. -/
def to_completion : α → completion α := quotient.mk ∘ pure_cauchy
/-- Automatic coercion from `α` to its completion -/
instance : has_coe α (completion α) := ⟨to_completion α⟩
@[simp]
lemma completion_coe : ∀ a : α, to_completion α a = (a : completion α) := assume a, rfl
namespace to_completion
open set
lemma uniform_continuous : uniform_continuous (to_completion α) :=
uniform_continuous.comp uniform_embedding_pure_cauchy.uniform_continuous
uniform_continuous_quotient_mk
lemma continuous : continuous (to_completion α) :=
uniform_continuous.continuous (uniform_continuous α)
variable {α}
lemma dense : closure (range (to_completion α)) = univ :=
begin
dsimp[to_completion],
rw range_comp,
exact quotient_dense_of_dense pure_cauchy_dense
end
lemma dense₁ : closure (range (λ x : α, (x : completion α))) = univ :=
to_completion.dense
lemma dense₂ : let φ : α × β → (completion α) × (completion β) := λ x, ⟨x.1, x.2⟩ in
closure (range φ) = univ :=
begin
intro φ,
have : range φ = set.prod (range (to_completion α)) (range (to_completion β)),
{ ext x,
dsimp[φ],
unfold_coes,
simp[prod.ext_iff] },
simp [this, closure_prod_eq, dense]
end
lemma dense₃ : let β := completion α in let φ : α × α × α → β × β × β := λ x, ⟨x.1, x.2.1, x.2.2⟩ in
closure (range φ) = univ :=
begin
intros β φ,
have : range φ = set.prod (range (to_completion α))
(set.prod (range (to_completion α)) (range (to_completion α))),
{ ext x,
dsimp[φ],
unfold_coes,
simp[prod.ext_iff] },
simp [this, closure_prod_eq, dense]
end
lemma uniform_embedding [separated α] : uniform_embedding (coe : α → completion α) :=
⟨injective_separated_pure_cauchy,
begin
change filter.comap ((λ (y : Cauchy α × Cauchy α), (⟦y.1⟧, ⟦y.2⟧)) ∘
(λ (x : α × α), (pure_cauchy x.1, pure_cauchy x.2))) uniformity = uniformity,
rw [←filter.comap_comap_comp, comap_quotient_eq_uniformity, uniform_embedding_pure_cauchy.2]
end⟩
end to_completion
variable {α}
lemma nonempty_completion_iff : nonempty (completion α) ↔ nonempty α :=
begin
split ; rintro ⟨c⟩,
{ have := eq_univ_iff_forall.1 to_completion.dense c,
have := mem_closure_iff.1 this _ is_open_univ trivial,
rcases exists_mem_of_ne_empty this with ⟨_, ⟨_, a, _⟩⟩,
exact ⟨a⟩ },
{ exact ⟨to_completion α c⟩ }
end
variables [complete_space β] [separated β]
/-- "Extension" to the completion.
Defined for any map `f` but returns garbage if `f` is not uniformly continuous -/
noncomputable
def completion_extension (f : α → β) : completion α → β :=
if H : uniform_continuous f then
let g₀ := (uniform_embedding_pure_cauchy.dense_embedding pure_cauchy_dense).extend f in
have g₀_unif : uniform_continuous g₀ :=
uniform_continuous_uniformly_extend uniform_embedding_pure_cauchy pure_cauchy_dense H,
have compat : ∀ p q : Cauchy α, p ≈ q → g₀ p = g₀ q :=
assume p q h, eq_of_separated_of_uniform_continuous g₀_unif h,
quotient.lift g₀ compat
else
λ x, f (classical.inhabited_of_nonempty $ nonempty_completion_iff.1 ⟨x⟩).default
/-- Completion functor acting on morphisms -/
noncomputable def completion.map (f : α → γ) : completion α → completion γ :=
completion_extension ((to_completion γ) ∘ f)
end uniform_space
namespace completion_extension
open uniform_space
variables {α : Type*} [uniform_space α]
variables {β : Type*} [uniform_space β]
variables [complete_space β] [separated β]
variables {f : α → β} (H : uniform_continuous f)
include H
lemma lifts : f = (completion_extension f) ∘ to_completion α :=
begin
unfold completion_extension,
simp [H],
ext x,
let lim := H.continuous.tendsto x,
have := (uniform_embedding_pure_cauchy.dense_embedding pure_cauchy_dense).extend_e_eq lim,
rw ←this,
refl
end
@[simp]
lemma lifts' : ∀ a : α, f a = (completion_extension f) a := λ a, congr_fun (lifts H) a
lemma uniform_continuity : uniform_continuous (completion_extension f) :=
begin
unfold completion_extension,
split_ifs,
let g := completion_extension f,
intros r r_in,
let g₀ := (uniform_embedding_pure_cauchy.dense_embedding pure_cauchy_dense).extend f,
have g₀_unif : uniform_continuous g₀ :=
uniform_continuous_uniformly_extend uniform_embedding_pure_cauchy pure_cauchy_dense H,
rw filter.mem_map,
dsimp[completion],
rw prod_quotient_preimage_eq_image _ rfl r,
exact filter.image_mem_map (g₀_unif r_in)
end
lemma continuity : continuous (completion_extension f) :=
uniform_continuous.continuous (uniform_continuity H)
lemma unique {h : completion α → β} :
uniform_continuous h → f = (h ∘ to_completion α) → h = completion_extension f :=
begin
let g := completion_extension f,
have g_unif : uniform_continuous g := uniform_continuity H,
intros h_unif h_lifts,
change h = g,
ext x,
have closed_eq : is_closed {x | h x = g x} := is_closed_eq h_unif.continuous g_unif.continuous,
have : f = g ∘ to_completion α := lifts H,
have eq_on_α : ∀ x, (h ∘ to_completion α) x = (g ∘ to_completion α) x, by cc,
exact (is_closed_property to_completion.dense closed_eq eq_on_α x : _)
end
end completion_extension
namespace completion
variables {α : Type*} [uniform_space α] {β : Type*} [uniform_space β]
open uniform_space uniform_space.pure_cauchy
noncomputable
def prod : (completion α) × (completion β) → completion (α × β) :=
begin
let g₀ := λ (a : Cauchy α) (b : Cauchy β), (prod.de.extend (to_completion (α × β))) (a, b),
refine function.uncurry (quotient.lift₂ g₀ _),
{ intros a₁ b₁ a₂ b₂ eqv₁ eqv₂,
have g₁_uc : uniform_continuous (prod.de.extend (to_completion (α × β))),
{ let ue : uniform_embedding (λ (p : α × β), (pure_cauchy (p.fst), pure_cauchy (p.snd))) :=
uniform_embedding.prod uniform_embedding_pure_cauchy uniform_embedding_pure_cauchy,
refine uniform_continuous_uniformly_extend ue _ (to_completion.uniform_continuous (α × β)) },
exact (eq_of_separated_of_uniform_continuous g₁_uc (separation_prod.2 ⟨eqv₁, eqv₂⟩) : _) },
end
lemma prod.uc : uniform_continuous (@prod α _ β _) :=
begin
dsimp[prod],
rw function.uncurry_def,
apply uniform_continuous_quotient_lift₂,
suffices : uniform_continuous (dense_embedding.extend prod.de (to_completion (α × β))),
by simpa,
exact uniform_continuous_uniformly_extend
(uniform_embedding.prod uniform_embedding_pure_cauchy uniform_embedding_pure_cauchy)
prod.de.dense (to_completion.uniform_continuous _)
end
@[simp]
lemma prod.lifts (a : α) (b : β) : @prod α _ β _ (a, b) = (a, b) :=
begin
let f := to_completion (α × β),
change dense_embedding.extend prod.de f (pure_cauchy a, pure_cauchy b) = ⟦pure_cauchy (a, b)⟧,
have hf : filter.tendsto f (nhds (a, b)) (nhds (f (a,b))) :=
continuous.tendsto (to_completion.continuous _) _,
exact (prod.de.extend_e_eq hf : _)
end
/-- Canonical map completion (α × β) → (completion α) × (completion β). Not used in group_completion. -/
noncomputable def prod_inv : completion (α × β) → (completion α) × (completion β) :=
completion_extension (λ x, (x.1, x.2))
@[simp]
lemma prod_inv.lifts : ∀ x : α × β, prod_inv (x : completion (α × β)) = ((x.1 : completion α), (x.2 : completion β)) :=
begin
intros x,
have u1 := uniform_continuous.comp uniform_continuous_fst (to_completion.uniform_continuous α),
have u2 := uniform_continuous.comp uniform_continuous_snd (to_completion.uniform_continuous β),
have := completion_extension.lifts' (uniform_continuous.prod_mk u1 u2) x,
simp at this,
unfold_coes,
simpa [this]
end
lemma prod_inv.uc : uniform_continuous (@prod_inv α _ β _) :=
begin
have u1 := uniform_continuous.comp uniform_continuous_fst (to_completion.uniform_continuous α),
have u2 := uniform_continuous.comp uniform_continuous_snd (to_completion.uniform_continuous β),
exact completion_extension.uniform_continuity (uniform_continuous.prod_mk u1 u2)
end
end completion
namespace uniform_space
variables {α : Type*} [uniform_space α]
variables {β : Type*} [uniform_space β]
variables {γ : Type*} [uniform_space γ]
open uniform_space function
noncomputable def completion.map₂ (f : α → β → γ) : completion α × completion β → completion γ :=
completion.map (uncurry f) ∘ completion.prod
end uniform_space
namespace completion.map
open uniform_space uniform_space.completion
variables {α : Type*} [uniform_space α]
variables {β : Type*} [uniform_space β]
variables {γ : Type*} [uniform_space γ]
variables {δ : Type*} [uniform_space δ]
variables {f : α → β} (H : uniform_continuous f)
variables {g : β → γ} (H' : uniform_continuous g)
lemma lifts : (to_completion β) ∘ f = (map f) ∘ to_completion α :=
completion_extension.lifts $ uniform_continuous.comp H (to_completion.uniform_continuous β)
lemma lifts' : ∀ a : α, (f a : completion β) = map f a :=
congr_fun (lifts H)
lemma unique {f' : completion α → completion β} :
uniform_continuous f' → (to_completion β) ∘ f = f' ∘ to_completion α → f' = map f :=
completion_extension.unique $ uniform_continuous.comp H (to_completion.uniform_continuous β)
lemma uniform_continuity : uniform_continuous (map f) :=
completion_extension.uniform_continuity $ uniform_continuous.comp H (to_completion.uniform_continuous β)
protected lemma id : map (@id α) = id :=
by rw (unique uniform_continuous_id uniform_continuous_id) ; simp
@[simp]
protected lemma const (a : α) : map (λ x : α, a) = (λ x, a) :=
by rw unique uniform_continuous_const uniform_continuous_const ; refl
lemma prod_prod_inv : completion.prod ∘ (@completion.prod_inv α _ β _) = id :=
begin
rw ←completion.map.id,
apply completion.map.unique uniform_continuous_id
(uniform_continuous.comp completion.prod_inv.uc completion.prod.uc),
ext x,
simp
end
lemma prod_inv_prod : completion.prod_inv ∘ (@completion.prod α _ β _) = id :=
begin
funext x,
have closed : is_closed {x | (completion.prod_inv ∘ (@completion.prod α _ β _)) x = id x},
{ have c₁ : continuous (completion.prod_inv ∘ (@completion.prod α _ β _)) :=
continuous.comp (completion.prod.uc.continuous) (completion.prod_inv.uc.continuous),
exact is_closed_eq c₁ continuous_id },
exact (is_closed_property to_completion.dense₂ closed (by simp) x : _)
end
include H H'
lemma comp : map (g ∘ f) = (map g) ∘ map f :=
begin
let l := completion.map f,
let l' := completion.map g,
have : uniform_continuous (g ∘ f) := uniform_continuous.comp H H',
have : uniform_continuous (l' ∘ l ):=
uniform_continuous.comp (uniform_continuity H) (uniform_continuity H'),
have : (to_completion γ ∘ g) ∘ f = (l' ∘ l) ∘ to_completion α := calc
(to_completion γ ∘ g) ∘ f = (l' ∘ to_completion β) ∘ f : by rw completion.map.lifts H'
... = l' ∘ (to_completion β ∘ f) : rfl
... = l' ∘ (l ∘ to_completion α) : by rw completion.map.lifts H,
apply eq.symm,
apply unique ; assumption
end
omit H H'
open function
variables {h : α → β → γ} (h_uc : uniform_continuous (uncurry h))
include h_uc
lemma lifts₂ : (to_completion γ) ∘ (uncurry h) = (map₂ h) ∘ (λ p, (p.1, p.2)) :=
begin
ext x,
rw lifts h_uc,
apply congr_arg (map (uncurry h)),
simp
end
lemma lifts₂' : ∀ (a : α) (b : β), (h a b : completion γ) = map₂ h (a, b) :=
λ a b, congr_fun (lifts₂ h_uc) (a,b)
lemma uniform_continuity₂ : uniform_continuous (map₂ h) :=
uniform_continuous.comp completion.prod.uc (uniform_continuity h_uc)
lemma map₂_map_map {f : δ → α} {g : δ → β} (f_uc : uniform_continuous f) (g_uc : uniform_continuous g) :
map (λ x, h (f x) (g x)) = λ y, map₂ h (map f y, map g y) :=
begin
apply eq.symm,
have uc₁ := (uniform_continuous.comp (uniform_continuous.prod_mk f_uc g_uc) h_uc),
have uc₂ := (uniform_continuous.comp (uniform_continuous.prod_mk (uniform_continuity f_uc) (uniform_continuity g_uc)) (uniform_continuity₂ h_uc)),
apply unique uc₁ uc₂,
ext x,
change (h (f x) (g x) : completion γ) = map₂ h (map f x, map g x),
rw [←lifts' f_uc x, ←lifts' g_uc x, lifts₂' h_uc]
end
end completion.map |
2de6a3160b97fb3803311d68566b002e359e6083 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/mv_polynomial/basic.lean | 6408f52233976a238b80e49949fc3b4693789b71 | [
"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 | 47,738 | 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
-/
import ring_theory.adjoin.basic
import data.finsupp.antidiagonal
import algebra.monoid_algebra.basic
import order.symm_diff
/-!
# Multivariate polynomials
This file defines polynomial rings over a base ring (or even semiring),
with variables from a general type `σ` (which could be infinite).
## Important definitions
Let `R` be a commutative ring (or a semiring) and let `σ` be an arbitrary
type. This file creates the type `mv_polynomial σ R`, which mathematicians
might denote $R[X_i : i \in σ]$. It is the type of multivariate
(a.k.a. multivariable) polynomials, with variables
corresponding to the terms in `σ`, and coefficients in `R`.
### Notation
In the definitions below, we use the following notation:
+ `σ : Type*` (indexing the variables)
+ `R : Type*` `[comm_semiring R]` (the coefficients)
+ `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set.
This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s`
+ `a : R`
+ `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians
+ `p : mv_polynomial σ R`
### Definitions
* `mv_polynomial σ R` : the type of polynomials with variables of type `σ` and coefficients
in the commutative semiring `R`
* `monomial s a` : the monomial which mathematically would be denoted `a * X^s`
* `C a` : the constant polynomial with value `a`
* `X i` : the degree one monomial corresponding to i; mathematically this might be denoted `Xᵢ`.
* `coeff s p` : the coefficient of `s` in `p`.
* `eval₂ (f : R → S₁) (g : σ → S₁) p` : given a semiring homomorphism from `R` to another
semiring `S₁`, and a map `σ → S₁`, evaluates `p` at this valuation, returning a term of type `S₁`.
Note that `eval₂` can be made using `eval` and `map` (see below), and it has been suggested
that sticking to `eval` and `map` might make the code less brittle.
* `eval (g : σ → R) p` : given a map `σ → R`, evaluates `p` at this valuation,
returning a term of type `R`
* `map (f : R → S₁) p` : returns the multivariate polynomial obtained from `p` by the change of
coefficient semiring corresponding to `f`
## Implementation notes
Recall that if `Y` has a zero, then `X →₀ Y` is the type of functions from `X` to `Y` with finite
support, i.e. such that only finitely many elements of `X` get sent to non-zero terms in `Y`.
The definition of `mv_polynomial σ R` is `(σ →₀ ℕ) →₀ R` ; here `σ →₀ ℕ` denotes the space of all
monomials in the variables, and the function to `R` sends a monomial to its coefficient in
the polynomial being represented.
## Tags
polynomial, multivariate polynomial, multivariable polynomial
-/
noncomputable theory
open_locale classical big_operators
open set function finsupp add_monoid_algebra
open_locale big_operators
universes u v w x
variables {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x}
/-- Multivariate polynomial, where `σ` is the index set of the variables and
`R` is the coefficient ring -/
def mv_polynomial (σ : Type*) (R : Type*) [comm_semiring R] := add_monoid_algebra R (σ →₀ ℕ)
namespace mv_polynomial
variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ}
section comm_semiring
section instances
instance decidable_eq_mv_polynomial [comm_semiring R] [decidable_eq σ] [decidable_eq R] :
decidable_eq (mv_polynomial σ R) := finsupp.decidable_eq
instance [comm_semiring R] : comm_semiring (mv_polynomial σ R) := add_monoid_algebra.comm_semiring
instance [comm_semiring R] : inhabited (mv_polynomial σ R) := ⟨0⟩
instance [monoid R] [comm_semiring S₁] [distrib_mul_action R S₁] :
distrib_mul_action R (mv_polynomial σ S₁) :=
add_monoid_algebra.distrib_mul_action
instance [monoid R] [comm_semiring S₁] [distrib_mul_action R S₁] [has_faithful_scalar R S₁] :
has_faithful_scalar R (mv_polynomial σ S₁) :=
add_monoid_algebra.has_faithful_scalar
instance [semiring R] [comm_semiring S₁] [module R S₁] : module R (mv_polynomial σ S₁) :=
add_monoid_algebra.module
instance [monoid R] [monoid S₁] [comm_semiring S₂]
[has_scalar R S₁] [distrib_mul_action R S₂] [distrib_mul_action S₁ S₂] [is_scalar_tower R S₁ S₂] :
is_scalar_tower R S₁ (mv_polynomial σ S₂) :=
add_monoid_algebra.is_scalar_tower
instance [monoid R] [monoid S₁][comm_semiring S₂]
[distrib_mul_action R S₂] [distrib_mul_action S₁ S₂] [smul_comm_class R S₁ S₂] :
smul_comm_class R S₁ (mv_polynomial σ S₂) :=
add_monoid_algebra.smul_comm_class
instance [monoid R] [comm_semiring S₁] [distrib_mul_action R S₁] [distrib_mul_action Rᵐᵒᵖ S₁]
[is_central_scalar R S₁] :
is_central_scalar R (mv_polynomial σ S₁) :=
add_monoid_algebra.is_central_scalar
instance [comm_semiring R] [comm_semiring S₁] [algebra R S₁] : algebra R (mv_polynomial σ S₁) :=
add_monoid_algebra.algebra
-- Register with high priority to avoid timeout in `data.mv_polynomial.pderiv`
instance is_scalar_tower' [comm_semiring R] [comm_semiring S₁] [algebra R S₁] :
is_scalar_tower R (mv_polynomial σ S₁) (mv_polynomial σ S₁) :=
is_scalar_tower.right
-- TODO[gh-6025]: make this an instance once safe to do so
/-- If `R` is a subsingleton, then `mv_polynomial σ R` has a unique element -/
protected def unique [comm_semiring R] [subsingleton R] : unique (mv_polynomial σ R) :=
add_monoid_algebra.unique
end instances
variables [comm_semiring R] [comm_semiring S₁] {p q : mv_polynomial σ R}
/-- `monomial s a` is the monomial with coefficient `a` and exponents given by `s` -/
def monomial (s : σ →₀ ℕ) : R →ₗ[R] mv_polynomial σ R := lsingle s
lemma single_eq_monomial (s : σ →₀ ℕ) (a : R) : single s a = monomial s a := rfl
lemma mul_def : (p * q) = p.sum (λ m a, q.sum $ λ n b, monomial (m + n) (a * b)) := rfl
/-- `C a` is the constant polynomial with value `a` -/
def C : R →+* mv_polynomial σ R :=
{ to_fun := monomial 0, ..single_zero_ring_hom }
variables (R σ)
theorem algebra_map_eq : algebra_map R (mv_polynomial σ R) = C := rfl
variables {R σ}
/-- `X n` is the degree `1` monomial $X_n$. -/
def X (n : σ) : mv_polynomial σ R := monomial (single n 1) 1
lemma C_apply : (C a : mv_polynomial σ R) = monomial 0 a := rfl
@[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ R) := by simp [C_apply, monomial]
@[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ R) := rfl
lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') :=
by simp [C_apply, monomial, single_mul_single]
@[simp] lemma C_add : (C (a + a') : mv_polynomial σ R) = C a + C a' := single_add
@[simp] lemma C_mul : (C (a * a') : mv_polynomial σ R) = C a * C a' := C_mul_monomial.symm
@[simp] lemma C_pow (a : R) (n : ℕ) : (C (a^n) : mv_polynomial σ R) = (C a)^n :=
by induction n; simp [pow_succ, *]
lemma C_injective (σ : Type*) (R : Type*) [comm_semiring R] :
function.injective (C : R → mv_polynomial σ R) :=
finsupp.single_injective _
lemma C_surjective {R : Type*} [comm_semiring R] (σ : Type*) [is_empty σ] :
function.surjective (C : R → mv_polynomial σ R) :=
begin
refine λ p, ⟨p.to_fun 0, finsupp.ext (λ a, _)⟩,
simpa [(finsupp.ext is_empty_elim : a = 0), C_apply, monomial],
end
@[simp] lemma C_inj {σ : Type*} (R : Type*) [comm_semiring R] (r s : R) :
(C r : mv_polynomial σ R) = C s ↔ r = s :=
(C_injective σ R).eq_iff
instance infinite_of_infinite (σ : Type*) (R : Type*) [comm_semiring R] [infinite R] :
infinite (mv_polynomial σ R) :=
infinite.of_injective C (C_injective _ _)
instance infinite_of_nonempty (σ : Type*) (R : Type*) [nonempty σ] [comm_semiring R]
[nontrivial R] :
infinite (mv_polynomial σ R) :=
infinite.of_injective ((λ s : σ →₀ ℕ, monomial s 1) ∘ single (classical.arbitrary σ)) $
function.injective.comp
(λ m n, (finsupp.single_left_inj one_ne_zero).mp) (finsupp.single_injective _)
lemma C_eq_coe_nat (n : ℕ) : (C ↑n : mv_polynomial σ R) = n :=
by induction n; simp [nat.succ_eq_add_one, *]
theorem C_mul' : mv_polynomial.C a * p = a • p :=
(algebra.smul_def a p).symm
lemma smul_eq_C_mul (p : mv_polynomial σ R) (a : R) : a • p = C a * p := C_mul'.symm
lemma C_eq_smul_one : (C a : mv_polynomial σ R) = a • 1 :=
by rw [← C_mul', mul_one]
lemma monomial_pow : monomial s a ^ e = monomial (e • s) (a ^ e) :=
add_monoid_algebra.single_pow e
@[simp] lemma monomial_mul {s s' : σ →₀ ℕ} {a b : R} :
monomial s a * monomial s' b = monomial (s + s') (a * b) :=
add_monoid_algebra.single_mul_single
variables (σ R)
/-- `λ s, monomial s 1` as a homomorphism. -/
def monomial_one_hom : multiplicative (σ →₀ ℕ) →* mv_polynomial σ R :=
add_monoid_algebra.of _ _
variables {σ R}
@[simp] lemma monomial_one_hom_apply :
monomial_one_hom R σ s = (monomial s 1 : mv_polynomial σ R) := rfl
lemma X_pow_eq_monomial : X n ^ e = monomial (single n e) (1 : R) :=
by simp [X, monomial_pow]
lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e) :=
by rw [X_pow_eq_monomial, monomial_mul, mul_one]
lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a) :=
by rw [X_pow_eq_monomial, monomial_mul, one_mul]
lemma monomial_eq_C_mul_X {s : σ} {a : R} {n : ℕ} :
monomial (single s n) a = C a * (X s)^n :=
by rw [← zero_add (single s n), monomial_add_single, C_apply]
@[simp] lemma monomial_zero {s : σ →₀ ℕ} : monomial s (0 : R) = 0 :=
single_zero
@[simp] lemma monomial_zero' : (monomial (0 : σ →₀ ℕ) : R → mv_polynomial σ R) = C := rfl
@[simp] lemma monomial_eq_zero {s : σ →₀ ℕ} {b : R} : monomial s b = 0 ↔ b = 0 :=
finsupp.single_eq_zero
@[simp] lemma sum_monomial_eq {A : Type*} [add_comm_monoid A]
{u : σ →₀ ℕ} {r : R} {b : (σ →₀ ℕ) → R → A} (w : b u 0 = 0) :
sum (monomial u r) b = b u r :=
sum_single_index w
@[simp] lemma sum_C {A : Type*} [add_comm_monoid A]
{b : (σ →₀ ℕ) → R → A} (w : b 0 0 = 0) :
sum (C a) b = b 0 a :=
sum_monomial_eq w
lemma monomial_sum_one {α : Type*} (s : finset α) (f : α → (σ →₀ ℕ)) :
(monomial (∑ i in s, f i) 1 : mv_polynomial σ R) = ∏ i in s, monomial (f i) 1 :=
(monomial_one_hom R σ).map_prod (λ i, multiplicative.of_add (f i)) s
lemma monomial_sum_index {α : Type*} (s : finset α) (f : α → (σ →₀ ℕ)) (a : R) :
(monomial (∑ i in s, f i) a) = C a * ∏ i in s, monomial (f i) 1 :=
by rw [← monomial_sum_one, C_mul', ← (monomial _).map_smul, smul_eq_mul, mul_one]
lemma monomial_finsupp_sum_index {α β : Type*} [has_zero β] (f : α →₀ β)
(g : α → β → (σ →₀ ℕ)) (a : R) :
(monomial (f.sum g) a) = C a * f.prod (λ a b, monomial (g a b) 1) :=
monomial_sum_index _ _ _
lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ R) :=
by simp only [X_pow_eq_monomial, ← monomial_finsupp_sum_index, finsupp.sum_single]
lemma induction_on_monomial {M : mv_polynomial σ R → Prop} (h_C : ∀ a, M (C a))
(h_X : ∀ p n, M p → M (p * X n)) : ∀ 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 [add_comm, monomial_add_single, this] }
end
/-- Analog of `polynomial.induction_on'`.
To prove something about mv_polynomials,
it suffices to show the condition is closed under taking sums,
and it holds for monomials. -/
attribute [elab_as_eliminator]
theorem induction_on' {P : mv_polynomial σ R → Prop} (p : mv_polynomial σ R)
(h1 : ∀ (u : σ →₀ ℕ) (a : R), P (monomial u a))
(h2 : ∀ (p q : mv_polynomial σ R), P p → P q → P (p + q)) : P p :=
finsupp.induction p (suffices P (monomial 0 0), by rwa monomial_zero at this,
show P (monomial 0 0), from h1 0 0)
(λ a b f ha hb hPf, h2 _ _ (h1 _ _) hPf)
/-- Similar to `mv_polynomial.induction_on` but only a weak form of `h_add` is required.-/
lemma induction_on''' {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h_C : ∀ a, M (C a))
(h_add_weak : ∀ (a : σ →₀ ℕ) (b : R) (f : (σ →₀ ℕ) →₀ R),
a ∉ f.support → b ≠ 0 → M f → M (monomial a b + f)) : M p :=
finsupp.induction p (C_0.rec $ h_C 0) h_add_weak
/-- Similar to `mv_polynomial.induction_on` but only a yet weaker form of `h_add` is required.-/
lemma induction_on'' {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h_C : ∀ a, M (C a))
(h_add_weak : ∀ (a : σ →₀ ℕ) (b : R) (f : (σ →₀ ℕ) →₀ R),
a ∉ f.support → b ≠ 0 → M f → M (monomial a b) → M (monomial a b + f))
(h_X : ∀ (p : mv_polynomial σ R) (n : σ), M p → M (p * mv_polynomial.X n)): M p :=
induction_on''' p h_C (λ a b f ha hb hf,
h_add_weak a b f ha hb hf $ induction_on_monomial h_C h_X a b)
/-- Analog of `polynomial.induction_on`.-/
@[recursor 5]
lemma induction_on {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R)
(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 :=
induction_on'' p h_C (λ a b f ha hb hf hm, h_add (monomial a b) f hm hf) h_X
lemma ring_hom_ext {A : Type*} [semiring A] {f g : mv_polynomial σ R →+* A}
(hC : ∀ r, f (C r) = g (C r)) (hX : ∀ i, f (X i) = g (X i)) :
f = g :=
by { ext, exacts [hC _, hX _] }
/-- See note [partially-applied ext lemmas]. -/
@[ext] lemma ring_hom_ext' {A : Type*} [semiring A] {f g : mv_polynomial σ R →+* A}
(hC : f.comp C = g.comp C) (hX : ∀ i, f (X i) = g (X i)) :
f = g :=
ring_hom_ext (ring_hom.ext_iff.1 hC) hX
lemma hom_eq_hom [semiring S₂]
(f g : mv_polynomial σ R →+* S₂)
(hC : f.comp C = g.comp C) (hX : ∀n:σ, f (X n) = g (X n)) (p : mv_polynomial σ R) :
f p = g p :=
ring_hom.congr_fun (ring_hom_ext' hC hX) p
lemma is_id (f : mv_polynomial σ R →+* mv_polynomial σ R)
(hC : f.comp C = C) (hX : ∀n:σ, f (X n) = (X n)) (p : mv_polynomial σ R) :
f p = p :=
hom_eq_hom f (ring_hom.id _) hC hX p
@[ext] lemma alg_hom_ext' {A B : Type*} [comm_semiring A] [comm_semiring B]
[algebra R A] [algebra R B] {f g : mv_polynomial σ A →ₐ[R] B}
(h₁ : f.comp (is_scalar_tower.to_alg_hom R A (mv_polynomial σ A)) =
g.comp (is_scalar_tower.to_alg_hom R A (mv_polynomial σ A)))
(h₂ : ∀ i, f (X i) = g (X i)) : f = g :=
alg_hom.coe_ring_hom_injective (mv_polynomial.ring_hom_ext'
(congr_arg alg_hom.to_ring_hom h₁) h₂)
@[ext] lemma alg_hom_ext {A : Type*} [semiring A] [algebra R A]
{f g : mv_polynomial σ R →ₐ[R] A} (hf : ∀ i : σ, f (X i) = g (X i)) :
f = g :=
add_monoid_algebra.alg_hom_ext' (mul_hom_ext' (λ (x : σ), monoid_hom.ext_mnat (hf x)))
@[simp] lemma alg_hom_C (f : mv_polynomial σ R →ₐ[R] mv_polynomial σ R) (r : R) :
f (C r) = C r :=
f.commutes r
@[simp] lemma adjoin_range_X : algebra.adjoin R (range (X : σ → mv_polynomial σ R)) = ⊤ :=
begin
set S := algebra.adjoin R (range (X : σ → mv_polynomial σ R)),
refine top_unique (λ p hp, _), clear hp,
induction p using mv_polynomial.induction_on,
case h_C : { exact S.algebra_map_mem _ },
case h_add : p q hp hq { exact S.add_mem hp hq },
case h_X : p i hp { exact S.mul_mem hp (algebra.subset_adjoin $ mem_range_self _) }
end
@[ext] lemma linear_map_ext {M : Type*} [add_comm_monoid M] [module R M]
{f g : mv_polynomial σ R →ₗ[R] M} (h : ∀ s, f ∘ₗ monomial s = g ∘ₗ monomial s) :
f = g :=
finsupp.lhom_ext' h
section support
/--
The finite set of all `m : σ →₀ ℕ` such that `X^m` has a non-zero coefficient.
-/
def support (p : mv_polynomial σ R) : finset (σ →₀ ℕ) :=
p.support
lemma finsupp_support_eq_support (p : mv_polynomial σ R) : finsupp.support p = p.support := rfl
lemma support_monomial [decidable (a = 0)] : (monomial s a).support = if a = 0 then ∅ else {s} :=
by convert rfl
lemma support_monomial_subset : (monomial s a).support ⊆ {s} :=
support_single_subset
lemma support_add : (p + q).support ⊆ p.support ∪ q.support := finsupp.support_add
lemma support_X [nontrivial R] : (X n : mv_polynomial σ R).support = {single n 1} :=
by rw [X, support_monomial, if_neg]; exact one_ne_zero
@[simp] lemma support_zero : (0 : mv_polynomial σ R).support = ∅ := rfl
lemma support_sum {α : Type*} {s : finset α} {f : α → mv_polynomial σ R} :
(∑ x in s, f x).support ⊆ s.bUnion (λ x, (f x).support) := finsupp.support_finset_sum
end support
section coeff
/-- The coefficient of the monomial `m` in the multi-variable polynomial `p`. -/
def coeff (m : σ →₀ ℕ) (p : mv_polynomial σ R) : R :=
@coe_fn _ _ (monoid_algebra.has_coe_to_fun _ _) p m
@[simp] lemma mem_support_iff {p : mv_polynomial σ R} {m : σ →₀ ℕ} :
m ∈ p.support ↔ p.coeff m ≠ 0 :=
by simp [support, coeff]
lemma not_mem_support_iff {p : mv_polynomial σ R} {m : σ →₀ ℕ} :
m ∉ p.support ↔ p.coeff m = 0 :=
by simp
lemma sum_def {A} [add_comm_monoid A] {p : mv_polynomial σ R} {b : (σ →₀ ℕ) → R → A} :
p.sum b = ∑ m in p.support, b m (p.coeff m) :=
by simp [support, finsupp.sum, coeff]
lemma support_mul (p q : mv_polynomial σ R) :
(p * q).support ⊆ p.support.bUnion (λ a, q.support.bUnion $ λ b, {a + b}) :=
by convert add_monoid_algebra.support_mul p q; ext; convert iff.rfl
@[ext] lemma ext (p q : mv_polynomial σ R) :
(∀ m, coeff m p = coeff m q) → p = q := ext
lemma ext_iff (p q : mv_polynomial σ R) :
p = q ↔ (∀ m, coeff m p = coeff m q) :=
⟨ λ h m, by rw h, ext p q⟩
@[simp] lemma coeff_add (m : σ →₀ ℕ) (p q : mv_polynomial σ R) :
coeff m (p + q) = coeff m p + coeff m q := add_apply p q m
@[simp] lemma coeff_smul {S₁ : Type*} [monoid S₁] [distrib_mul_action S₁ R]
(m : σ →₀ ℕ) (c : S₁) (p : mv_polynomial σ R) :
coeff m (c • p) = c • coeff m p := smul_apply c p m
@[simp] lemma coeff_zero (m : σ →₀ ℕ) :
coeff m (0 : mv_polynomial σ R) = 0 := rfl
@[simp] lemma coeff_zero_X (i : σ) : coeff 0 (X i : mv_polynomial σ R) = 0 :=
single_eq_of_ne (λ h, by cases single_eq_zero.1 h)
/-- `mv_polynomial.coeff m` but promoted to an `add_monoid_hom`. -/
@[simps] def coeff_add_monoid_hom (m : σ →₀ ℕ) : mv_polynomial σ R →+ R :=
{ to_fun := coeff m,
map_zero' := coeff_zero m,
map_add' := coeff_add m }
lemma coeff_sum {X : Type*} (s : finset X) (f : X → mv_polynomial σ R) (m : σ →₀ ℕ) :
coeff m (∑ x in s, f x) = ∑ x in s, coeff m (f x) :=
(coeff_add_monoid_hom _).map_sum _ s
lemma monic_monomial_eq (m) : monomial m (1:R) = (m.prod $ λn e, X n ^ e : mv_polynomial σ R) :=
by simp [monomial_eq]
@[simp] lemma coeff_monomial [decidable_eq σ] (m n) (a) :
coeff m (monomial n a : mv_polynomial σ R) = if n = m then a else 0 :=
single_apply
@[simp] lemma coeff_C [decidable_eq σ] (m) (a) :
coeff m (C a : mv_polynomial σ R) = if 0 = m then a else 0 :=
single_apply
lemma coeff_one [decidable_eq σ] (m) :
coeff m (1 : mv_polynomial σ R) = if 0 = m then 1 else 0 :=
coeff_C m 1
@[simp] lemma coeff_zero_C (a) : coeff 0 (C a : mv_polynomial σ R) = a :=
single_eq_same
@[simp] lemma coeff_zero_one : coeff 0 (1 : mv_polynomial σ R) = 1 :=
coeff_zero_C 1
lemma coeff_X_pow [decidable_eq σ] (i : σ) (m) (k : ℕ) :
coeff m (X i ^ k : mv_polynomial σ R) = if single i k = m then 1 else 0 :=
begin
have := coeff_monomial m (finsupp.single i k) (1:R),
rwa [@monomial_eq _ _ (1:R) (finsupp.single i k) _,
C_1, one_mul, finsupp.prod_single_index] at this,
exact pow_zero _
end
lemma coeff_X' [decidable_eq σ] (i : σ) (m) :
coeff m (X i : mv_polynomial σ R) = if single i 1 = m then 1 else 0 :=
by rw [← coeff_X_pow, pow_one]
@[simp] lemma coeff_X (i : σ) :
coeff (single i 1) (X i : mv_polynomial σ R) = 1 :=
by rw [coeff_X', if_pos rfl]
@[simp] lemma coeff_C_mul (m) (a : R) (p : mv_polynomial σ R) :
coeff m (C a * p) = a * coeff m p :=
begin
rw [mul_def, sum_C],
{ simp [sum_def, coeff_sum] {contextual := tt} },
simp
end
lemma coeff_mul (p q : mv_polynomial σ R) (n : σ →₀ ℕ) :
coeff n (p * q) = ∑ x in antidiagonal n, coeff x.1 p * coeff x.2 q :=
add_monoid_algebra.mul_apply_antidiagonal p q _ _ $ λ p, mem_antidiagonal
@[simp] lemma coeff_mul_monomial (m) (s : σ →₀ ℕ) (r : R) (p : mv_polynomial σ R) :
coeff (m + s) (p * monomial s r) = coeff m p * r :=
(add_monoid_algebra.mul_single_apply_aux p _ _ _ _ (λ a, add_left_inj _))
@[simp] lemma coeff_monomial_mul (m) (s : σ →₀ ℕ) (r : R) (p : mv_polynomial σ R) :
coeff (s + m) (monomial s r * p) = r * coeff m p :=
(add_monoid_algebra.single_mul_apply_aux p _ _ _ _ (λ a, add_right_inj _))
@[simp] lemma coeff_mul_X (m) (s : σ) (p : mv_polynomial σ R) :
coeff (m + single s 1) (p * X s) = coeff m p :=
(coeff_mul_monomial _ _ _ _).trans (mul_one _)
@[simp] lemma coeff_X_mul (m) (s : σ) (p : mv_polynomial σ R) :
coeff (single s 1 + m) (X s * p) = coeff m p :=
(coeff_monomial_mul _ _ _ _).trans (one_mul _)
@[simp] lemma support_mul_X (s : σ) (p : mv_polynomial σ R) :
(p * X s).support = p.support.map (add_right_embedding (single s 1)) :=
add_monoid_algebra.support_mul_single p _ (by simp) _
@[simp] lemma support_X_mul (s : σ) (p : mv_polynomial σ R) :
(X s * p).support = p.support.map (add_left_embedding (single s 1)) :=
add_monoid_algebra.support_single_mul p _ (by simp) _
lemma support_sdiff_support_subset_support_add [decidable_eq σ] (p q : mv_polynomial σ R) :
p.support \ q.support ⊆ (p + q).support :=
begin
intros m hm,
simp only [not_not, mem_support_iff, finset.mem_sdiff, ne.def] at hm,
simp [hm.2, hm.1],
end
lemma support_symm_diff_support_subset_support_add [decidable_eq σ] (p q : mv_polynomial σ R) :
p.support Δ q.support ⊆ (p + q).support :=
begin
rw [symm_diff_def, finset.sup_eq_union],
apply finset.union_subset,
{ exact support_sdiff_support_subset_support_add p q, },
{ rw add_comm,
exact support_sdiff_support_subset_support_add q p, },
end
lemma coeff_mul_monomial' (m) (s : σ →₀ ℕ) (r : R) (p : mv_polynomial σ R) :
coeff m (p * monomial s r) = if s ≤ m then coeff (m - s) p * r else 0 :=
begin
obtain rfl | hr := eq_or_ne r 0,
{ simp only [monomial_zero, coeff_zero, mul_zero, if_t_t], },
haveI : nontrivial R := nontrivial_of_ne _ _ hr,
split_ifs with h h,
{ conv_rhs {rw ← coeff_mul_monomial _ s},
congr' with t,
rw tsub_add_cancel_of_le h, },
{ rw ← not_mem_support_iff, intro hm, apply h,
have H := support_mul _ _ hm, simp only [finset.mem_bUnion] at H,
rcases H with ⟨j, hj, i', hi', H⟩,
rw [support_monomial, if_neg hr, finset.mem_singleton] at hi', subst i',
rw finset.mem_singleton at H, subst m,
exact le_add_left le_rfl, }
end
lemma coeff_monomial_mul' (m) (s : σ →₀ ℕ) (r : R) (p : mv_polynomial σ R) :
coeff m (monomial s r * p) = if s ≤ m then r * coeff (m - s) p else 0 :=
begin
-- note that if we allow `R` to be non-commutative we will have to duplicate the proof above.
rw [mul_comm, mul_comm r],
exact coeff_mul_monomial' _ _ _ _
end
lemma coeff_mul_X' [decidable_eq σ] (m) (s : σ) (p : mv_polynomial σ R) :
coeff m (p * X s) = if s ∈ m.support then coeff (m - single s 1) p else 0 :=
begin
refine (coeff_mul_monomial' _ _ _ _).trans _,
simp_rw [finsupp.single_le_iff, finsupp.mem_support_iff, nat.succ_le_iff, pos_iff_ne_zero,
mul_one],
end
lemma coeff_X_mul' [decidable_eq σ] (m) (s : σ) (p : mv_polynomial σ R) :
coeff m (X s * p) = if s ∈ m.support then coeff (m - single s 1) p else 0 :=
begin
refine (coeff_monomial_mul' _ _ _ _).trans _,
simp_rw [finsupp.single_le_iff, finsupp.mem_support_iff, nat.succ_le_iff, pos_iff_ne_zero,
one_mul],
end
lemma eq_zero_iff {p : mv_polynomial σ R} :
p = 0 ↔ ∀ d, coeff d p = 0 :=
by { rw ext_iff, simp only [coeff_zero], }
lemma ne_zero_iff {p : mv_polynomial σ R} :
p ≠ 0 ↔ ∃ d, coeff d p ≠ 0 :=
by { rw [ne.def, eq_zero_iff], push_neg, }
lemma exists_coeff_ne_zero {p : mv_polynomial σ R} (h : p ≠ 0) :
∃ d, coeff d p ≠ 0 :=
ne_zero_iff.mp h
lemma C_dvd_iff_dvd_coeff (r : R) (φ : mv_polynomial σ R) :
C r ∣ φ ↔ ∀ i, r ∣ φ.coeff i :=
begin
split,
{ rintros ⟨φ, rfl⟩ c, rw coeff_C_mul, apply dvd_mul_right },
{ intro h,
choose c hc using h,
classical,
let c' : (σ →₀ ℕ) → R := λ i, if i ∈ φ.support then c i else 0,
let ψ : mv_polynomial σ R := ∑ i in φ.support, monomial i (c' i),
use ψ,
apply mv_polynomial.ext, intro i,
simp only [coeff_C_mul, coeff_sum, coeff_monomial, finset.sum_ite_eq', c'],
split_ifs with hi hi,
{ rw hc },
{ rw not_mem_support_iff at hi, rwa mul_zero } },
end
end coeff
section constant_coeff
/--
`constant_coeff p` returns the constant term of the polynomial `p`, defined as `coeff 0 p`.
This is a ring homomorphism.
-/
def constant_coeff : mv_polynomial σ R →+* R :=
{ to_fun := coeff 0,
map_one' := by simp [coeff, add_monoid_algebra.one_def],
map_mul' := by simp [coeff_mul, finsupp.support_single_ne_zero],
map_zero' := coeff_zero _,
map_add' := coeff_add _ }
lemma constant_coeff_eq : (constant_coeff : mv_polynomial σ R → R) = coeff 0 := rfl
@[simp]
lemma constant_coeff_C (r : R) :
constant_coeff (C r : mv_polynomial σ R) = r :=
by simp [constant_coeff_eq]
@[simp]
lemma constant_coeff_X (i : σ) :
constant_coeff (X i : mv_polynomial σ R) = 0 :=
by simp [constant_coeff_eq]
lemma constant_coeff_monomial [decidable_eq σ] (d : σ →₀ ℕ) (r : R) :
constant_coeff (monomial d r) = if d = 0 then r else 0 :=
by rw [constant_coeff_eq, coeff_monomial]
variables (σ R)
@[simp] lemma constant_coeff_comp_C :
constant_coeff.comp (C : R →+* mv_polynomial σ R) = ring_hom.id R :=
by { ext, apply constant_coeff_C }
@[simp] lemma constant_coeff_comp_algebra_map :
constant_coeff.comp (algebra_map R (mv_polynomial σ R)) = ring_hom.id R :=
constant_coeff_comp_C _ _
end constant_coeff
section as_sum
@[simp] lemma support_sum_monomial_coeff (p : mv_polynomial σ R) :
∑ v in p.support, monomial v (coeff v p) = p :=
finsupp.sum_single p
lemma as_sum (p : mv_polynomial σ R) : p = ∑ v in p.support, monomial v (coeff v p) :=
(support_sum_monomial_coeff p).symm
end as_sum
section eval₂
variables (f : R →+* S₁) (g : σ → S₁)
/-- 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 σ R) : S₁ :=
p.sum (λs a, f a * s.prod (λn e, g n ^ e))
lemma eval₂_eq (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) :
f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i in d.support, x i ^ d i :=
rfl
lemma eval₂_eq' [fintype σ] (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) :
f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i, x i ^ d i :=
by { simp only [eval₂_eq, ← finsupp.prod_pow], refl }
@[simp] lemma eval₂_zero : (0 : mv_polynomial σ R).eval₂ f g = 0 :=
finsupp.sum_zero_index
section
@[simp] lemma eval₂_add : (p + q).eval₂ f g = p.eval₂ f g + q.eval₂ f g :=
finsupp.sum_add_index
(by simp [f.map_zero])
(by simp [add_mul, f.map_add])
@[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 [f.map_zero])
@[simp] lemma eval₂_C (a) : (C a).eval₂ f g = f a :=
by rw [C_apply, eval₂_monomial, prod_zero_index, mul_one]
@[simp] lemma eval₂_one : (1 : mv_polynomial σ R).eval₂ f g = 1 :=
(eval₂_C _ _ _).trans f.map_one
@[simp] lemma eval₂_X (n) : (X n).eval₂ f g = g n :=
by simp [eval₂_monomial, f.map_one, 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, f.map_mul] },
{ 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 rw [monomial_single_add, 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,
f.map_one, -add_comm] }
end
lemma eval₂_mul_C : (p * C a).eval₂ f g = p.eval₂ f g * f a :=
(eval₂_mul_monomial _ _).trans $ by simp
@[simp] 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 [eval₂_C, eval₂_mul_C] },
{ simp [mul_add, eval₂_add] {contextual := tt} },
{ simp [X, eval₂_monomial, eval₂_mul_monomial, ← mul_assoc] { contextual := tt} }
end
@[simp] lemma eval₂_pow {p:mv_polynomial σ R} : ∀{n:ℕ}, (p ^ n).eval₂ f g = (p.eval₂ f g)^n
| 0 := by { rw [pow_zero, pow_zero], exact eval₂_one _ _ }
| (n + 1) := by rw [pow_add, pow_one, pow_add, pow_one, eval₂_mul, eval₂_pow]
/-- `mv_polynomial.eval₂` as a `ring_hom`. -/
def eval₂_hom (f : R →+* S₁) (g : σ → S₁) : mv_polynomial σ R →+* S₁ :=
{ to_fun := eval₂ f g,
map_one' := eval₂_one _ _,
map_mul' := λ p q, eval₂_mul _ _,
map_zero' := eval₂_zero _ _,
map_add' := λ p q, eval₂_add _ _ }
@[simp] lemma coe_eval₂_hom (f : R →+* S₁) (g : σ → S₁) :
⇑(eval₂_hom f g) = eval₂ f g := rfl
lemma eval₂_hom_congr {f₁ f₂ : R →+* S₁} {g₁ g₂ : σ → S₁} {p₁ p₂ : mv_polynomial σ R} :
f₁ = f₂ → g₁ = g₂ → p₁ = p₂ → eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ :=
by rintros rfl rfl rfl; refl
end
@[simp] lemma eval₂_hom_C (f : R →+* S₁) (g : σ → S₁) (r : R) :
eval₂_hom f g (C r) = f r := eval₂_C f g r
@[simp] lemma eval₂_hom_X' (f : R →+* S₁) (g : σ → S₁) (i : σ) :
eval₂_hom f g (X i) = g i := eval₂_X f g i
@[simp] lemma comp_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) :
φ.comp (eval₂_hom f g) = (eval₂_hom (φ.comp f) (λ i, φ (g i))) :=
begin
apply mv_polynomial.ring_hom_ext,
{ intro r, rw [ring_hom.comp_apply, eval₂_hom_C, eval₂_hom_C, ring_hom.comp_apply] },
{ intro i, rw [ring_hom.comp_apply, eval₂_hom_X', eval₂_hom_X'] }
end
lemma map_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂)
(p : mv_polynomial σ R) :
φ (eval₂_hom f g p) = (eval₂_hom (φ.comp f) (λ i, φ (g i)) p) :=
by { rw ← comp_eval₂_hom, refl }
lemma eval₂_hom_monomial (f : R →+* S₁) (g : σ → S₁) (d : σ →₀ ℕ) (r : R) :
eval₂_hom f g (monomial d r) = f r * d.prod (λ i k, g i ^ k) :=
by simp only [monomial_eq, ring_hom.map_mul, eval₂_hom_C, finsupp.prod,
ring_hom.map_prod, ring_hom.map_pow, eval₂_hom_X']
section
lemma eval₂_comp_left {S₂} [comm_semiring S₂]
(k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁)
(p) : k (eval₂ f g p) = eval₂ (k.comp f) (k ∘ g) p :=
by apply mv_polynomial.induction_on p; simp [
eval₂_add, k.map_add,
eval₂_mul, k.map_mul] {contextual := tt}
end
@[simp] lemma eval₂_eta (p : mv_polynomial σ R) : eval₂ C X p = p :=
by apply mv_polynomial.induction_on p;
simp [eval₂_add, eval₂_mul] {contextual := tt}
lemma eval₂_congr (g₁ g₂ : σ → S₁)
(h : ∀ {i : σ} {c : σ →₀ ℕ}, i ∈ c.support → coeff c p ≠ 0 → g₁ i = g₂ i) :
p.eval₂ f g₁ = p.eval₂ f g₂ :=
begin
apply finset.sum_congr rfl,
intros c hc, dsimp, congr' 1,
apply finset.prod_congr rfl,
intros i hi, dsimp, congr' 1,
apply h hi,
rwa finsupp.mem_support_iff at hc
end
@[simp] lemma eval₂_prod (s : finset S₂) (p : S₂ → mv_polynomial σ R) :
eval₂ f g (∏ x in s, p x) = ∏ x in s, eval₂ f g (p x) :=
(eval₂_hom f g).map_prod _ s
@[simp] lemma eval₂_sum (s : finset S₂) (p : S₂ → mv_polynomial σ R) :
eval₂ f g (∑ x in s, p x) = ∑ x in s, eval₂ f g (p x) :=
(eval₂_hom f g).map_sum _ s
attribute [to_additive] eval₂_prod
lemma eval₂_assoc (q : S₂ → mv_polynomial σ R) (p : mv_polynomial S₂ R) :
eval₂ f (λ t, eval₂ f g (q t)) p = eval₂ f g (eval₂ C q p) :=
begin
show _ = eval₂_hom f g (eval₂ C q p),
rw eval₂_comp_left (eval₂_hom f g), congr' with a, simp,
end
end eval₂
section eval
variables {f : σ → R}
/-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/
def eval (f : σ → R) : mv_polynomial σ R →+* R := eval₂_hom (ring_hom.id _) f
lemma eval_eq (x : σ → R) (f : mv_polynomial σ R) :
eval x f = ∑ d in f.support, f.coeff d * ∏ i in d.support, x i ^ d i :=
rfl
lemma eval_eq' [fintype σ] (x : σ → R) (f : mv_polynomial σ R) :
eval x f = ∑ d in f.support, f.coeff d * ∏ i, x i ^ d i :=
eval₂_eq' (ring_hom.id R) x f
lemma eval_monomial : eval f (monomial s a) = a * s.prod (λn e, f n ^ e) :=
eval₂_monomial _ _
@[simp] lemma eval_C : ∀ a, eval f (C a) = a := eval₂_C _ _
@[simp] lemma eval_X : ∀ n, eval f (X n) = f n := eval₂_X _ _
@[simp] lemma smul_eval (x) (p : mv_polynomial σ R) (s) : eval x (s • p) = s * eval x p :=
by rw [smul_eq_C_mul, (eval x).map_mul, eval_C]
lemma eval_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) :
eval g (∑ i in s, f i) = ∑ i in s, eval g (f i) :=
(eval g).map_sum _ _
@[to_additive]
lemma eval_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) :
eval g (∏ i in s, f i) = ∏ i in s, eval g (f i) :=
(eval g).map_prod _ _
theorem eval_assoc {τ}
(f : σ → mv_polynomial τ R) (g : τ → R)
(p : mv_polynomial σ R) :
eval (eval g ∘ f) p = eval g (eval₂ C f p) :=
begin
rw eval₂_comp_left (eval g),
unfold eval, simp only [coe_eval₂_hom],
congr' with a, simp
end
end eval
section map
variables (f : R →+* S₁)
/-- `map f p` maps a polynomial `p` across a ring hom `f` -/
def map : mv_polynomial σ R →+* mv_polynomial σ S₁ := eval₂_hom (C.comp f) X
@[simp] theorem map_monomial (s : σ →₀ ℕ) (a : R) : map f (monomial s a) = monomial s (f a) :=
(eval₂_monomial _ _).trans monomial_eq.symm
@[simp] theorem map_C : ∀ (a : R), map f (C a : mv_polynomial σ R) = C (f a) := map_monomial _ _
@[simp] theorem map_X : ∀ (n : σ), map f (X n : mv_polynomial σ R) = X n := eval₂_X _ _
theorem map_id : ∀ (p : mv_polynomial σ R), map (ring_hom.id R) p = p := eval₂_eta
theorem map_map [comm_semiring S₂]
(g : S₁ →+* S₂)
(p : mv_polynomial σ R) :
map g (map f p) = map (g.comp f) p :=
(eval₂_comp_left (map g) (C.comp f) X p).trans $
begin
congr,
{ ext1 a, simp only [map_C, comp_app, ring_hom.coe_comp], },
{ ext1 n, simp only [map_X, comp_app], }
end
theorem eval₂_eq_eval_map (g : σ → S₁) (p : mv_polynomial σ R) :
p.eval₂ f g = eval g (map f p) :=
begin
unfold map eval, simp only [coe_eval₂_hom],
have h := eval₂_comp_left (eval₂_hom _ g),
dsimp at h,
rw h,
congr,
{ ext1 a, simp only [coe_eval₂_hom, ring_hom.id_apply, comp_app, eval₂_C, ring_hom.coe_comp], },
{ ext1 n, simp only [comp_app, eval₂_X], },
end
lemma eval₂_comp_right {S₂} [comm_semiring S₂]
(k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁)
(p) : k (eval₂ f g p) = eval₂ k (k ∘ g) (map f p) :=
begin
apply mv_polynomial.induction_on p,
{ intro r, rw [eval₂_C, map_C, eval₂_C] },
{ intros p q hp hq, rw [eval₂_add, k.map_add, (map f).map_add, eval₂_add, hp, hq] },
{ intros p s hp,
rw [eval₂_mul, k.map_mul, (map f).map_mul, eval₂_mul, map_X, hp, eval₂_X, eval₂_X] }
end
lemma map_eval₂ (f : R →+* S₁) (g : S₂ → mv_polynomial S₃ R) (p : mv_polynomial S₂ R) :
map f (eval₂ C g p) = eval₂ C (map f ∘ g) (map f p) :=
begin
apply mv_polynomial.induction_on p,
{ intro r, rw [eval₂_C, map_C, map_C, eval₂_C] },
{ intros p q hp hq, rw [eval₂_add, (map f).map_add, hp, hq, (map f).map_add, eval₂_add] },
{ intros p s hp,
rw [eval₂_mul, (map f).map_mul, hp, (map f).map_mul, map_X, eval₂_mul, eval₂_X, eval₂_X] }
end
lemma coeff_map (p : mv_polynomial σ R) : ∀ (m : σ →₀ ℕ), coeff m (map f p) = f (coeff m p) :=
begin
apply mv_polynomial.induction_on p; clear p,
{ intros r m, rw [map_C], simp only [coeff_C], split_ifs, {refl}, rw f.map_zero },
{ intros p q hp hq m, simp only [hp, hq, (map f).map_add, coeff_add], rw f.map_add },
{ intros p i hp m, simp only [hp, (map f).map_mul, map_X],
simp only [hp, mem_support_iff, coeff_mul_X'],
split_ifs, {refl},
rw f.map_zero }
end
lemma map_injective (hf : function.injective f) :
function.injective (map f : mv_polynomial σ R → mv_polynomial σ S₁) :=
begin
intros p q h,
simp only [ext_iff, coeff_map] at h ⊢,
intro m,
exact hf (h m),
end
lemma map_surjective (hf : function.surjective f) :
function.surjective (map f : mv_polynomial σ R → mv_polynomial σ S₁) :=
λ p, begin
induction p using mv_polynomial.induction_on' with i fr a b ha hb,
{ obtain ⟨r, rfl⟩ := hf fr,
exact ⟨monomial i r, map_monomial _ _ _⟩, },
{ obtain ⟨a, rfl⟩ := ha,
obtain ⟨b, rfl⟩ := hb,
exact ⟨a + b, ring_hom.map_add _ _ _⟩ },
end
/-- If `f` is a left-inverse of `g` then `map f` is a left-inverse of `map g`. -/
lemma map_left_inverse {f : R →+* S₁} {g : S₁ →+* R} (hf : function.left_inverse f g) :
function.left_inverse (map f : mv_polynomial σ R → mv_polynomial σ S₁) (map g) :=
λ x, by rw [map_map, (ring_hom.ext hf : f.comp g = ring_hom.id _), map_id]
/-- If `f` is a right-inverse of `g` then `map f` is a right-inverse of `map g`. -/
lemma map_right_inverse {f : R →+* S₁} {g : S₁ →+* R} (hf : function.right_inverse f g) :
function.right_inverse (map f : mv_polynomial σ R → mv_polynomial σ S₁) (map g) :=
(map_left_inverse hf.left_inverse).right_inverse
@[simp] lemma eval_map (f : R →+* S₁) (g : σ → S₁) (p : mv_polynomial σ R) :
eval g (map f p) = eval₂ f g p :=
by { apply mv_polynomial.induction_on p; { simp { contextual := tt } } }
@[simp] lemma eval₂_map [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂)
(p : mv_polynomial σ R) :
eval₂ φ g (map f p) = eval₂ (φ.comp f) g p :=
by { rw [← eval_map, ← eval_map, map_map], }
@[simp] lemma eval₂_hom_map_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂)
(p : mv_polynomial σ R) :
eval₂_hom φ g (map f p) = eval₂_hom (φ.comp f) g p :=
eval₂_map f g φ p
@[simp] lemma constant_coeff_map (f : R →+* S₁) (φ : mv_polynomial σ R) :
constant_coeff (mv_polynomial.map f φ) = f (constant_coeff φ) :=
coeff_map f φ 0
lemma constant_coeff_comp_map (f : R →+* S₁) :
(constant_coeff : mv_polynomial σ S₁ →+* S₁).comp (mv_polynomial.map f) = f.comp constant_coeff :=
by { ext; simp }
lemma support_map_subset (p : mv_polynomial σ R) : (map f p).support ⊆ p.support :=
begin
intro x,
simp only [mem_support_iff],
contrapose!,
change p.coeff x = 0 → (map f p).coeff x = 0,
rw coeff_map,
intro hx,
rw hx,
exact ring_hom.map_zero f
end
lemma support_map_of_injective (p : mv_polynomial σ R) {f : R →+* S₁} (hf : injective f) :
(map f p).support = p.support :=
begin
apply finset.subset.antisymm,
{ exact mv_polynomial.support_map_subset _ _ },
intros x hx,
rw mem_support_iff,
contrapose! hx,
simp only [not_not, mem_support_iff],
change (map f p).coeff x = 0 at hx,
rw [coeff_map, ← f.map_zero] at hx,
exact hf hx
end
lemma C_dvd_iff_map_hom_eq_zero
(q : R →+* S₁) (r : R) (hr : ∀ r' : R, q r' = 0 ↔ r ∣ r')
(φ : mv_polynomial σ R) :
C r ∣ φ ↔ map q φ = 0 :=
begin
rw [C_dvd_iff_dvd_coeff, mv_polynomial.ext_iff],
simp only [coeff_map, coeff_zero, hr],
end
lemma map_map_range_eq_iff (f : R →+* S₁) (g : S₁ → R) (hg : g 0 = 0) (φ : mv_polynomial σ S₁) :
map f (finsupp.map_range g hg φ) = φ ↔ ∀ d, f (g (coeff d φ)) = coeff d φ :=
begin
rw mv_polynomial.ext_iff,
apply forall_congr, intro m,
rw [coeff_map],
apply eq_iff_eq_cancel_right.mpr,
refl
end
/-- If `f : S₁ →ₐ[R] S₂` is a morphism of `R`-algebras, then so is `mv_polynomial.map f`. -/
@[simps]
def map_alg_hom [comm_semiring S₂] [algebra R S₁] [algebra R S₂] (f : S₁ →ₐ[R] S₂) :
mv_polynomial σ S₁ →ₐ[R] mv_polynomial σ S₂ :=
{ to_fun := map ↑f,
commutes' := λ r, begin
have h₁ : algebra_map R (mv_polynomial σ S₁) r = C (algebra_map R S₁ r) := rfl,
have h₂ : algebra_map R (mv_polynomial σ S₂) r = C (algebra_map R S₂ r) := rfl,
rw [h₁, h₂, map, eval₂_hom_C, ring_hom.comp_apply, alg_hom.coe_to_ring_hom, alg_hom.commutes],
end,
..map ↑f }
@[simp] lemma map_alg_hom_id [algebra R S₁] :
map_alg_hom (alg_hom.id R S₁) = alg_hom.id R (mv_polynomial σ S₁) :=
alg_hom.ext map_id
@[simp] lemma map_alg_hom_coe_ring_hom [comm_semiring S₂] [algebra R S₁] [algebra R S₂]
(f : S₁ →ₐ[R] S₂) :
↑(map_alg_hom f : _ →ₐ[R] mv_polynomial σ S₂) =
(map ↑f : mv_polynomial σ S₁ →+* mv_polynomial σ S₂) :=
ring_hom.mk_coe _ _ _ _ _
end map
section aeval
/-! ### The algebra of multivariate polynomials -/
variables [algebra R S₁] [comm_semiring S₂]
variables (f : σ → S₁)
/-- A map `σ → S₁` where `S₁` is an algebra over `R` generates an `R`-algebra homomorphism
from multivariate polynomials over `σ` to `S₁`. -/
def aeval : mv_polynomial σ R →ₐ[R] S₁ :=
{ commutes' := λ r, eval₂_C _ _ _
.. eval₂_hom (algebra_map R S₁) f }
theorem aeval_def (p : mv_polynomial σ R) : aeval f p = eval₂ (algebra_map R S₁) f p := rfl
lemma aeval_eq_eval₂_hom (p : mv_polynomial σ R) :
aeval f p = eval₂_hom (algebra_map R S₁) f p := rfl
@[simp] lemma aeval_X (s : σ) : aeval f (X s : mv_polynomial _ R) = f s := eval₂_X _ _ _
@[simp] lemma aeval_C (r : R) : aeval f (C r) = algebra_map R S₁ r := eval₂_C _ _ _
theorem aeval_unique (φ : mv_polynomial σ R →ₐ[R] S₁) :
φ = aeval (φ ∘ X) :=
by { ext i, simp }
lemma comp_aeval {B : Type*} [comm_semiring B] [algebra R B]
(φ : S₁ →ₐ[R] B) :
φ.comp (aeval f) = aeval (λ i, φ (f i)) :=
by { ext i, simp }
@[simp] lemma map_aeval {B : Type*} [comm_semiring B]
(g : σ → S₁) (φ : S₁ →+* B) (p : mv_polynomial σ R) :
φ (aeval g p) = (eval₂_hom (φ.comp (algebra_map R S₁)) (λ i, φ (g i)) p) :=
by { rw ← comp_eval₂_hom, refl }
@[simp] lemma eval₂_hom_zero (f : R →+* S₂) (p : mv_polynomial σ R) :
eval₂_hom f (0 : σ → S₂) p = f (constant_coeff p) :=
begin
suffices : eval₂_hom f (0 : σ → S₂) = f.comp constant_coeff,
from ring_hom.congr_fun this p,
ext; simp
end
@[simp] lemma eval₂_hom_zero' (f : R →+* S₂) (p : mv_polynomial σ R) :
eval₂_hom f (λ _, 0 : σ → S₂) p = f (constant_coeff p) :=
eval₂_hom_zero f p
@[simp] lemma aeval_zero (p : mv_polynomial σ R) :
aeval (0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) :=
eval₂_hom_zero (algebra_map R S₁) p
@[simp] lemma aeval_zero' (p : mv_polynomial σ R) :
aeval (λ _, 0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) :=
aeval_zero p
lemma aeval_monomial (g : σ → S₁) (d : σ →₀ ℕ) (r : R) :
aeval g (monomial d r) = algebra_map _ _ r * d.prod (λ i k, g i ^ k) :=
eval₂_hom_monomial _ _ _ _
lemma eval₂_hom_eq_zero (f : R →+* S₂) (g : σ → S₂) (φ : mv_polynomial σ R)
(h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, g i = 0) :
eval₂_hom f g φ = 0 :=
begin
rw [φ.as_sum, ring_hom.map_sum, finset.sum_eq_zero],
intros d hd,
obtain ⟨i, hi, hgi⟩ : ∃ i ∈ d.support, g i = 0 := h d (finsupp.mem_support_iff.mp hd),
rw [eval₂_hom_monomial, finsupp.prod, finset.prod_eq_zero hi, mul_zero],
rw [hgi, zero_pow],
rwa [pos_iff_ne_zero, ← finsupp.mem_support_iff]
end
lemma aeval_eq_zero [algebra R S₂] (f : σ → S₂) (φ : mv_polynomial σ R)
(h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, f i = 0) :
aeval f φ = 0 :=
eval₂_hom_eq_zero _ _ _ h
lemma aeval_sum {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) :
aeval f (∑ i in s, φ i) = ∑ i in s, aeval f (φ i) :=
(mv_polynomial.aeval f).map_sum _ _
@[to_additive]
lemma aeval_prod {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) :
aeval f (∏ i in s, φ i) = ∏ i in s, aeval f (φ i) :=
(mv_polynomial.aeval f).map_prod _ _
variable (R)
lemma _root_.algebra.adjoin_range_eq_range_aeval :
algebra.adjoin R (set.range f) = (mv_polynomial.aeval f).range :=
by simp only [← algebra.map_top, ← mv_polynomial.adjoin_range_X, alg_hom.map_adjoin,
← set.range_comp, (∘), mv_polynomial.aeval_X]
theorem _root_.algebra.adjoin_eq_range (s : set S₁) :
algebra.adjoin R s = (mv_polynomial.aeval (coe : s → S₁)).range :=
by rw [← algebra.adjoin_range_eq_range_aeval, subtype.range_coe]
end aeval
section aeval_tower
variables {S A B : Type*} [comm_semiring S] [comm_semiring A] [comm_semiring B]
variables [algebra S R] [algebra S A] [algebra S B]
/-- Version of `aeval` for defining algebra homs out of `mv_polynomial σ R` over a smaller base ring
than `R`. -/
def aeval_tower (f : R →ₐ[S] A) (x : σ → A) : mv_polynomial σ R →ₐ[S] A :=
{ commutes' := λ r,
by simp [is_scalar_tower.algebra_map_eq S R (mv_polynomial σ R), algebra_map_eq],
..eval₂_hom ↑f x }
variables (g : R →ₐ[S] A) (y : σ → A)
@[simp] lemma aeval_tower_X (i : σ): aeval_tower g y (X i) = y i := eval₂_X _ _ _
@[simp] lemma aeval_tower_C (x : R) : aeval_tower g y (C x) = g x := eval₂_C _ _ _
@[simp] lemma aeval_tower_comp_C : ((aeval_tower g y : mv_polynomial σ R →+* A).comp C) = g :=
ring_hom.ext $ aeval_tower_C _ _
@[simp] lemma aeval_tower_algebra_map (x : R) :
aeval_tower g y (algebra_map R (mv_polynomial σ R) x) = g x := eval₂_C _ _ _
@[simp] lemma aeval_tower_comp_algebra_map :
(aeval_tower g y : mv_polynomial σ R →+* A).comp (algebra_map R (mv_polynomial σ R)) = g :=
aeval_tower_comp_C _ _
lemma aeval_tower_to_alg_hom (x : R) :
aeval_tower g y (is_scalar_tower.to_alg_hom S R (mv_polynomial σ R) x) = g x :=
aeval_tower_algebra_map _ _ _
@[simp] lemma aeval_tower_comp_to_alg_hom :
(aeval_tower g y).comp (is_scalar_tower.to_alg_hom S R (mv_polynomial σ R)) = g :=
alg_hom.coe_ring_hom_injective $ aeval_tower_comp_algebra_map _ _
@[simp] lemma aeval_tower_id : aeval_tower (alg_hom.id S S) =
(aeval : (σ → S) → (mv_polynomial σ S →ₐ[S] S)) :=
by { ext, simp only [aeval_tower_X, aeval_X] }
@[simp] lemma aeval_tower_of_id : aeval_tower (algebra.of_id S A) =
(aeval : (σ → A) → (mv_polynomial σ S →ₐ[S] A)) :=
by { ext, simp only [aeval_X, aeval_tower_X] }
end aeval_tower
end comm_semiring
end mv_polynomial
|
41e2a4114f1ec437cc089870457300828a3d5ae6 | 367134ba5a65885e863bdc4507601606690974c1 | /src/data/set/intervals/ord_connected.lean | e981566098fb2d47e1ce1de91ed0bbe04d0b6f35 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 6,283 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury G. Kudryashov
-/
import data.set.intervals.unordered_interval
import data.set.lattice
/-!
# Order-connected sets
We say that a set `s : set α` is `ord_connected` if for all `x y ∈ s` it includes the
interval `[x, y]`. If `α` is a `densely_ordered` `conditionally_complete_linear_order` with
the `order_topology`, then this condition is equivalent to `is_preconnected s`. If `α = ℝ`, then
this condition is also equivalent to `convex s`.
In this file we prove that intersection of a family of `ord_connected` sets is `ord_connected` and
that all standard intervals are `ord_connected`.
-/
namespace set
variables {α : Type*} [preorder α] {s t : set α}
/--
We say that a set `s : set α` is `ord_connected` if for all `x y ∈ s` it includes the
interval `[x, y]`. If `α` is a `densely_ordered` `conditionally_complete_linear_order` with
the `order_topology`, then this condition is equivalent to `is_preconnected s`. If `α = ℝ`, then
this condition is also equivalent to `convex s`.
-/
def ord_connected (s : set α) : Prop := ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), Icc x y ⊆ s
attribute [class] ord_connected
/-- It suffices to prove `[x, y] ⊆ s` for `x y ∈ s`, `x ≤ y`. -/
lemma ord_connected_iff : ord_connected s ↔ ∀ (x ∈ s) (y ∈ s), x ≤ y → Icc x y ⊆ s :=
⟨λ hs x hx y hy hxy, hs hx hy, λ H x hx y hy z hz, H x hx y hy (le_trans hz.1 hz.2) hz⟩
lemma ord_connected_of_Ioo {α : Type*} [partial_order α] {s : set α}
(hs : ∀ (x ∈ s) (y ∈ s), x < y → Ioo x y ⊆ s) :
ord_connected s :=
begin
rw ord_connected_iff,
intros x hx y hy hxy,
rcases eq_or_lt_of_le hxy with rfl|hxy', { simpa },
have := hs x hx y hy hxy',
rw [← union_diff_cancel Ioo_subset_Icc_self],
simp [*, insert_subset]
end
protected lemma Icc_subset (s : set α) [hs : ord_connected s] {x y} (hx : x ∈ s) (hy : y ∈ s) :
Icc x y ⊆ s :=
hs hx hy
lemma ord_connected.inter {s t : set α} (hs : ord_connected s) (ht : ord_connected t) :
ord_connected (s ∩ t) :=
λ x hx y hy, subset_inter (hs hx.1 hy.1) (ht hx.2 hy.2)
instance ord_connected.inter' {s t : set α} [ord_connected s] [ord_connected t] :
ord_connected (s ∩ t) :=
ord_connected.inter ‹_› ‹_›
lemma ord_connected.dual {s : set α} (hs : ord_connected s) : @ord_connected (order_dual α) _ s :=
λ x hx y hy z hz, hs hy hx ⟨hz.2, hz.1⟩
lemma ord_connected_dual {s : set α} : @ord_connected (order_dual α) _ s ↔ ord_connected s :=
⟨λ h, h.dual, λ h, h.dual⟩
lemma ord_connected_sInter {S : set (set α)} (hS : ∀ s ∈ S, ord_connected s) :
ord_connected (⋂₀ S) :=
λ x hx y hy, subset_sInter $ λ s hs, hS s hs (hx s hs) (hy s hs)
lemma ord_connected_Inter {ι : Sort*} {s : ι → set α} (hs : ∀ i, ord_connected (s i)) :
ord_connected (⋂ i, s i) :=
ord_connected_sInter $ forall_range_iff.2 hs
instance ord_connected_Inter' {ι : Sort*} {s : ι → set α} [∀ i, ord_connected (s i)] :
ord_connected (⋂ i, s i) :=
ord_connected_Inter ‹_›
lemma ord_connected_bInter {ι : Sort*} {p : ι → Prop} {s : Π (i : ι) (hi : p i), set α}
(hs : ∀ i hi, ord_connected (s i hi)) :
ord_connected (⋂ i hi, s i hi) :=
ord_connected_Inter $ λ i, ord_connected_Inter $ hs i
lemma ord_connected_pi {ι : Type*} {α : ι → Type*} [Π i, preorder (α i)] {s : set ι}
{t : Π i, set (α i)} (h : ∀ i ∈ s, ord_connected (t i)) : ord_connected (s.pi t) :=
λ x hx y hy z hz i hi, h i hi (hx i hi) (hy i hi) ⟨hz.1 i, hz.2 i⟩
instance ord_connected_pi' {ι : Type*} {α : ι → Type*} [Π i, preorder (α i)] {s : set ι}
{t : Π i, set (α i)} [h : ∀ i, ord_connected (t i)] : ord_connected (s.pi t) :=
ord_connected_pi $ λ i hi, h i
@[instance] lemma ord_connected_Ici {a : α} : ord_connected (Ici a) :=
λ x hx y hy z hz, le_trans hx hz.1
@[instance] lemma ord_connected_Iic {a : α} : ord_connected (Iic a) :=
λ x hx y hy z hz, le_trans hz.2 hy
@[instance] lemma ord_connected_Ioi {a : α} : ord_connected (Ioi a) :=
λ x hx y hy z hz, lt_of_lt_of_le hx hz.1
@[instance] lemma ord_connected_Iio {a : α} : ord_connected (Iio a) :=
λ x hx y hy z hz, lt_of_le_of_lt hz.2 hy
@[instance] lemma ord_connected_Icc {a b : α} : ord_connected (Icc a b) :=
ord_connected_Ici.inter ord_connected_Iic
@[instance] lemma ord_connected_Ico {a b : α} : ord_connected (Ico a b) :=
ord_connected_Ici.inter ord_connected_Iio
@[instance] lemma ord_connected_Ioc {a b : α} : ord_connected (Ioc a b) :=
ord_connected_Ioi.inter ord_connected_Iic
@[instance] lemma ord_connected_Ioo {a b : α} : ord_connected (Ioo a b) :=
ord_connected_Ioi.inter ord_connected_Iio
@[instance] lemma ord_connected_singleton {α : Type*} [partial_order α] {a : α} :
ord_connected ({a} : set α) :=
by { rw ← Icc_self, exact ord_connected_Icc }
@[instance] lemma ord_connected_empty : ord_connected (∅ : set α) := λ x, false.elim
@[instance] lemma ord_connected_univ : ord_connected (univ : set α) := λ _ _ _ _, subset_univ _
/-- In a dense order `α`, the subtype from an `ord_connected` set is also densely ordered. -/
instance [densely_ordered α] {s : set α} [hs : ord_connected s] :
densely_ordered s :=
⟨ begin
intros a₁ a₂ ha,
have ha' : ↑a₁ < ↑a₂ := ha,
obtain ⟨x, ha₁x, hxa₂⟩ := exists_between ha',
refine ⟨⟨x, _⟩, ⟨ha₁x, hxa₂⟩⟩,
exact (hs a₁.2 a₂.2) (Ioo_subset_Icc_self ⟨ha₁x, hxa₂⟩),
end ⟩
variables {β : Type*} [linear_order β]
@[instance] lemma ord_connected_interval {a b : β} : ord_connected (interval a b) :=
ord_connected_Icc
lemma ord_connected.interval_subset {s : set β} (hs : ord_connected s)
⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s) :
interval x y ⊆ s :=
by cases le_total x y; simp only [interval_of_le, interval_of_ge, *]; apply hs; assumption
lemma ord_connected_iff_interval_subset {s : set β} :
ord_connected s ↔ ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), interval x y ⊆ s :=
⟨λ h, h.interval_subset,
λ h, ord_connected_iff.2 $ λ x hx y hy hxy, by simpa only [interval_of_le hxy] using h hx hy⟩
end set
|
4f15e4c2102229ff2b911355af3fff7391d80315 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/category_theory/abelian/exact.lean | 79419368d87ef85ecfc9b16424f8c574cbec4246 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 18,199 | lean | /-
Copyright (c) 2020 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel, Adam Topaz, Johan Commelin, Jakob von Raumer
-/
import category_theory.abelian.opposite
import category_theory.limits.constructions.finite_products_of_binary_products
import category_theory.limits.preserves.shapes.zero
import category_theory.limits.preserves.shapes.kernels
import category_theory.preadditive.left_exact
import category_theory.adjunction.limits
import algebra.homology.exact
import tactic.tfae
/-!
# Exact sequences in abelian categories
In an abelian category, we get several interesting results related to exactness which are not
true in more general settings.
## Main results
* `(f, g)` is exact if and only if `f ≫ g = 0` and `kernel.ι g ≫ cokernel.π f = 0`. This
characterisation tends to be less cumbersome to work with than the original definition involving
the comparison map `image f ⟶ kernel g`.
* If `(f, g)` is exact, then `image.ι f` has the universal property of the kernel of `g`.
* `f` is a monomorphism iff `kernel.ι f = 0` iff `exact 0 f`, and `f` is an epimorphism iff
`cokernel.π = 0` iff `exact f 0`.
* A faithful functor between abelian categories that preserves zero morphisms reflects exact
sequences.
* `X ⟶ Y ⟶ Z ⟶ 0` is exact if and only if the second map is a cokernel of the first, and
`0 ⟶ X ⟶ Y ⟶ Z` is exact if and only if the first map is a kernel of the second.
* An exact functor preserves exactness, more specifically, `F` preserves finite colimits and
finite limits, if and only if `exact f g` implies `exact (F.map f) (F.map g)`.
-/
universes v₁ v₂ u₁ u₂
noncomputable theory
open category_theory
open category_theory.limits
open category_theory.preadditive
variables {C : Type u₁} [category.{v₁} C] [abelian C]
namespace category_theory
namespace abelian
variables {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
local attribute [instance] has_equalizers_of_has_kernels
/--
In an abelian category, a pair of morphisms `f : X ⟶ Y`, `g : Y ⟶ Z` is exact
iff `image_subobject f = kernel_subobject g`.
-/
theorem exact_iff_image_eq_kernel : exact f g ↔ image_subobject f = kernel_subobject g :=
begin
split,
{ intro h,
fapply subobject.eq_of_comm,
{ suffices : is_iso (image_to_kernel _ _ h.w),
{ exactI as_iso (image_to_kernel _ _ h.w), },
exact is_iso_of_mono_of_epi _, },
{ simp, }, },
{ apply exact_of_image_eq_kernel, },
end
theorem exact_iff : exact f g ↔ f ≫ g = 0 ∧ kernel.ι g ≫ cokernel.π f = 0 :=
begin
split,
{ intro h,
exact ⟨h.1, kernel_comp_cokernel f g h⟩ },
{ refine λ h, ⟨h.1, _⟩,
suffices hl : is_limit
(kernel_fork.of_ι (image_subobject f).arrow (image_subobject_arrow_comp_eq_zero h.1)),
{ have : image_to_kernel f g h.1 =
(is_limit.cone_point_unique_up_to_iso hl (limit.is_limit _)).hom ≫
(kernel_subobject_iso _).inv,
{ ext, simp },
rw this,
apply_instance, },
refine kernel_fork.is_limit.of_ι _ _ _ _ _,
{ refine λ W u hu,
kernel.lift (cokernel.π f) u _ ≫ (image_iso_image f).hom ≫ (image_subobject_iso _).inv,
rw [←kernel.lift_ι g u hu, category.assoc, h.2, has_zero_morphisms.comp_zero] },
{ tidy },
{ intros, rw [←cancel_mono (image_subobject f).arrow, w],
simp, } }
end
theorem exact_iff' {cg : kernel_fork g} (hg : is_limit cg)
{cf : cokernel_cofork f} (hf : is_colimit cf) : exact f g ↔ f ≫ g = 0 ∧ cg.ι ≫ cf.π = 0 :=
begin
split,
{ intro h,
exact ⟨h.1, fork_ι_comp_cofork_π f g h cg cf⟩ },
{ rw exact_iff,
refine λ h, ⟨h.1, _⟩,
apply zero_of_epi_comp (is_limit.cone_point_unique_up_to_iso hg (limit.is_limit _)).hom,
apply zero_of_comp_mono
(is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) hf).hom,
simp [h.2] }
end
theorem exact_tfae :
tfae [exact f g,
f ≫ g = 0 ∧ kernel.ι g ≫ cokernel.π f = 0,
image_subobject f = kernel_subobject g] :=
begin
tfae_have : 1 ↔ 2, { apply exact_iff },
tfae_have : 1 ↔ 3, { apply exact_iff_image_eq_kernel },
tfae_finish
end
lemma is_equivalence.exact_iff {D : Type u₁} [category.{v₁} D] [abelian D]
(F : C ⥤ D) [is_equivalence F] :
exact (F.map f) (F.map g) ↔ exact f g :=
begin
simp only [exact_iff, ← F.map_eq_zero_iff, F.map_comp, category.assoc,
← kernel_comparison_comp_ι g F, ← π_comp_cokernel_comparison f F],
rw [is_iso.comp_left_eq_zero (kernel_comparison g F), ← category.assoc,
is_iso.comp_right_eq_zero _ (cokernel_comparison f F)],
end
/-- The dual result is true even in non-abelian categories, see
`category_theory.exact_comp_mono_iff`. -/
lemma exact_epi_comp_iff {W : C} (h : W ⟶ X) [epi h] : exact (h ≫ f) g ↔ exact f g :=
begin
refine ⟨λ hfg, _, λ h, exact_epi_comp h⟩,
let hc := is_cokernel_of_comp _ _ (colimit.is_colimit (parallel_pair (h ≫ f) 0))
(by rw [← cancel_epi h, ← category.assoc, cokernel_cofork.condition, comp_zero]) rfl,
refine (exact_iff' _ _ (limit.is_limit _) hc).2 ⟨_, ((exact_iff _ _).1 hfg).2⟩,
exact zero_of_epi_comp h (by rw [← hfg.1, category.assoc])
end
/-- If `(f, g)` is exact, then `abelian.image.ι f` is a kernel of `g`. -/
def is_limit_image (h : exact f g) :
is_limit
(kernel_fork.of_ι (abelian.image.ι f) (image_ι_comp_eq_zero h.1) : kernel_fork g) :=
begin
rw exact_iff at h,
refine kernel_fork.is_limit.of_ι _ _ _ _ _,
{ refine λ W u hu, kernel.lift (cokernel.π f) u _,
rw [←kernel.lift_ι g u hu, category.assoc, h.2, has_zero_morphisms.comp_zero] },
tidy
end
/-- If `(f, g)` is exact, then `image.ι f` is a kernel of `g`. -/
def is_limit_image' (h : exact f g) :
is_limit (kernel_fork.of_ι (limits.image.ι f) (limits.image_ι_comp_eq_zero h.1)) :=
is_kernel.iso_kernel _ _ (is_limit_image f g h) (image_iso_image f).symm $ is_image.lift_fac _ _
/-- If `(f, g)` is exact, then `coimages.coimage.π g` is a cokernel of `f`. -/
def is_colimit_coimage (h : exact f g) : is_colimit (cokernel_cofork.of_π (abelian.coimage.π g)
(abelian.comp_coimage_π_eq_zero h.1) : cokernel_cofork f) :=
begin
rw exact_iff at h,
refine cokernel_cofork.is_colimit.of_π _ _ _ _ _,
{ refine λ W u hu, cokernel.desc (kernel.ι g) u _,
rw [←cokernel.π_desc f u hu, ←category.assoc, h.2, has_zero_morphisms.zero_comp] },
tidy
end
/-- If `(f, g)` is exact, then `factor_thru_image g` is a cokernel of `f`. -/
def is_colimit_image (h : exact f g) : is_colimit
(cokernel_cofork.of_π (limits.factor_thru_image g) (comp_factor_thru_image_eq_zero h.1)) :=
is_cokernel.cokernel_iso _ _ (is_colimit_coimage f g h) (coimage_iso_image' g) $
(cancel_mono (limits.image.ι g)).1 $ by simp
lemma exact_cokernel : exact f (cokernel.π f) :=
by { rw exact_iff, tidy }
instance (h : exact f g) : mono (cokernel.desc f g h.w) :=
suffices h : cokernel.desc f g h.w =
(is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (is_colimit_image f g h)).hom
≫ limits.image.ι g, by { rw h, apply mono_comp },
(cancel_epi (cokernel.π f)).1 $ by simp
/-- If `ex : exact f g` and `epi g`, then `cokernel.desc _ _ ex.w` is an isomorphism. -/
instance (ex : exact f g) [epi g] : is_iso (cokernel.desc f g ex.w) :=
is_iso_of_mono_of_epi (limits.cokernel.desc f g ex.w)
@[simp, reassoc]
lemma cokernel.desc.inv [epi g] (ex : exact f g) :
g ≫ inv (cokernel.desc _ _ ex.w) = cokernel.π _ :=
by simp
instance (ex : exact f g) [mono f] : is_iso (kernel.lift g f ex.w) :=
is_iso_of_mono_of_epi (limits.kernel.lift g f ex.w)
@[simp, reassoc]
lemma kernel.lift.inv [mono f] (ex : exact f g) :
inv (kernel.lift _ _ ex.w) ≫ f = kernel.ι g :=
by simp
/-- If `X ⟶ Y ⟶ Z ⟶ 0` is exact, then the second map is a cokernel of the first. -/
def is_colimit_of_exact_of_epi [epi g] (h : exact f g) :
is_colimit (cokernel_cofork.of_π _ h.w) :=
is_colimit.of_iso_colimit (colimit.is_colimit _) $ cocones.ext
⟨cokernel.desc _ _ h.w, epi_desc g (cokernel.π f) ((exact_iff _ _).1 h).2,
(cancel_epi (cokernel.π f)).1 (by tidy), (cancel_epi g).1 (by tidy)⟩ (λ j, by cases j; simp)
/-- If `0 ⟶ X ⟶ Y ⟶ Z` is exact, then the first map is a kernel of the second. -/
def is_limit_of_exact_of_mono [mono f] (h : exact f g) :
is_limit (kernel_fork.of_ι _ h.w) :=
is_limit.of_iso_limit (limit.is_limit _) $ cones.ext
⟨mono_lift f (kernel.ι g) ((exact_iff _ _).1 h).2, kernel.lift _ _ h.w,
(cancel_mono (kernel.ι g)).1 (by tidy), (cancel_mono f).1 (by tidy)⟩ (λ j, by cases j; simp)
lemma exact_of_is_cokernel (w : f ≫ g = 0)
(h : is_colimit (cokernel_cofork.of_π _ w)) : exact f g :=
begin
refine (exact_iff _ _).2 ⟨w, _⟩,
have := h.fac (cokernel_cofork.of_π _ (cokernel.condition f)) walking_parallel_pair.one,
simp only [cofork.of_π_ι_app] at this,
rw [← this, ← category.assoc, kernel.condition, zero_comp]
end
lemma exact_of_is_kernel (w : f ≫ g = 0)
(h : is_limit (kernel_fork.of_ι _ w)) : exact f g :=
begin
refine (exact_iff _ _).2 ⟨w, _⟩,
have := h.fac (kernel_fork.of_ι _ (kernel.condition g)) walking_parallel_pair.zero,
simp only [fork.of_ι_π_app] at this,
rw [← this, category.assoc, cokernel.condition, comp_zero]
end
lemma exact_iff_exact_image_ι : exact f g ↔ exact (abelian.image.ι f) g :=
by conv_lhs { rw ← abelian.image.fac f }; apply exact_epi_comp_iff
lemma exact_iff_exact_coimage_π : exact f g ↔ exact f (coimage.π g) :=
by conv_lhs { rw ← abelian.coimage.fac g}; apply exact_comp_mono_iff
section
variables (Z)
lemma tfae_mono : tfae [mono f, kernel.ι f = 0, exact (0 : Z ⟶ X) f] :=
begin
tfae_have : 3 → 2,
{ exact kernel_ι_eq_zero_of_exact_zero_left Z },
tfae_have : 1 → 3,
{ introsI, exact exact_zero_left_of_mono Z },
tfae_have : 2 → 1,
{ exact mono_of_kernel_ι_eq_zero _ },
tfae_finish
end
-- Note we've already proved `mono_iff_exact_zero_left : mono f ↔ exact (0 : Z ⟶ X) f`
-- in any preadditive category with kernels and images.
lemma mono_iff_kernel_ι_eq_zero : mono f ↔ kernel.ι f = 0 :=
(tfae_mono X f).out 0 1
lemma tfae_epi : tfae [epi f, cokernel.π f = 0, exact f (0 : Y ⟶ Z)] :=
begin
tfae_have : 3 → 2,
{ rw exact_iff,
rintro ⟨-, h⟩,
exact zero_of_epi_comp _ h },
tfae_have : 1 → 3,
{ rw exact_iff,
introI,
exact ⟨by simp, by simp [cokernel.π_of_epi]⟩ },
tfae_have : 2 → 1,
{ exact epi_of_cokernel_π_eq_zero _ },
tfae_finish
end
-- Note we've already proved `epi_iff_exact_zero_right : epi f ↔ exact f (0 : Y ⟶ Z)`
-- in any preadditive category with equalizers and images.
lemma epi_iff_cokernel_π_eq_zero : epi f ↔ cokernel.π f = 0 :=
(tfae_epi X f).out 0 1
end
section opposite
lemma exact.op (h : exact f g) : exact g.op f.op :=
begin
rw exact_iff,
refine ⟨by simp [← op_comp, h.w], quiver.hom.unop_inj _⟩,
simp only [unop_comp, cokernel.π_op, eq_to_hom_refl, kernel.ι_op, category.id_comp,
category.assoc, kernel_comp_cokernel_assoc _ _ h, zero_comp, comp_zero, unop_zero],
end
lemma exact.op_iff : exact g.op f.op ↔ exact f g :=
⟨λ e, begin
rw ← is_equivalence.exact_iff _ _ (op_op_equivalence C).inverse,
exact exact.op _ _ e
end, exact.op _ _⟩
lemma exact.unop {X Y Z : Cᵒᵖ} (g : X ⟶ Y) (f : Y ⟶ Z) (h : exact g f) : exact f.unop g.unop :=
begin
rw [← f.op_unop, ← g.op_unop] at h,
rwa ← exact.op_iff,
end
lemma exact.unop_iff {X Y Z : Cᵒᵖ} (g : X ⟶ Y) (f : Y ⟶ Z) : exact f.unop g.unop ↔ exact g f :=
⟨λ e, by rwa [← f.op_unop, ← g.op_unop, ← exact.op_iff] at e, λ e, @@exact.unop _ _ g f e⟩
end opposite
end abelian
namespace functor
section
variables {D : Type u₂} [category.{v₂} D] [abelian D]
variables (F : C ⥤ D) [preserves_zero_morphisms F]
@[priority 100]
instance reflects_exact_sequences_of_preserves_zero_morphisms_of_faithful [faithful F] :
reflects_exact_sequences F :=
{ reflects := λ X Y Z f g hfg,
begin
rw [abelian.exact_iff, ← F.map_comp, F.map_eq_zero_iff] at hfg,
refine (abelian.exact_iff _ _).2 ⟨hfg.1, F.zero_of_map_zero _ _⟩,
obtain ⟨k, hk⟩ := kernel.lift' (F.map g) (F.map (kernel.ι g))
(by simp only [← F.map_comp, kernel.condition, category_theory.functor.map_zero]),
obtain ⟨l, hl⟩ := cokernel.desc' (F.map f) (F.map (cokernel.π f))
(by simp only [← F.map_comp, cokernel.condition, category_theory.functor.map_zero]),
rw [F.map_comp, ← hk, ← hl, category.assoc, reassoc_of hfg.2, zero_comp, comp_zero]
end }
end
end functor
namespace functor
open limits abelian
variables {A : Type u₁} {B : Type u₂} [category.{v₁} A] [category.{v₂} B]
variables [abelian A] [abelian B]
variables (L : A ⥤ B)
section
variables [preserves_finite_limits L] [preserves_finite_colimits L]
/-- A functor preserving finite limits and finite colimits preserves exactness. The converse
result is also true, see `functor.preserves_finite_limits_of_map_exact` and
`functor.preserves_finite_colimits_of_map_exact`. -/
lemma map_exact {X Y Z : A} (f : X ⟶ Y) (g : Y ⟶ Z) (e1 : exact f g) :
exact (L.map f) (L.map g) :=
begin
let hcoker := is_colimit_of_has_cokernel_of_preserves_colimit L f,
let hker := is_limit_of_has_kernel_of_preserves_limit L g,
refine (exact_iff' _ _ hker hcoker).2 ⟨by simp [← L.map_comp, e1.1], _⟩,
rw [fork.ι_of_ι, cofork.π_of_π, ← L.map_comp, kernel_comp_cokernel _ _ e1, L.map_zero]
end
end
section
variables (h : ∀ ⦃X Y Z : A⦄ {f : X ⟶ Y} {g : Y ⟶ Z}, exact f g → exact (L.map f) (L.map g))
include h
open_locale zero_object
/-- A functor which preserves exactness preserves zero morphisms. -/
lemma preserves_zero_morphisms_of_map_exact : L.preserves_zero_morphisms :=
begin
replace h := (h (exact_of_zero (𝟙 0) (𝟙 0))).w,
rw [L.map_id, category.comp_id] at h,
exact preserves_zero_morphisms_of_map_zero_object (id_zero_equiv_iso_zero _ h),
end
/-- A functor which preserves exactness preserves monomorphisms. -/
lemma preserves_monomorphisms_of_map_exact : L.preserves_monomorphisms :=
{ preserves := λ X Y f hf,
begin
letI := preserves_zero_morphisms_of_map_exact L h,
apply ((tfae_mono (L.obj 0) (L.map f)).out 2 0).mp,
rw ←L.map_zero,
exact h (((tfae_mono 0 f).out 0 2).mp hf)
end }
/-- A functor which preserves exactness preserves epimorphisms. -/
lemma preserves_epimorphisms_of_map_exact : L.preserves_epimorphisms :=
{ preserves := λ X Y f hf,
begin
letI := preserves_zero_morphisms_of_map_exact L h,
apply ((tfae_epi (L.obj 0) (L.map f)).out 2 0).mp,
rw ←L.map_zero,
exact h (((tfae_epi 0 f).out 0 2).mp hf)
end }
/-- A functor which preserves exactness preserves kernels. -/
def preserves_kernels_of_map_exact (X Y : A) (f : X ⟶ Y) :
preserves_limit (parallel_pair f 0) L :=
{ preserves := λ c ic,
begin
letI := preserves_zero_morphisms_of_map_exact L h,
letI := preserves_monomorphisms_of_map_exact L h,
letI := mono_of_is_limit_fork ic,
have hf := (is_limit_map_cone_fork_equiv' L (kernel_fork.condition c)).symm
(is_limit_of_exact_of_mono (L.map (fork.ι c)) (L.map f)
(h (exact_of_is_kernel (fork.ι c) f (kernel_fork.condition c)
(ic.of_iso_limit (iso_of_ι _))))),
exact hf.of_iso_limit ((cones.functoriality _ L).map_iso (iso_of_ι _).symm),
end }
/-- A functor which preserves exactness preserves zero cokernels. -/
def preserves_cokernels_of_map_exact (X Y : A) (f : X ⟶ Y) :
preserves_colimit (parallel_pair f 0) L :=
{ preserves := λ c ic,
begin
letI := preserves_zero_morphisms_of_map_exact L h,
letI := preserves_epimorphisms_of_map_exact L h,
letI := epi_of_is_colimit_cofork ic,
have hf := (is_colimit_map_cocone_cofork_equiv' L (cokernel_cofork.condition c)).symm
(is_colimit_of_exact_of_epi (L.map f) (L.map (cofork.π c))
(h (exact_of_is_cokernel f (cofork.π c) (cokernel_cofork.condition c)
(ic.of_iso_colimit (iso_of_π _))))),
exact hf.of_iso_colimit ((cocones.functoriality _ L).map_iso (iso_of_π _).symm),
end }
/-- A functor which preserves exactness is left exact, i.e. preserves finite limits.
This is part of the inverse implication to `functor.map_exact`. -/
def preserves_finite_limits_of_map_exact : preserves_finite_limits L :=
begin
letI := preserves_zero_morphisms_of_map_exact L h,
letI := preserves_kernels_of_map_exact L h,
apply preserves_finite_limits_of_preserves_kernels,
end
/-- A functor which preserves exactness is right exact, i.e. preserves finite colimits.
This is part of the inverse implication to `functor.map_exact`. -/
def preserves_finite_colimits_of_map_exact : preserves_finite_colimits L :=
begin
letI := preserves_zero_morphisms_of_map_exact L h,
letI := preserves_cokernels_of_map_exact L h,
apply preserves_finite_colimits_of_preserves_cokernels,
end
end
section
/-- A functor preserving zero morphisms, monos, and cokernels preserves finite limits. -/
def preserves_finite_limits_of_preserves_monos_and_cokernels
[preserves_zero_morphisms L] [preserves_monomorphisms L]
[∀ {X Y} (f : X ⟶ Y), preserves_colimit (parallel_pair f 0) L] : preserves_finite_limits L :=
begin
apply preserves_finite_limits_of_map_exact,
intros X Y Z f g h,
rw [← abelian.coimage.fac g, L.map_comp, exact_comp_mono_iff],
exact exact_of_is_cokernel _ _ _
(is_colimit_cofork_map_of_is_colimit' L _ (is_colimit_coimage f g h))
end
/-- A functor preserving zero morphisms, epis, and kernels preserves finite colimits. -/
def preserves_finite_colimits_of_preserves_epis_and_kernels
[preserves_zero_morphisms L] [preserves_epimorphisms L]
[∀ {X Y} (f : X ⟶ Y), preserves_limit (parallel_pair f 0) L] : preserves_finite_colimits L :=
begin
apply preserves_finite_colimits_of_map_exact,
intros X Y Z f g h,
rw [← abelian.image.fac f, L.map_comp, exact_epi_comp_iff],
exact exact_of_is_kernel _ _ _ (is_limit_fork_map_of_is_limit' L _ (is_limit_image f g h))
end
end
end functor
end category_theory
|
b9b49221a8420299923aec9712312eaa3d85cc21 | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/group_theory/specific_groups/alternating.lean | 6ea1d58ef8edf01363bc356361ecd4453c928a36 | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,515 | lean | /-
Copyright (c) 2021 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import group_theory.perm.cycle_type
/-!
# Alternating Groups
The alternating group on a finite type `α` is the subgroup of the permutation group `perm α`
consisting of the even permutations.
## Main definitions
* `alternating_group α` is the alternating group on `α`, defined as a `subgroup (perm α)`.
## Main results
* `two_mul_card_alternating_group` shows that the alternating group is half as large as
the permutation group it is a subgroup of.
* `closure_three_cycles_eq_alternating` shows that the alternating group is
generated by three-cycles.
## Tags
alternating group permutation
## TODO
* Show that `alternating_group α` is simple if and only if `fintype.card α ≠ 4`.
-/
open equiv equiv.perm subgroup fintype
variables (α : Type*) [fintype α] [decidable_eq α]
/-- The alternating group on a finite type, realized as a subgroup of `equiv.perm`.
For $A_n$, use `alternating_group (fin n)`. -/
@[derive fintype] def alternating_group : subgroup (perm α) :=
sign.ker
instance [subsingleton α] : unique (alternating_group α) :=
⟨⟨1⟩, λ ⟨p, hp⟩, subtype.eq (subsingleton.elim p _)⟩
variables {α}
lemma alternating_group_eq_sign_ker : alternating_group α = sign.ker := rfl
namespace equiv.perm
@[simp]
lemma mem_alternating_group {f : perm α} :
f ∈ alternating_group α ↔ sign f = 1 :=
sign.mem_ker
lemma prod_list_swap_mem_alternating_group_iff_even_length {l : list (perm α)}
(hl : ∀ g ∈ l, is_swap g) :
l.prod ∈ alternating_group α ↔ even l.length :=
begin
rw [mem_alternating_group, sign_prod_list_swap hl, ← units.coe_eq_one, units.coe_pow,
units.coe_neg_one, nat.neg_one_pow_eq_one_iff_even],
dec_trivial
end
end equiv.perm
lemma two_mul_card_alternating_group [nontrivial α] :
2 * card (alternating_group α) = card (perm α) :=
begin
let := (quotient_group.quotient_ker_equiv_of_surjective _ (sign_surjective α)).to_equiv,
rw [←fintype.card_units_int, ←fintype.card_congr this],
exact (subgroup.card_eq_card_quotient_mul_card_subgroup _).symm,
end
instance alternating_group_normal : (alternating_group α).normal := sign.normal_ker
namespace equiv.perm
@[simp]
theorem closure_three_cycles_eq_alternating :
closure {σ : perm α | is_three_cycle σ} = alternating_group α :=
closure_eq_of_le _ (λ σ hσ, mem_alternating_group.2 hσ.sign) $ λ σ hσ, begin
suffices hind : ∀ (n : ℕ) (l : list (perm α)) (hl : ∀ g, g ∈ l → is_swap g)
(hn : l.length = 2 * n), l.prod ∈ closure {σ : perm α | is_three_cycle σ},
{ obtain ⟨l, rfl, hl⟩ := trunc_swap_factors σ,
obtain ⟨n, hn⟩ := (prod_list_swap_mem_alternating_group_iff_even_length hl).1 hσ,
exact hind n l hl hn },
intro n,
induction n with n ih; intros l hl hn,
{ simp [list.length_eq_zero.1 hn, one_mem] },
rw [nat.mul_succ] at hn,
obtain ⟨a, l, rfl⟩ := l.exists_of_length_succ hn,
rw [list.length_cons, nat.succ_inj'] at hn,
obtain ⟨b, l, rfl⟩ := l.exists_of_length_succ hn,
rw [list.prod_cons, list.prod_cons, ← mul_assoc],
rw [list.length_cons, nat.succ_inj'] at hn,
exact mul_mem _ (is_swap.mul_mem_closure_three_cycles (hl a (list.mem_cons_self a _))
(hl b (list.mem_cons_of_mem a (l.mem_cons_self b))))
(ih _ (λ g hg, hl g (list.mem_cons_of_mem _ (list.mem_cons_of_mem _ hg))) hn),
end
end equiv.perm
|
44574ebd4c0fc79c680406a9d5547a301039b5a4 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/data/nat/choose/dvd.lean | a58c180b9b8dbb0218ab7bf77f1c07eee892f750 | [
"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,224 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Patrick Stevens
-/
import data.nat.choose.basic
import data.nat.prime
/-!
# Divisibility properties of binomial coefficients
-/
namespace nat
namespace prime
open_locale nat
lemma dvd_choose_add {p a b : ℕ} (hap : a < p) (hbp : b < p) (h : p ≤ a + b)
(hp : prime p) : p ∣ choose (a + b) a :=
have h₁ : p ∣ (a + b)!, from hp.dvd_factorial.2 h,
have h₂ : ¬p ∣ a!, from mt hp.dvd_factorial.1 (not_le_of_gt hap),
have h₃ : ¬p ∣ b!, from mt hp.dvd_factorial.1 (not_le_of_gt hbp),
by
rw [← choose_mul_factorial_mul_factorial (le.intro rfl), mul_assoc, hp.dvd_mul, hp.dvd_mul,
nat.add_sub_cancel_left a b] at h₁;
exact h₁.resolve_right (not_or_distrib.2 ⟨h₂, h₃⟩)
lemma dvd_choose_self {p k : ℕ} (hk : 0 < k) (hkp : k < p) (hp : prime p) :
p ∣ choose p k :=
begin
have r : k + (p - k) = p,
by rw [← nat.add_sub_assoc (nat.le_of_lt hkp) k, nat.add_sub_cancel_left],
have e : p ∣ choose (k + (p - k)) k,
by exact dvd_choose_add hkp (sub_lt (lt.trans hk hkp) hk) (by rw r) hp,
rwa r at e,
end
end prime
end nat
|
ee2c98c21b03318dcf027fe22c523823220d1df6 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/empty.lean | b4948f6665890790fbe725018ad24a2a003f368c | [
"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 | 190 | lean | import logic
open inhabited nonempty classical
noncomputable definition v1 : Prop := epsilon (λ x, true)
inductive Empty : Type
noncomputable definition v2 : Empty := epsilon (λ x, true)
|
8f8ab102297b36efa7ea02f28693e101b7b49515 | 12dabd587ce2621d9a4eff9f16e354d02e206c8e | /world02/level04.lean | c136bb204923bdd3a741b83255bb8c241ba1fb0b | [] | no_license | abdelq/natural-number-game | a1b5b8f1d52625a7addcefc97c966d3f06a48263 | bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2 | refs/heads/master | 1,668,606,478,691 | 1,594,175,058,000 | 1,594,175,058,000 | 278,673,209 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 152 | lean | lemma add_comm (a b : mynat) : a + b = b + a :=
begin
induction a with h hd,
rw zero_add,
rw add_zero,
refl,
rw succ_add,
rw hd,
rw add_succ,
refl,
end
|
a8948e8df6e545be32f5fa7215998551077e70da | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/topology/algebra/ring.lean | 7863dd19687cbe1ec4e54c26aceb08a2b9fd6f59 | [
"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 | 13,178 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes Hölzl
-/
import algebra.ring.prod
import ring_theory.ideal.quotient
import ring_theory.subring
import topology.algebra.group
/-!
# Topological (semi)rings
A topological (semi)ring is a (semi)ring equipped with a topology such that all operations are
continuous. Besides this definition, this file proves that the topological closure of a subring
(resp. an ideal) is a subring (resp. an ideal) and defines products and quotients
of topological (semi)rings.
## Main Results
- `subring.topological_closure`/`subsemiring.topological_closure`: the topological closure of a
`subring`/`subsemiring` is itself a `sub(semi)ring`.
- `prod.topological_ring`/`prod.topological_ring`: The product of two topological (semi)rings.
- `pi.topological_ring`/`pi.topological_ring`: The arbitrary product of topological (semi)rings.
- `ideal.closure`: The closure of an ideal is an ideal.
- `topological_ring_quotient`: The quotient of a topological ring by an ideal is a topological ring.
-/
open classical set filter topological_space function
open_locale classical topological_space filter
section topological_ring
variables (α : Type*)
/-- A topological (semi)ring is a (semi)ring `R` where addition and multiplication are continuous.
If `R` is a ring, then negation is automatically continuous, as it is multiplication with `-1`. -/
class topological_ring [topological_space α] [semiring α]
extends has_continuous_add α, has_continuous_mul α : Prop
section
variables {α} [topological_space α] [semiring α] [topological_ring α]
/-- The (topological-space) closure of a subsemiring of a topological semiring is
itself a subsemiring. -/
def subsemiring.topological_closure (s : subsemiring α) : subsemiring α :=
{ carrier := closure (s : set α),
..(s.to_submonoid.topological_closure),
..(s.to_add_submonoid.topological_closure ) }
@[simp] lemma subsemiring.topological_closure_coe (s : subsemiring α) :
(s.topological_closure : set α) = closure (s : set α) :=
rfl
instance subsemiring.topological_closure_topological_ring (s : subsemiring α) :
topological_ring (s.topological_closure) :=
{ ..s.to_add_submonoid.topological_closure_has_continuous_add,
..s.to_submonoid.topological_closure_has_continuous_mul }
lemma subsemiring.subring_topological_closure (s : subsemiring α) :
s ≤ s.topological_closure :=
subset_closure
lemma subsemiring.is_closed_topological_closure (s : subsemiring α) :
is_closed (s.topological_closure : set α) :=
by convert is_closed_closure
lemma subsemiring.topological_closure_minimal
(s : subsemiring α) {t : subsemiring α} (h : s ≤ t) (ht : is_closed (t : set α)) :
s.topological_closure ≤ t :=
closure_minimal h ht
/-- The product topology on the cartesian product of two topological semirings
makes the product into a topological semiring. -/
instance {β : Type*} [semiring β] [topological_space β] [topological_ring β] :
topological_ring (α × β) := {}
instance {β : Type*} {C : β → Type*} [∀ b, topological_space (C b)]
[Π b, semiring (C b)] [Π b, topological_ring (C b)] : topological_ring (Π b, C b) := {}
end
section
variables {R : Type*} [ring R] [topological_space R]
lemma topological_ring.of_add_group_of_nhds_zero [topological_add_group R]
(hmul : tendsto (uncurry ((*) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) $ 𝓝 0)
(hmul_left : ∀ (x₀ : R), tendsto (λ x : R, x₀ * x) (𝓝 0) $ 𝓝 0)
(hmul_right : ∀ (x₀ : R), tendsto (λ x : R, x * x₀) (𝓝 0) $ 𝓝 0) : topological_ring R :=
begin
refine {..‹topological_add_group R›, ..},
have hleft : ∀ x₀ : R, 𝓝 x₀ = map (λ x, x₀ + x) (𝓝 0), by simp,
have hadd : tendsto (uncurry ((+) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) (𝓝 0),
{ rw ← nhds_prod_eq,
convert continuous_add.tendsto ((0 : R), (0 : R)),
rw zero_add },
rw continuous_iff_continuous_at,
rintro ⟨x₀, y₀⟩,
rw [continuous_at, nhds_prod_eq, hleft x₀, hleft y₀, hleft (x₀*y₀), filter.prod_map_map_eq,
tendsto_map'_iff],
suffices :
tendsto ((λ (x : R), x + x₀ * y₀) ∘ (λ (p : R × R), p.1 + p.2) ∘
(λ (p : R × R), (p.1*y₀ + x₀*p.2, p.1*p.2)))
((𝓝 0) ×ᶠ (𝓝 0)) (map (λ (x : R), x + x₀ * y₀) $ 𝓝 0),
{ convert this using 1,
{ ext, simp only [comp_app, mul_add, add_mul], abel },
{ simp only [add_comm] } },
refine tendsto_map.comp (hadd.comp (tendsto.prod_mk _ hmul)),
exact hadd.comp (((hmul_right y₀).comp tendsto_fst).prod_mk ((hmul_left x₀).comp tendsto_snd))
end
lemma topological_ring.of_nhds_zero
(hadd : tendsto (uncurry ((+) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) $ 𝓝 0)
(hneg : tendsto (λ x, -x : R → R) (𝓝 0) (𝓝 0))
(hmul : tendsto (uncurry ((*) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) $ 𝓝 0)
(hmul_left : ∀ (x₀ : R), tendsto (λ x : R, x₀ * x) (𝓝 0) $ 𝓝 0)
(hmul_right : ∀ (x₀ : R), tendsto (λ x : R, x * x₀) (𝓝 0) $ 𝓝 0)
(hleft : ∀ x₀ : R, 𝓝 x₀ = map (λ x, x₀ + x) (𝓝 0)) : topological_ring R :=
begin
haveI := topological_add_group.of_comm_of_nhds_zero hadd hneg hleft,
exact topological_ring.of_add_group_of_nhds_zero hmul hmul_left hmul_right
end
end
variables {α} [ring α] [topological_space α] [topological_ring α]
@[priority 100] -- See note [lower instance priority]
instance topological_ring.to_topological_add_group : topological_add_group α :=
{ continuous_add := continuous_add,
continuous_neg := by simpa only [neg_one_mul, id.def] using
(@continuous_const α α _ _ (-1)).mul continuous_id }
/-- In a topological ring, the left-multiplication `add_monoid_hom` is continuous. -/
lemma mul_left_continuous (x : α) : continuous (add_monoid_hom.mul_left x) :=
continuous_const.mul continuous_id
/-- In a topological ring, the right-multiplication `add_monoid_hom` is continuous. -/
lemma mul_right_continuous (x : α) : continuous (add_monoid_hom.mul_right x) :=
continuous_id.mul continuous_const
/-- The (topological-space) closure of a subring of a topological semiring is
itself a subring. -/
def subring.topological_closure (S : subring α) : subring α :=
{ carrier := closure (S : set α),
..S.to_submonoid.topological_closure,
..S.to_add_subgroup.topological_closure }
instance subring.topological_closure_topological_ring (s : subring α) :
topological_ring (s.topological_closure) :=
{ ..s.to_add_subgroup.topological_closure_topological_add_group,
..s.to_submonoid.topological_closure_has_continuous_mul }
lemma subring.subring_topological_closure (s : subring α) :
s ≤ s.topological_closure := subset_closure
lemma subring.is_closed_topological_closure (s : subring α) :
is_closed (s.topological_closure : set α) := by convert is_closed_closure
lemma subring.topological_closure_minimal
(s : subring α) {t : subring α} (h : s ≤ t) (ht : is_closed (t : set α)) :
s.topological_closure ≤ t := closure_minimal h ht
end topological_ring
section topological_comm_ring
variables {α : Type*} [topological_space α] [comm_ring α] [topological_ring α]
/-- The closure of an ideal in a topological ring as an ideal. -/
def ideal.closure (S : ideal α) : ideal α :=
{ carrier := closure S,
smul_mem' := λ c x hx, map_mem_closure (mul_left_continuous _) hx $ λ a, S.mul_mem_left c,
..(add_submonoid.topological_closure S.to_add_submonoid) }
@[simp] lemma ideal.coe_closure (S : ideal α) : (S.closure : set α) = closure S := rfl
end topological_comm_ring
section topological_ring
variables {α : Type*} [topological_space α] [comm_ring α] (N : ideal α)
open ideal.quotient
instance topological_ring_quotient_topology : topological_space N.quotient :=
by dunfold ideal.quotient submodule.quotient; apply_instance
-- note for the reader: in the following, `mk` is `ideal.quotient.mk`, the canonical map `R → R/I`.
variable [topological_ring α]
lemma quotient_ring.is_open_map_coe : is_open_map (mk N) :=
begin
intros s s_op,
change is_open (mk N ⁻¹' (mk N '' s)),
rw quotient_ring_saturate,
exact is_open_Union (λ ⟨n, _⟩, is_open_map_add_left n s s_op)
end
lemma quotient_ring.quotient_map_coe_coe : quotient_map (λ p : α × α, (mk N p.1, mk N p.2)) :=
is_open_map.to_quotient_map
((quotient_ring.is_open_map_coe N).prod (quotient_ring.is_open_map_coe N))
((continuous_quot_mk.comp continuous_fst).prod_mk (continuous_quot_mk.comp continuous_snd))
(by rintro ⟨⟨x⟩, ⟨y⟩⟩; exact ⟨(x, y), rfl⟩)
instance topological_ring_quotient : topological_ring N.quotient :=
{ continuous_add :=
have cont : continuous (mk N ∘ (λ (p : α × α), p.fst + p.snd)) :=
continuous_quot_mk.comp continuous_add,
(quotient_map.continuous_iff (quotient_ring.quotient_map_coe_coe N)).mpr cont,
continuous_mul :=
have cont : continuous (mk N ∘ (λ (p : α × α), p.fst * p.snd)) :=
continuous_quot_mk.comp continuous_mul,
(quotient_map.continuous_iff (quotient_ring.quotient_map_coe_coe N)).mpr cont }
end topological_ring
/-!
### Lattice of ring topologies
We define a type class `ring_topology α` which endows a ring `α` with a topology such that all ring
operations are continuous.
Ring topologies on a fixed ring `α` are ordered, by reverse inclusion. They form a complete lattice,
with `⊥` the discrete topology and `⊤` the indiscrete topology.
Any function `f : α → β` induces `coinduced f : topological_space α → ring_topology β`. -/
universes u v
/-- A ring topology on a ring `α` is a topology for which addition, negation and multiplication
are continuous. -/
@[ext]
structure ring_topology (α : Type u) [ring α]
extends topological_space α, topological_ring α : Type u
namespace ring_topology
variables {α : Type*} [ring α]
instance inhabited {α : Type u} [ring α] : inhabited (ring_topology α) :=
⟨{to_topological_space := ⊤,
continuous_add := continuous_top,
continuous_mul := continuous_top}⟩
@[ext]
lemma ext' {f g : ring_topology α} (h : f.is_open = g.is_open) : f = g :=
by { ext, rw h }
/-- The ordering on ring topologies on the ring `α`.
`t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/
instance : partial_order (ring_topology α) :=
partial_order.lift ring_topology.to_topological_space $ ext
local notation `cont` := @continuous _ _
private def def_Inf (S : set (ring_topology α)) : ring_topology α :=
let Inf_S' := Inf (to_topological_space '' S) in
{ to_topological_space := Inf_S',
continuous_add :=
begin
apply continuous_Inf_rng,
rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI,
have h := continuous_Inf_dom (set.mem_image_of_mem to_topological_space haS) continuous_id,
have h_continuous_id := @continuous.prod_map _ _ _ _ t t Inf_S' Inf_S' _ _ h h,
have h_continuous_add : cont (id _) t (λ (p : α × α), p.fst + p.snd) := continuous_add,
exact @continuous.comp _ _ _ (id _) (id _) t _ _ h_continuous_add h_continuous_id,
end,
continuous_mul :=
begin
apply continuous_Inf_rng,
rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI,
have h := continuous_Inf_dom (set.mem_image_of_mem to_topological_space haS) continuous_id,
have h_continuous_id := @continuous.prod_map _ _ _ _ t t Inf_S' Inf_S' _ _ h h,
have h_continuous_mul : cont (id _) t (λ (p : α × α), p.fst * p.snd) := continuous_mul,
exact @continuous.comp _ _ _ (id _) (id _) t _ _ h_continuous_mul h_continuous_id,
end }
/-- Ring topologies on `α` form a complete lattice, with `⊥` the discrete topology and `⊤` the
indiscrete topology.
The infimum of a collection of ring topologies is the topology generated by all their open sets
(which is a ring topology).
The supremum of two ring topologies `s` and `t` is the infimum of the family of all ring topologies
contained in the intersection of `s` and `t`. -/
instance : complete_semilattice_Inf (ring_topology α) :=
{ Inf := def_Inf,
Inf_le := λ S a haS, by { apply topological_space.complete_lattice.Inf_le, use [a, ⟨ haS, rfl⟩] },
le_Inf :=
begin
intros S a hab,
apply topological_space.complete_lattice.le_Inf,
rintros _ ⟨b, hbS, rfl⟩,
exact hab b hbS,
end,
..ring_topology.partial_order }
instance : complete_lattice (ring_topology α) :=
complete_lattice_of_complete_semilattice_Inf _
/-- Given `f : α → β` and a topology on `α`, the coinduced ring topology on `β` is the finest
topology such that `f` is continuous and `β` is a topological ring. -/
def coinduced {α β : Type*} [t : topological_space α] [ring β] (f : α → β) :
ring_topology β :=
Inf {b : ring_topology β | (topological_space.coinduced f t) ≤ b.to_topological_space}
lemma coinduced_continuous {α β : Type*} [t : topological_space α] [ring β] (f : α → β) :
cont t (coinduced f).to_topological_space f :=
begin
rw continuous_iff_coinduced_le,
refine le_Inf _,
rintros _ ⟨t', ht', rfl⟩,
exact ht',
end
end ring_topology
|
49971b99a9bde5420ba1ede9af48ad3c78a7ad51 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/set/intervals/proj_Icc.lean | 7a4cf4734a9323bbbbc321471ab8fdf1e436a7e0 | [
"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 | 4,363 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov, Patrick Massot
-/
import data.set.intervals.basic
/-!
# Projection of a line onto a closed interval
Given a linearly ordered type `α`, in this file we define
* `set.proj_Icc (a b : α) (h : a ≤ b)` to be the map `α → [a, b]` sending `(-∞, a]` to `a`, `[b, ∞)`
to `b`, and each point `x ∈ [a, b]` to itself;
* `set.Icc_extend {a b : α} (h : a ≤ b) (f : Icc a b → β)` to be the extension of `f` to `α` defined
as `f ∘ proj_Icc a b h`.
We also prove some trivial properties of these maps.
-/
variables {α β : Type*} [linear_order α]
open function
namespace set
/-- Projection of `α` to the closed interval `[a, b]`. -/
def proj_Icc (a b : α) (h : a ≤ b) (x : α) : Icc a b :=
⟨max a (min b x), le_max_left _ _, max_le h (min_le_left _ _)⟩
variables {a b : α} (h : a ≤ b) {x : α}
lemma proj_Icc_of_le_left (hx : x ≤ a) : proj_Icc a b h x = ⟨a, left_mem_Icc.2 h⟩ :=
by simp [proj_Icc, hx, hx.trans h]
@[simp] lemma proj_Icc_left : proj_Icc a b h a = ⟨a, left_mem_Icc.2 h⟩ :=
proj_Icc_of_le_left h le_rfl
lemma proj_Icc_of_right_le (hx : b ≤ x) : proj_Icc a b h x = ⟨b, right_mem_Icc.2 h⟩ :=
by simp [proj_Icc, hx, h]
@[simp] lemma proj_Icc_right : proj_Icc a b h b = ⟨b, right_mem_Icc.2 h⟩ :=
proj_Icc_of_right_le h le_rfl
lemma proj_Icc_eq_left (h : a < b) : proj_Icc a b h.le x = ⟨a, left_mem_Icc.mpr h.le⟩ ↔ x ≤ a :=
begin
refine ⟨λ h', _, proj_Icc_of_le_left _⟩,
simp_rw [subtype.ext_iff_val, proj_Icc, max_eq_left_iff, min_le_iff, h.not_le, false_or] at h',
exact h'
end
lemma proj_Icc_eq_right (h : a < b) : proj_Icc a b h.le x = ⟨b, right_mem_Icc.mpr h.le⟩ ↔ b ≤ x :=
begin
refine ⟨λ h', _, proj_Icc_of_right_le _⟩,
simp_rw [subtype.ext_iff_val, proj_Icc] at h',
have := ((max_choice _ _).resolve_left (by simp [h.ne', h'])).symm.trans h',
exact min_eq_left_iff.mp this
end
lemma proj_Icc_of_mem (hx : x ∈ Icc a b) : proj_Icc a b h x = ⟨x, hx⟩ :=
by simp [proj_Icc, hx.1, hx.2]
@[simp] lemma proj_Icc_coe (x : Icc a b) : proj_Icc a b h x = x :=
by { cases x, apply proj_Icc_of_mem }
lemma proj_Icc_surj_on : surj_on (proj_Icc a b h) (Icc a b) univ :=
λ x _, ⟨x, x.2, proj_Icc_coe h x⟩
lemma proj_Icc_surjective : surjective (proj_Icc a b h) :=
λ x, ⟨x, proj_Icc_coe h x⟩
@[simp] lemma range_proj_Icc : range (proj_Icc a b h) = univ :=
(proj_Icc_surjective h).range_eq
lemma monotone_proj_Icc : monotone (proj_Icc a b h) :=
λ x y hxy, max_le_max le_rfl $ min_le_min le_rfl hxy
lemma strict_mono_on_proj_Icc : strict_mono_on (proj_Icc a b h) (Icc a b) :=
λ x hx y hy hxy, by simpa only [proj_Icc_of_mem, hx, hy]
/-- Extend a function `[a, b] → β` to a map `α → β`. -/
def Icc_extend {a b : α} (h : a ≤ b) (f : Icc a b → β) : α → β :=
f ∘ proj_Icc a b h
@[simp] lemma Icc_extend_range (f : Icc a b → β) :
range (Icc_extend h f) = range f :=
by simp only [Icc_extend, range_comp f, range_proj_Icc, range_id']
lemma Icc_extend_of_le_left (f : Icc a b → β) (hx : x ≤ a) :
Icc_extend h f x = f ⟨a, left_mem_Icc.2 h⟩ :=
congr_arg f $ proj_Icc_of_le_left h hx
@[simp] lemma Icc_extend_left (f : Icc a b → β) :
Icc_extend h f a = f ⟨a, left_mem_Icc.2 h⟩ :=
Icc_extend_of_le_left h f le_rfl
lemma Icc_extend_of_right_le (f : Icc a b → β) (hx : b ≤ x) :
Icc_extend h f x = f ⟨b, right_mem_Icc.2 h⟩ :=
congr_arg f $ proj_Icc_of_right_le h hx
@[simp] lemma Icc_extend_right (f : Icc a b → β) :
Icc_extend h f b = f ⟨b, right_mem_Icc.2 h⟩ :=
Icc_extend_of_right_le h f le_rfl
lemma Icc_extend_of_mem (f : Icc a b → β) (hx : x ∈ Icc a b) :
Icc_extend h f x = f ⟨x, hx⟩ :=
congr_arg f $ proj_Icc_of_mem h hx
@[simp] lemma Icc_extend_coe (f : Icc a b → β) (x : Icc a b) :
Icc_extend h f x = f x :=
congr_arg f $ proj_Icc_coe h x
end set
open set
variables [preorder β] {a b : α} (h : a ≤ b) {f : Icc a b → β}
lemma monotone.Icc_extend (hf : monotone f) : monotone (Icc_extend h f) :=
hf.comp $ monotone_proj_Icc h
lemma strict_mono.strict_mono_on_Icc_extend (hf : strict_mono f) :
strict_mono_on (Icc_extend h f) (Icc a b) :=
hf.comp_strict_mono_on (strict_mono_on_proj_Icc h)
|
983a4072a6f17c8f6a6beb4ceeb94940afdcee6f | 94637389e03c919023691dcd05bd4411b1034aa5 | /src/inClassNotes/final/env.lean | a4080b65fdab4e38ace53a6ea3fdf61149d00fa6 | [] | no_license | kevinsullivan/complogic-s21 | 7c4eef2105abad899e46502270d9829d913e8afc | 99039501b770248c8ceb39890be5dfe129dc1082 | refs/heads/master | 1,682,985,669,944 | 1,621,126,241,000 | 1,621,126,241,000 | 335,706,272 | 0 | 38 | null | 1,618,325,669,000 | 1,612,374,118,000 | Lean | UTF-8 | Lean | false | false | 248 | lean | import .var
structure env :=
(bool_var_interp : var bool → bool)
(nat_var_interp : var nat → nat)
-- Collect init environments for each of the supported types
def init_env [a: has_var bool] [b: has_var nat] : env :=
⟨ a.init, b.init ⟩
|
26da93c9b47448ac93535a398a25fce2a9dc2c5b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/matrix/reindex.lean | 10513e866f5521bda96399febc87439745b7f865 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 5,638 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen
-/
import linear_algebra.matrix.determinant
/-!
# Changing the index type of a matrix
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file concerns the map `matrix.reindex`, mapping a `m` by `n` matrix
to an `m'` by `n'` matrix, as long as `m ≃ m'` and `n ≃ n'`.
## Main definitions
* `matrix.reindex_linear_equiv R A`: `matrix.reindex` is an `R`-linear equivalence between
`A`-matrices.
* `matrix.reindex_alg_equiv R`: `matrix.reindex` is an `R`-algebra equivalence between `R`-matrices.
## Tags
matrix, reindex
-/
namespace matrix
open equiv
open_locale matrix
variables {l m n o : Type*} {l' m' n' o' : Type*} {m'' n'' : Type*}
variables (R A : Type*)
section add_comm_monoid
variables [semiring R] [add_comm_monoid A] [module R A]
/-- The natural map that reindexes a matrix's rows and columns with equivalent types,
`matrix.reindex`, is a linear equivalence. -/
def reindex_linear_equiv (eₘ : m ≃ m') (eₙ : n ≃ n') : matrix m n A ≃ₗ[R] matrix m' n' A :=
{ map_add' := λ _ _, rfl,
map_smul' := λ _ _, rfl,
..(reindex eₘ eₙ)}
@[simp] lemma reindex_linear_equiv_apply
(eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n A) :
reindex_linear_equiv R A eₘ eₙ M = reindex eₘ eₙ M :=
rfl
@[simp] lemma reindex_linear_equiv_symm (eₘ : m ≃ m') (eₙ : n ≃ n') :
(reindex_linear_equiv R A eₘ eₙ).symm = reindex_linear_equiv R A eₘ.symm eₙ.symm :=
rfl
@[simp] lemma reindex_linear_equiv_refl_refl :
reindex_linear_equiv R A (equiv.refl m) (equiv.refl n) = linear_equiv.refl R _ :=
linear_equiv.ext $ λ _, rfl
lemma reindex_linear_equiv_trans (e₁ : m ≃ m') (e₂ : n ≃ n') (e₁' : m' ≃ m'')
(e₂' : n' ≃ n'') : (reindex_linear_equiv R A e₁ e₂).trans (reindex_linear_equiv R A e₁' e₂') =
(reindex_linear_equiv R A (e₁.trans e₁') (e₂.trans e₂') : _ ≃ₗ[R] _) :=
by { ext, refl }
lemma reindex_linear_equiv_comp (e₁ : m ≃ m') (e₂ : n ≃ n') (e₁' : m' ≃ m'')
(e₂' : n' ≃ n'') :
(reindex_linear_equiv R A e₁' e₂') ∘ (reindex_linear_equiv R A e₁ e₂)
= reindex_linear_equiv R A (e₁.trans e₁') (e₂.trans e₂') :=
by { rw [← reindex_linear_equiv_trans], refl }
lemma reindex_linear_equiv_comp_apply (e₁ : m ≃ m') (e₂ : n ≃ n') (e₁' : m' ≃ m'')
(e₂' : n' ≃ n'') (M : matrix m n A) :
(reindex_linear_equiv R A e₁' e₂') (reindex_linear_equiv R A e₁ e₂ M) =
reindex_linear_equiv R A (e₁.trans e₁') (e₂.trans e₂') M :=
submatrix_submatrix _ _ _ _ _
lemma reindex_linear_equiv_one [decidable_eq m] [decidable_eq m'] [has_one A]
(e : m ≃ m') : (reindex_linear_equiv R A e e (1 : matrix m m A)) = 1 :=
submatrix_one_equiv e.symm
end add_comm_monoid
section semiring
variables [semiring R] [semiring A] [module R A]
lemma reindex_linear_equiv_mul [fintype n] [fintype n']
(eₘ : m ≃ m') (eₙ : n ≃ n') (eₒ : o ≃ o') (M : matrix m n A) (N : matrix n o A) :
reindex_linear_equiv R A eₘ eₙ M ⬝ reindex_linear_equiv R A eₙ eₒ N =
reindex_linear_equiv R A eₘ eₒ (M ⬝ N) :=
submatrix_mul_equiv M N _ _ _
lemma mul_reindex_linear_equiv_one [fintype n] [decidable_eq o] (e₁ : o ≃ n)
(e₂ : o ≃ n') (M : matrix m n A) : M.mul (reindex_linear_equiv R A e₁ e₂ 1) =
reindex_linear_equiv R A (equiv.refl m) (e₁.symm.trans e₂) M :=
by { haveI := fintype.of_equiv _ e₁.symm, exact mul_submatrix_one _ _ _ }
end semiring
section algebra
variables [comm_semiring R] [fintype n] [fintype m] [decidable_eq m] [decidable_eq n]
/--
For square matrices with coefficients in commutative semirings, the natural map that reindexes
a matrix's rows and columns with equivalent types, `matrix.reindex`, is an equivalence of algebras.
-/
def reindex_alg_equiv (e : m ≃ n) : matrix m m R ≃ₐ[R] matrix n n R :=
{ to_fun := reindex e e,
map_mul' := λ a b, (reindex_linear_equiv_mul R R e e e a b).symm,
commutes' := λ r, by simp [algebra_map, algebra.to_ring_hom, submatrix_smul],
..(reindex_linear_equiv R R e e) }
@[simp] lemma reindex_alg_equiv_apply (e : m ≃ n) (M : matrix m m R) :
reindex_alg_equiv R e M = reindex e e M :=
rfl
@[simp] lemma reindex_alg_equiv_symm (e : m ≃ n) :
(reindex_alg_equiv R e).symm = reindex_alg_equiv R e.symm :=
rfl
@[simp] lemma reindex_alg_equiv_refl : reindex_alg_equiv R (equiv.refl m) = alg_equiv.refl :=
alg_equiv.ext $ λ _, rfl
lemma reindex_alg_equiv_mul (e : m ≃ n) (M : matrix m m R) (N : matrix m m R) :
reindex_alg_equiv R e (M ⬝ N) = reindex_alg_equiv R e M ⬝ reindex_alg_equiv R e N :=
(reindex_alg_equiv R e).map_mul M N
end algebra
/-- Reindexing both indices along the same equivalence preserves the determinant.
For the `simp` version of this lemma, see `det_submatrix_equiv_self`.
-/
lemma det_reindex_linear_equiv_self [comm_ring R] [fintype m] [decidable_eq m]
[fintype n] [decidable_eq n] (e : m ≃ n) (M : matrix m m R) :
det (reindex_linear_equiv R R e e M) = det M :=
det_reindex_self e M
/-- Reindexing both indices along the same equivalence preserves the determinant.
For the `simp` version of this lemma, see `det_submatrix_equiv_self`.
-/
lemma det_reindex_alg_equiv [comm_ring R] [fintype m] [decidable_eq m] [fintype n] [decidable_eq n]
(e : m ≃ n) (A : matrix m m R) :
det (reindex_alg_equiv R e A) = det A :=
det_reindex_self e A
end matrix
|
dedc726006575f907566b13c724b853a46dcade5 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/topology/uniform_space/compact_separated.lean | 34a4694041207ca4c925ab2cbaeec768363e4b44 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,636 | lean | /-
Copyright (c) 2020 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.topology.uniform_space.separation
import Mathlib.PostPort
universes u_1 u_2 u_3
namespace Mathlib
/-!
# Compact separated uniform spaces
## Main statements
* `compact_space_uniformity`: On a separated compact uniform space, the topology determines the
uniform structure, entourages are exactly the neighborhoods of the diagonal.
* `uniform_space_of_compact_t2`: every compact T2 topological structure is induced by a uniform
structure. This uniform structure is described in the previous item.
* Heine-Cantor theorem: continuous functions on compact separated uniform spaces with values in
uniform spaces are automatically uniformly continuous. There are several variations, the main one
is `compact_space.uniform_continuous_of_continuous`.
## Implementation notes
The construction `uniform_space_of_compact_t2` is not declared as an instance, as it would badly
loop.
## tags
uniform space, uniform continuity, compact space
-/
/-!
### Uniformity on compact separated spaces
-/
/-- On a separated compact uniform space, the topology determines the uniform structure, entourages
are exactly the neighborhoods of the diagonal. -/
theorem compact_space_uniformity {α : Type u_1} [uniform_space α] [compact_space α] [separated_space α] : uniformity α = supr fun (x : α) => nhds (x, x) := sorry
theorem unique_uniformity_of_compact_t2 {α : Type u_1} [t : topological_space α] [compact_space α] [t2_space α] {u : uniform_space α} {u' : uniform_space α} (h : uniform_space.to_topological_space = t) (h' : uniform_space.to_topological_space = t) : u = u' := sorry
/-- The unique uniform structure inducing a given compact Hausdorff topological structure. -/
def uniform_space_of_compact_t2 {α : Type (max (max u_1 u_2 u_3) u_2)} [topological_space α] [compact_space α] [t2_space α] : uniform_space α :=
uniform_space.mk (uniform_space.core.mk (supr fun (x : α) => nhds (x, x)) sorry sorry sorry) sorry
/-!
### Heine-Cantor theorem
-/
/-- Heine-Cantor: a continuous function on a compact separated uniform space is uniformly
continuous. -/
theorem compact_space.uniform_continuous_of_continuous {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] [compact_space α] [separated_space α] {f : α → β} (h : continuous f) : uniform_continuous f := sorry
/-- Heine-Cantor: a continuous function on a compact separated set of a uniform space is
uniformly continuous. -/
theorem is_compact.uniform_continuous_on_of_continuous' {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] {s : set α} {f : α → β} (hs : is_compact s) (hs' : is_separated s) (hf : continuous_on f s) : uniform_continuous_on f s :=
eq.mpr (id (Eq._oldrec (Eq.refl (uniform_continuous_on f s)) (propext uniform_continuous_on_iff_restrict)))
(compact_space.uniform_continuous_of_continuous
(eq.mp (Eq._oldrec (Eq.refl (continuous_on f s)) (propext continuous_on_iff_continuous_restrict)) hf))
/-- Heine-Cantor: a continuous function on a compact set of a separated uniform space
is uniformly continuous. -/
theorem is_compact.uniform_continuous_on_of_continuous {α : Type u_1} {β : Type u_2} [uniform_space α] [uniform_space β] [separated_space α] {s : set α} {f : α → β} (hs : is_compact s) (hf : continuous_on f s) : uniform_continuous_on f s :=
is_compact.uniform_continuous_on_of_continuous' hs (is_separated_of_separated_space s) hf
|
f6dc26dbb1d56734c7585248eba2f9c02310dde1 | 3dc4623269159d02a444fe898d33e8c7e7e9461b | /.github/workflows/project_1_a_decrire/foncteur/import.lean | ad325a15f021c583963e5fc7ec4b84fa8589dd96 | [] | no_license | Or7ando/lean | cc003e6c41048eae7c34aa6bada51c9e9add9e66 | d41169cf4e416a0d42092fb6bdc14131cee9dd15 | refs/heads/master | 1,650,600,589,722 | 1,587,262,906,000 | 1,587,262,906,000 | 255,387,160 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 229 | lean | import tactic
import data.sum
def map_from_sum {A B C : Type} (f : A → C) (g : B → C) : (A ⊕ B) → C := by suggest
/- There are no applicable declarations
state:
A B C : Type,
f : A → C,
g : B → C
⊢ A ⊕ B → C -/ |
2097696ac0d8c08c32be9482f8a88b92e11c7d0c | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/ring_theory/polynomial/cyclotomic.lean | 659ee697e24d1407810488d768caccbc995283a5 | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 30,482 | lean | /-
Copyright (c) 2020 Riccardo Brasca. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Riccardo Brasca
-/
import field_theory.splitting_field
import ring_theory.roots_of_unity
import algebra.polynomial.big_operators
import number_theory.arithmetic_function
import data.polynomial.lifts
import analysis.complex.roots_of_unity
import field_theory.separable
/-!
# Cyclotomic polynomials.
For `n : ℕ` and an integral domain `R`, we define a modified version of the `n`-th cyclotomic
polynomial with coefficients in `R`, denoted `cyclotomic' n R`, as `∏ (X - μ)`, where `μ` varies
over the primitive `n`th roots of unity. If there is a primitive `n`th root of unity in `R` then
this the standard definition. We then define the standard cyclotomic polynomial `cyclotomic n R`
with coefficients in any ring `R`.
## Main definition
* `cyclotomic n R` : the `n`-th cyclotomic polynomial with coefficients in `R`.
## Main results
* `int_coeff_of_cycl` : If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K`
comes from a polynomial with integer coefficients.
* `deg_of_cyclotomic` : The degree of `cyclotomic n` is `totient n`.
* `prod_cyclotomic_eq_X_pow_sub_one` : `X ^ n - 1 = ∏ (cyclotomic i)`, where `i` divides `n`.
* `cyclotomic_eq_prod_X_pow_sub_one_pow_moebius` : The Möbius inversion formula for
`cyclotomic n R` over an abstract fraction field for `polynomial R`.
* `cyclotomic.irreducible` : `cyclotomic n ℤ` is irreducible.
## Implementation details
Our definition of `cyclotomic' n R` makes sense in any integral domain `R`, but the interesting
results hold if there is a primitive `n`-th root of unity in `R`. In particular, our definition is
not the standard one unless there is a primitive `n`th root of unity in `R`. For example,
`cyclotomic' 3 ℤ = 1`, since there are no primitive cube roots of unity in `ℤ`. The main example is
`R = ℂ`, we decided to work in general since the difficulties are essentially the same.
To get the standard cyclotomic polynomials, we use `int_coeff_of_cycl`, with `R = ℂ`, to get a
polynomial with integer coefficients and then we map it to `polynomial R`, for any ring `R`.
To prove `cyclotomic.irreducible`, the irreducibility of `cyclotomic n ℤ`, we show in
`cyclotomic_eq_minpoly` that `cyclotomic n ℤ` is the minimal polynomial of any `n`-th primitive root
of unity `μ : K`, where `K` is a field of characteristic `0`.
-/
open_locale classical big_operators
noncomputable theory
universe u
namespace polynomial
section cyclotomic'
section integral_domain
variables {R : Type*} [comm_ring R] [integral_domain R]
/-- The modified `n`-th cyclotomic polynomial with coefficients in `R`, it is the usual cyclotomic
polynomial if there is a primitive `n`-th root of unity in `R`. -/
def cyclotomic' (n : ℕ) (R : Type*) [comm_ring R] [integral_domain R] : polynomial R :=
∏ μ in primitive_roots n R, (X - C μ)
/-- The zeroth modified cyclotomic polyomial is `1`. -/
@[simp] lemma cyclotomic'_zero
(R : Type*) [comm_ring R] [integral_domain R] : cyclotomic' 0 R = 1 :=
by simp only [cyclotomic', finset.prod_empty, is_primitive_root.primitive_roots_zero]
/-- The first modified cyclotomic polyomial is `X - 1`. -/
@[simp] lemma cyclotomic'_one
(R : Type*) [comm_ring R] [integral_domain R] : cyclotomic' 1 R = X - 1 :=
begin
simp only [cyclotomic', finset.prod_singleton, ring_hom.map_one,
is_primitive_root.primitive_roots_one]
end
/-- The second modified cyclotomic polyomial is `X + 1` if the characteristic of `R` is not `2`. -/
@[simp] lemma cyclotomic'_two
(R : Type*) [comm_ring R] [integral_domain R] (p : ℕ) [char_p R p] (hp : p ≠ 2) :
cyclotomic' 2 R = X + 1 :=
begin
rw [cyclotomic'],
have prim_root_two : primitive_roots 2 R = {(-1 : R)},
{ apply finset.eq_singleton_iff_unique_mem.2,
split,
{ simp only [is_primitive_root.neg_one p hp, nat.succ_pos', mem_primitive_roots] },
{ intros x hx,
rw [mem_primitive_roots zero_lt_two] at hx,
exact is_primitive_root.eq_neg_one_of_two_right hx } },
simp only [prim_root_two, finset.prod_singleton, ring_hom.map_neg, ring_hom.map_one,
sub_neg_eq_add]
end
/-- `cyclotomic' n R` is monic. -/
lemma cyclotomic'.monic
(n : ℕ) (R : Type*) [comm_ring R] [integral_domain R] : (cyclotomic' n R).monic :=
monic_prod_of_monic _ _ $ λ z hz, monic_X_sub_C _
/-- `cyclotomic' n R` is different from `0`. -/
lemma cyclotomic'_ne_zero
(n : ℕ) (R : Type*) [comm_ring R] [integral_domain R] : cyclotomic' n R ≠ 0 :=
(cyclotomic'.monic n R).ne_zero
/-- The natural degree of `cyclotomic' n R` is `totient n` if there is a primitive root of
unity in `R`. -/
lemma nat_degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) :
(cyclotomic' n R).nat_degree = nat.totient n :=
begin
cases nat.eq_zero_or_pos n with hzero hpos,
{ simp only [hzero, cyclotomic'_zero, nat.totient_zero, nat_degree_one] },
rw [cyclotomic'],
rw nat_degree_prod (primitive_roots n R) (λ (z : R), (X - C z)),
simp only [is_primitive_root.card_primitive_roots h hpos, mul_one,
nat_degree_X_sub_C,
nat.cast_id, finset.sum_const, nsmul_eq_mul],
intros z hz,
exact X_sub_C_ne_zero z
end
/-- The degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/
lemma degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) :
(cyclotomic' n R).degree = nat.totient n :=
by simp only [degree_eq_nat_degree (cyclotomic'_ne_zero n R), nat_degree_cyclotomic' h]
/-- The roots of `cyclotomic' n R` are the primitive `n`-th roots of unity. -/
lemma roots_of_cyclotomic (n : ℕ) (R : Type*) [comm_ring R] [integral_domain R] :
(cyclotomic' n R).roots = (primitive_roots n R).val :=
by { rw cyclotomic', exact roots_prod_X_sub_C (primitive_roots n R) }
end integral_domain
section field
variables {K : Type*} [field K]
/-- If there is a primitive `n`th root of unity in `K`, then `X ^ n - 1 = ∏ (X - μ)`, where `μ`
varies over the `n`-th roots of unity. -/
lemma X_pow_sub_one_eq_prod {ζ : K} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) :
X ^ n - 1 = ∏ ζ in nth_roots_finset n K, (X - C ζ) :=
begin
rw [nth_roots_finset, ← multiset.to_finset_eq (is_primitive_root.nth_roots_nodup h)],
simp only [finset.prod_mk, ring_hom.map_one],
rw [nth_roots],
have hmonic : (X ^ n - C (1 : K)).monic := monic_X_pow_sub_C (1 : K) (ne_of_lt hpos).symm,
symmetry,
apply prod_multiset_X_sub_C_of_monic_of_roots_card_eq hmonic,
rw [@nat_degree_X_pow_sub_C K _ _ n 1, ← nth_roots],
exact is_primitive_root.card_nth_roots h
end
/-- `cyclotomic' n K` splits. -/
lemma cyclotomic'_splits (n : ℕ) : splits (ring_hom.id K) (cyclotomic' n K) :=
begin
apply splits_prod (ring_hom.id K),
intros z hz,
simp only [splits_X_sub_C (ring_hom.id K)]
end
/-- If there is a primitive `n`-th root of unity in `K`, then `X ^ n - 1`splits. -/
lemma X_pow_sub_one_splits {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) :
splits (ring_hom.id K) (X ^ n - C (1 : K)) :=
begin
by_cases hzero : n = 0,
{ simp only [hzero, ring_hom.map_one, splits_zero, pow_zero, sub_self] },
rw [splits_iff_card_roots, ← nth_roots, is_primitive_root.card_nth_roots h,
nat_degree_X_pow_sub_C],
end
/-- If there is a primitive `n`-th root of unity in `K`, then
`∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1`. -/
lemma prod_cyclotomic'_eq_X_pow_sub_one {ζ : K} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) :
∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1 :=
begin
rw [X_pow_sub_one_eq_prod hpos h],
have rwcyc : ∀ i ∈ nat.divisors n, cyclotomic' i K = ∏ μ in primitive_roots i K, (X - C μ),
{ intros i hi,
simp only [cyclotomic'] },
conv_lhs { apply_congr,
skip,
simp [rwcyc, H] },
rw ← finset.prod_bUnion,
{ simp only [is_primitive_root.nth_roots_one_eq_bUnion_primitive_roots hpos h] },
intros x hx y hy hdiff,
simp only [nat.mem_divisors, and_true, ne.def, pnat.ne_zero, not_false_iff] at hx hy,
refine is_primitive_root.disjoint _ _ hdiff,
{ exact @nat.pos_of_mem_divisors n x (nat.mem_divisors.2 hx) },
{ exact @nat.pos_of_mem_divisors n y (nat.mem_divisors.2 hy) }
end
/-- If there is a primitive `n`-th root of unity in `K`, then
`cyclotomic' n K = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic' i K)`. -/
lemma cyclotomic'_eq_X_pow_sub_one_div {ζ : K} {n : ℕ} (hpos: 0 < n) (h : is_primitive_root ζ n) :
cyclotomic' n K = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic' i K) :=
begin
rw [←prod_cyclotomic'_eq_X_pow_sub_one hpos h,
nat.divisors_eq_proper_divisors_insert_self_of_pos hpos,
finset.prod_insert nat.proper_divisors.not_self_mem],
have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic' i K).monic,
{ apply monic_prod_of_monic,
intros i hi,
exact cyclotomic'.monic i K },
rw (div_mod_by_monic_unique (cyclotomic' n K) 0 prod_monic _).1,
simp only [degree_zero, zero_add],
refine ⟨by rw mul_comm, _⟩,
rw [bot_lt_iff_ne_bot],
intro h,
exact monic.ne_zero prod_monic (degree_eq_bot.1 h)
end
/-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a
monic polynomial with integer coefficients. -/
lemma int_coeff_of_cyclotomic' {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) :
(∃ (P : polynomial ℤ), map (int.cast_ring_hom K) P = cyclotomic' n K ∧
P.degree = (cyclotomic' n K).degree ∧ P.monic) :=
begin
refine lifts_and_degree_eq_and_monic _ (cyclotomic'.monic n K),
induction n using nat.strong_induction_on with k hk generalizing ζ h,
cases nat.eq_zero_or_pos k with hzero hpos,
{ use 1,
simp only [hzero, cyclotomic'_zero, set.mem_univ, subsemiring.coe_top, eq_self_iff_true,
coe_map_ring_hom, map_one, and_self] },
by_cases hone : k = 1,
{ use X - 1,
simp only [hone, cyclotomic'_one K, set.mem_univ, pnat.one_coe, subsemiring.coe_top,
eq_self_iff_true, map_X, coe_map_ring_hom, map_one, and_self, map_sub], },
let B : polynomial K := ∏ i in nat.proper_divisors k, cyclotomic' i K,
have Bmo : B.monic,
{ apply monic_prod_of_monic,
intros i hi,
exact (cyclotomic'.monic i K) },
have Bint : B ∈ lifts (int.cast_ring_hom K),
{ refine subsemiring.prod_mem (lifts (int.cast_ring_hom K)) _,
intros x hx,
have xsmall := (nat.mem_proper_divisors.1 hx).2,
obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hx).1,
rw [mul_comm] at hd,
exact hk x xsmall (is_primitive_root.pow hpos h hd) },
replace Bint := lifts_and_degree_eq_and_monic Bint Bmo,
obtain ⟨B₁, hB₁, hB₁deg, hB₁mo⟩ := Bint,
let Q₁ : polynomial ℤ := (X ^ k - 1) /ₘ B₁,
have huniq : 0 + B * cyclotomic' k K = X ^ k - 1 ∧ (0 : polynomial K).degree < B.degree,
{ split,
{ rw [zero_add, mul_comm, ←(prod_cyclotomic'_eq_X_pow_sub_one hpos h),
nat.divisors_eq_proper_divisors_insert_self_of_pos hpos],
simp only [true_and, finset.prod_insert, not_lt, nat.mem_proper_divisors, dvd_refl] },
rw [degree_zero, bot_lt_iff_ne_bot],
intro habs,
exact (monic.ne_zero Bmo) (degree_eq_bot.1 habs) },
replace huniq := div_mod_by_monic_unique (cyclotomic' k K) (0 : polynomial K) Bmo huniq,
simp only [lifts, ring_hom.mem_srange],
use Q₁,
rw [coe_map_ring_hom, (map_div_by_monic (int.cast_ring_hom K) hB₁mo), hB₁, ← huniq.1],
simp
end
/-- If `K` is of characteristic `0` and there is a primitive `n`-th root of unity in `K`,
then `cyclotomic n K` comes from a unique polynomial with integer coefficients. -/
lemma unique_int_coeff_of_cycl [char_zero K] {ζ : K} {n : ℕ+} (h : is_primitive_root ζ n) :
(∃! (P : polynomial ℤ), map (int.cast_ring_hom K) P = cyclotomic' n K) :=
begin
obtain ⟨P, hP⟩ := int_coeff_of_cyclotomic' h,
refine ⟨P, hP.1, λ Q hQ, _⟩,
apply (map_injective (int.cast_ring_hom K) int.cast_injective),
rw [hP.1, hQ]
end
end field
end cyclotomic'
section cyclotomic
/-- The `n`-th cyclotomic polynomial with coefficients in `R`. -/
def cyclotomic (n : ℕ) (R : Type*) [ring R] : polynomial R :=
if h : n = 0 then 1 else
map (int.cast_ring_hom R) ((int_coeff_of_cyclotomic' (complex.is_primitive_root_exp n h)).some)
lemma int_cyclotomic_rw {n : ℕ} (h : n ≠ 0) :
cyclotomic n ℤ = (int_coeff_of_cyclotomic' (complex.is_primitive_root_exp n h)).some :=
begin
simp only [cyclotomic, h, dif_neg, not_false_iff],
ext i,
simp only [coeff_map, int.cast_id, ring_hom.eq_int_cast]
end
/-- `cyclotomic n R` comes from `cyclotomic n ℤ`. -/
lemma map_cyclotomic_int (n : ℕ) (R : Type*) [ring R] :
map (int.cast_ring_hom R) (cyclotomic n ℤ) = cyclotomic n R :=
begin
by_cases hzero : n = 0,
{ simp only [hzero, cyclotomic, dif_pos, map_one] },
simp only [cyclotomic, int_cyclotomic_rw, hzero, ne.def, dif_neg, not_false_iff]
end
lemma int_cyclotomic_spec (n : ℕ) : map (int.cast_ring_hom ℂ) (cyclotomic n ℤ) = cyclotomic' n ℂ ∧
(cyclotomic n ℤ).degree = (cyclotomic' n ℂ).degree ∧ (cyclotomic n ℤ).monic :=
begin
by_cases hzero : n = 0,
{ simp only [hzero, cyclotomic, degree_one, monic_one, cyclotomic'_zero, dif_pos,
eq_self_iff_true, map_one, and_self] },
rw int_cyclotomic_rw hzero,
exact (int_coeff_of_cyclotomic' (complex.is_primitive_root_exp n hzero)).some_spec
end
lemma int_cyclotomic_unique {n : ℕ} {P : polynomial ℤ} (h : map (int.cast_ring_hom ℂ) P =
cyclotomic' n ℂ) : P = cyclotomic n ℤ :=
begin
apply map_injective (int.cast_ring_hom ℂ) int.cast_injective,
rw [h, (int_cyclotomic_spec n).1]
end
/-- The definition of `cyclotomic n R` commutes with any ring homomorphism. -/
@[simp] lemma map_cyclotomic (n : ℕ) {R S : Type*} [ring R] [ring S] (f : R →+* S) :
map f (cyclotomic n R) = cyclotomic n S :=
begin
rw [←map_cyclotomic_int n R, ←map_cyclotomic_int n S],
ext i,
simp only [coeff_map, ring_hom.eq_int_cast, ring_hom.map_int_cast]
end
/-- The zeroth cyclotomic polyomial is `1`. -/
@[simp] lemma cyclotomic_zero (R : Type*) [ring R] : cyclotomic 0 R = 1 :=
by simp only [cyclotomic, dif_pos]
/-- The first cyclotomic polyomial is `X - 1`. -/
@[simp] lemma cyclotomic_one (R : Type*) [ring R] : cyclotomic 1 R = X - 1 :=
begin
have hspec : map (int.cast_ring_hom ℂ) (X - 1) = cyclotomic' 1 ℂ,
{ simp only [cyclotomic'_one, pnat.one_coe, map_X, map_one, map_sub] },
symmetry,
rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)],
simp only [map_X, map_one, map_sub]
end
/-- The second cyclotomic polyomial is `X + 1`. -/
@[simp] lemma cyclotomic_two (R : Type*) [ring R] : cyclotomic 2 R = X + 1 :=
begin
have hspec : map (int.cast_ring_hom ℂ) (X + 1) = cyclotomic' 2 ℂ,
{ simp only [cyclotomic'_two ℂ 0 two_ne_zero.symm, map_add, map_X, map_one] },
symmetry,
rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)],
simp only [map_add, map_X, map_one]
end
/-- `cyclotomic n` is monic. -/
lemma cyclotomic.monic (n : ℕ) (R : Type*) [ring R] : (cyclotomic n R).monic :=
begin
rw ←map_cyclotomic_int,
apply monic_map,
exact (int_cyclotomic_spec n).2.2
end
/-- `cyclotomic n R` is different from `0`. -/
lemma cyclotomic_ne_zero (n : ℕ) (R : Type*) [ring R] [nontrivial R] : cyclotomic n R ≠ 0 :=
monic.ne_zero (cyclotomic.monic n R)
/-- The degree of `cyclotomic n` is `totient n`. -/
lemma degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] :
(cyclotomic n R).degree = nat.totient n :=
begin
rw ←map_cyclotomic_int,
rw degree_map_eq_of_leading_coeff_ne_zero (int.cast_ring_hom R) _,
{ cases n with k,
{ simp only [cyclotomic, degree_one, dif_pos, nat.totient_zero, with_top.coe_zero]},
rw [←degree_cyclotomic' (complex.is_primitive_root_exp k.succ (nat.succ_ne_zero k))],
exact (int_cyclotomic_spec k.succ).2.1 },
simp only [(int_cyclotomic_spec n).right.right, ring_hom.eq_int_cast, monic.leading_coeff,
int.cast_one, ne.def, not_false_iff, one_ne_zero]
end
/-- The natural degree of `cyclotomic n` is `totient n`. -/
lemma nat_degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] :
(cyclotomic n R).nat_degree = nat.totient n :=
begin
have hdeg := degree_cyclotomic n R,
rw degree_eq_nat_degree (cyclotomic_ne_zero n R) at hdeg,
exact_mod_cast hdeg
end
/-- The degree of `cyclotomic n R` is positive. -/
lemma degree_cyclotomic_pos (n : ℕ) (R : Type*) (hpos : 0 < n) [ring R] [nontrivial R] :
0 < (cyclotomic n R).degree := by
{ rw degree_cyclotomic n R, exact_mod_cast (nat.totient_pos hpos) }
/-- `∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1`. -/
lemma prod_cyclotomic_eq_X_pow_sub_one {n : ℕ} (hpos : 0 < n) (R : Type*) [comm_ring R] :
∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1 :=
begin
have integer : ∏ i in nat.divisors n, cyclotomic i ℤ = X ^ n - 1,
{ apply map_injective (int.cast_ring_hom ℂ) int.cast_injective,
rw map_prod (int.cast_ring_hom ℂ) (λ i, cyclotomic i ℤ),
simp only [int_cyclotomic_spec, map_pow, nat.cast_id, map_X, map_one, map_sub],
exact prod_cyclotomic'_eq_X_pow_sub_one hpos
(complex.is_primitive_root_exp n (ne_of_lt hpos).symm) },
have coerc : X ^ n - 1 = map (int.cast_ring_hom R) (X ^ n - 1),
{ simp only [map_pow, map_X, map_one, map_sub] },
have h : ∀ i ∈ n.divisors, cyclotomic i R = map (int.cast_ring_hom R) (cyclotomic i ℤ),
{ intros i hi,
exact (map_cyclotomic_int i R).symm },
rw [finset.prod_congr (refl n.divisors) h, coerc, ←map_prod (int.cast_ring_hom R)
(λ i, cyclotomic i ℤ), integer]
end
section arithmetic_function
open nat.arithmetic_function
open_locale arithmetic_function
/-- `cyclotomic n R` can be expressed as a product in a fraction field of `polynomial R`
using Möbius inversion. -/
lemma cyclotomic_eq_prod_X_pow_sub_one_pow_moebius {n : ℕ} (hpos : 0 < n)
(R : Type*) [comm_ring R] [nontrivial R]
{K : Type*} [field K] [algebra (polynomial R) K] [is_fraction_ring (polynomial R) K] :
algebra_map _ K (cyclotomic n R) =
∏ i in n.divisors_antidiagonal, (algebra_map (polynomial R) K (X ^ i.snd - 1)) ^ μ i.fst :=
begin
have h : ∀ (n : ℕ), 0 < n →
∏ i in nat.divisors n, algebra_map _ K (cyclotomic i R) = algebra_map _ _ (X ^ n - 1),
{ intros n hn,
rw [← prod_cyclotomic_eq_X_pow_sub_one hn R, ring_hom.map_prod] },
rw (prod_eq_iff_prod_pow_moebius_eq_of_nonzero (λ n hn, _) (λ n hn, _)).1 h n hpos;
rw [ne.def, is_fraction_ring.to_map_eq_zero_iff],
{ apply cyclotomic_ne_zero },
{ apply monic.ne_zero,
apply monic_X_pow_sub_C _ (ne_of_gt hn) }
end
end arithmetic_function
/-- We have
`cyclotomic n R = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic i K)`. -/
lemma cyclotomic_eq_X_pow_sub_one_div {R : Type*} [comm_ring R] {n : ℕ}
(hpos: 0 < n) : cyclotomic n R = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic i R) :=
begin
nontriviality R,
rw [←prod_cyclotomic_eq_X_pow_sub_one hpos,
nat.divisors_eq_proper_divisors_insert_self_of_pos hpos,
finset.prod_insert nat.proper_divisors.not_self_mem],
have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic,
{ apply monic_prod_of_monic,
intros i hi,
exact cyclotomic.monic i R },
rw (div_mod_by_monic_unique (cyclotomic n R) 0 prod_monic _).1,
simp only [degree_zero, zero_add],
split,
{ rw mul_comm },
rw [bot_lt_iff_ne_bot],
intro h,
exact monic.ne_zero prod_monic (degree_eq_bot.1 h)
end
/-- If `m` is a proper divisor of `n`, then `X ^ m - 1` divides
`∏ i in nat.proper_divisors n, cyclotomic i R`. -/
lemma X_pow_sub_one_dvd_prod_cyclotomic (R : Type*) [comm_ring R] {n m : ℕ} (hpos : 0 < n)
(hm : m ∣ n) (hdiff : m ≠ n) : X ^ m - 1 ∣ ∏ i in nat.proper_divisors n, cyclotomic i R :=
begin
replace hm := nat.mem_proper_divisors.2 ⟨hm, lt_of_le_of_ne (nat.divisor_le (nat.mem_divisors.2
⟨hm, (ne_of_lt hpos).symm⟩)) hdiff⟩,
rw [← finset.sdiff_union_of_subset (nat.divisors_subset_proper_divisors (ne_of_lt hpos).symm
(nat.mem_proper_divisors.1 hm).1 (ne_of_lt (nat.mem_proper_divisors.1 hm).2)),
finset.prod_union finset.sdiff_disjoint, prod_cyclotomic_eq_X_pow_sub_one
(nat.pos_of_mem_proper_divisors hm)],
exact ⟨(∏ (x : ℕ) in n.proper_divisors \ m.divisors, cyclotomic x R), by rw mul_comm⟩
end
/-- If there is a primitive `n`-th root of unity in `K`, then
`cyclotomic n K = ∏ μ in primitive_roots n R, (X - C μ)`. In particular,
`cyclotomic n K = cyclotomic' n K` -/
lemma cyclotomic_eq_prod_X_sub_primitive_roots {K : Type*} [field K] {ζ : K} {n : ℕ}
(hz : is_primitive_root ζ n) :
cyclotomic n K = ∏ μ in primitive_roots n K, (X - C μ) :=
begin
rw ←cyclotomic',
induction n using nat.strong_induction_on with k hk generalizing ζ hz,
obtain hzero | hpos := k.eq_zero_or_pos,
{ simp only [hzero, cyclotomic'_zero, cyclotomic_zero] },
have h : ∀ i ∈ k.proper_divisors, cyclotomic i K = cyclotomic' i K,
{ intros i hi,
obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hi).1,
rw mul_comm at hd,
exact hk i (nat.mem_proper_divisors.1 hi).2 (is_primitive_root.pow hpos hz hd) },
rw [@cyclotomic_eq_X_pow_sub_one_div _ _ _ hpos,
cyclotomic'_eq_X_pow_sub_one_div hpos hz, finset.prod_congr (refl k.proper_divisors) h]
end
/-- Any `n`-th primitive root of unity is a root of `cyclotomic n ℤ`.-/
lemma is_root_cyclotomic {n : ℕ} {K : Type*} [field K] (hpos : 0 < n) {μ : K}
(h : is_primitive_root μ n) : is_root (cyclotomic n K) μ :=
begin
rw [← mem_roots (cyclotomic_ne_zero n K),
cyclotomic_eq_prod_X_sub_primitive_roots h, roots_prod_X_sub_C, ← finset.mem_def],
rwa [← mem_primitive_roots hpos] at h,
end
lemma eq_cyclotomic_iff {R : Type*} [comm_ring R] {n : ℕ} (hpos: 0 < n)
(P : polynomial R) :
P = cyclotomic n R ↔ P * (∏ i in nat.proper_divisors n, polynomial.cyclotomic i R) = X ^ n - 1 :=
begin
nontriviality R,
refine ⟨λ hcycl, _, λ hP, _⟩,
{ rw [hcycl, ← finset.prod_insert (@nat.proper_divisors.not_self_mem n),
← nat.divisors_eq_proper_divisors_insert_self_of_pos hpos],
exact prod_cyclotomic_eq_X_pow_sub_one hpos R },
{ have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic,
{ apply monic_prod_of_monic,
intros i hi,
exact cyclotomic.monic i R },
rw [@cyclotomic_eq_X_pow_sub_one_div R _ _ hpos,
(div_mod_by_monic_unique P 0 prod_monic _).1],
refine ⟨by rwa [zero_add, mul_comm], _⟩,
rw [degree_zero, bot_lt_iff_ne_bot],
intro h,
exact monic.ne_zero prod_monic (degree_eq_bot.1 h) },
end
/-- If `p` is prime, then `cyclotomic p R = geom_sum X p`. -/
lemma cyclotomic_eq_geom_sum {R : Type*} [comm_ring R] {p : ℕ}
(hp : nat.prime p) : cyclotomic p R = geom_sum X p :=
begin
refine ((eq_cyclotomic_iff hp.pos _).mpr _).symm,
simp only [nat.prime.proper_divisors hp, geom_sum_mul, finset.prod_singleton, cyclotomic_one],
end
/-- The constant term of `cyclotomic n R` is `1` if `2 ≤ n`. -/
lemma cyclotomic_coeff_zero (R : Type*) [comm_ring R] {n : ℕ} (hn : 2 ≤ n) :
(cyclotomic n R).coeff 0 = 1 :=
begin
induction n using nat.strong_induction_on with n hi,
have hprod : (∏ i in nat.proper_divisors n, (polynomial.cyclotomic i R).coeff 0) = -1,
{ rw [←finset.insert_erase (nat.one_mem_proper_divisors_iff_one_lt.2
(lt_of_lt_of_le one_lt_two hn)), finset.prod_insert (finset.not_mem_erase 1 _),
cyclotomic_one R],
have hleq : ∀ j ∈ n.proper_divisors.erase 1, 2 ≤ j,
{ intros j hj,
apply nat.succ_le_of_lt,
exact (ne.le_iff_lt ((finset.mem_erase.1 hj).1).symm).mp
(nat.succ_le_of_lt (nat.pos_of_mem_proper_divisors (finset.mem_erase.1 hj).2)) },
have hcongr : ∀ j ∈ n.proper_divisors.erase 1, (cyclotomic j R).coeff 0 = 1,
{ intros j hj,
exact hi j (nat.mem_proper_divisors.1 (finset.mem_erase.1 hj).2).2 (hleq j hj) },
have hrw : ∏ (x : ℕ) in n.proper_divisors.erase 1, (cyclotomic x R).coeff 0 = 1,
{ rw finset.prod_congr (refl (n.proper_divisors.erase 1)) hcongr,
simp only [finset.prod_const_one] },
simp only [hrw, mul_one, zero_sub, coeff_one_zero, coeff_X_zero, coeff_sub] },
have heq : (X ^ n - 1).coeff 0 = -(cyclotomic n R).coeff 0,
{ rw [←prod_cyclotomic_eq_X_pow_sub_one (lt_of_lt_of_le zero_lt_two hn),
nat.divisors_eq_proper_divisors_insert_self_of_pos (lt_of_lt_of_le zero_lt_two hn),
finset.prod_insert nat.proper_divisors.not_self_mem, mul_coeff_zero, coeff_zero_prod, hprod,
mul_neg_eq_neg_mul_symm, mul_one] },
have hzero : (X ^ n - 1).coeff 0 = (-1 : R),
{ rw coeff_zero_eq_eval_zero _,
simp only [zero_pow (lt_of_lt_of_le zero_lt_two hn), eval_X, eval_one, zero_sub, eval_pow,
eval_sub] },
rw hzero at heq,
exact neg_inj.mp (eq.symm heq)
end
/-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, where `p` is a prime, then `a` and `p` are
coprime. -/
lemma coprime_of_root_cyclotomic {n : ℕ} (hpos : 0 < n) {p : ℕ} [hprime : fact p.prime] {a : ℕ}
(hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) :
a.coprime p :=
begin
apply nat.coprime.symm,
rw [hprime.1.coprime_iff_not_dvd],
intro h,
replace h := (zmod.nat_coe_zmod_eq_zero_iff_dvd a p).2 h,
rw [is_root.def, ring_hom.eq_nat_cast, h, ← coeff_zero_eq_eval_zero] at hroot,
by_cases hone : n = 1,
{ simp only [hone, cyclotomic_one, zero_sub, coeff_one_zero, coeff_X_zero, neg_eq_zero,
one_ne_zero, coeff_sub] at hroot,
exact hroot },
rw [cyclotomic_coeff_zero (zmod p) (nat.succ_le_of_lt (lt_of_le_of_ne
(nat.succ_le_of_lt hpos) (ne.symm hone)))] at hroot,
exact one_ne_zero hroot
end
end cyclotomic
section order
/-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, then the multiplicative order of `a` modulo
`p` divides `n`. -/
lemma order_of_root_cyclotomic_dvd {n : ℕ} (hpos : 0 < n) {p : ℕ} [fact p.prime]
{a : ℕ} (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) :
order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)) ∣ n :=
begin
apply order_of_dvd_of_pow_eq_one,
suffices hpow : eval (nat.cast_ring_hom (zmod p) a) (X ^ n - 1 : polynomial (zmod p)) = 0,
{ simp only [eval_X, eval_one, eval_pow, eval_sub, ring_hom.eq_nat_cast] at hpow,
apply units.coe_eq_one.1,
simp only [sub_eq_zero.mp hpow, zmod.coe_unit_of_coprime, units.coe_pow] },
rw [is_root.def] at hroot,
rw [← prod_cyclotomic_eq_X_pow_sub_one hpos (zmod p),
nat.divisors_eq_proper_divisors_insert_self_of_pos hpos,
finset.prod_insert nat.proper_divisors.not_self_mem, eval_mul, hroot, zero_mul]
end
/-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, where `p` is a prime that does not divide
`n`, then the multiplicative order of `a` modulo `p` is exactly `n`. -/
lemma order_of_root_cyclotomic_eq {n : ℕ} (hpos : 0 < n) {p : ℕ} [fact p.prime] {a : ℕ}
(hn : ¬ p ∣ n) (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) :
order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)) = n :=
begin
set m := order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)),
have ha := coprime_of_root_cyclotomic hpos hroot,
have hdivcycl : map (int.cast_ring_hom (zmod p)) (X - a) ∣ (cyclotomic n (zmod p)),
{ replace hrootdiv := dvd_iff_is_root.2 hroot,
simp only [C_eq_nat_cast, ring_hom.eq_nat_cast] at hrootdiv,
simp only [hrootdiv, map_nat_cast, map_X, map_sub] },
by_contra hdiff,
have hdiv : map (int.cast_ring_hom (zmod p)) (X - a) ∣
∏ i in nat.proper_divisors n, cyclotomic i (zmod p),
{ suffices hdivm : map (int.cast_ring_hom (zmod p)) (X - a) ∣ X ^ m - 1,
{ exact hdivm.trans (X_pow_sub_one_dvd_prod_cyclotomic (zmod p) hpos
(order_of_root_cyclotomic_dvd hpos hroot) hdiff) },
rw [map_sub, map_X, map_nat_cast, ← C_eq_nat_cast, dvd_iff_is_root, is_root.def, eval_sub,
eval_pow, eval_one, eval_X, sub_eq_zero, ← zmod.coe_unit_of_coprime a ha, ← units.coe_pow,
units.coe_eq_one],
exact pow_order_of_eq_one (zmod.unit_of_coprime a ha) },
have habs : (map (int.cast_ring_hom (zmod p)) (X - a)) ^ 2 ∣ X ^ n - 1,
{ obtain ⟨P, hP⟩ := hdivcycl,
obtain ⟨Q, hQ⟩ := hdiv,
rw [← prod_cyclotomic_eq_X_pow_sub_one hpos, nat.divisors_eq_proper_divisors_insert_self_of_pos
hpos, finset.prod_insert nat.proper_divisors.not_self_mem, hP, hQ],
exact ⟨P * Q, by ring⟩ },
have hnzero : ↑n ≠ (0 : (zmod p)),
{ intro ha,
exact hn (int.coe_nat_dvd.1 ((zmod.int_coe_zmod_eq_zero_iff_dvd n p).1 ha)) },
rw [sq] at habs,
replace habs := squarefree_X_pow_sub_C (1 : (zmod p)) hnzero one_ne_zero
(map (int.cast_ring_hom (zmod p)) (X - a)) habs,
simp only [map_nat_cast, map_X, map_sub] at habs,
replace habs := degree_eq_zero_of_is_unit habs,
rw [← C_eq_nat_cast, degree_X_sub_C] at habs,
exact one_ne_zero habs
end
end order
section minpoly
open is_primitive_root complex
/-- The minimal polynomial of a primitive `n`-th root of unity `μ` divides `cyclotomic n ℤ`. -/
lemma _root_.minpoly_dvd_cyclotomic {n : ℕ} {K : Type*} [field K] {μ : K}
(h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] :
minpoly ℤ μ ∣ cyclotomic n ℤ :=
begin
apply minpoly.gcd_domain_dvd ℚ (is_integral h hpos) (cyclotomic.monic n ℤ).is_primitive,
simpa [aeval_def, eval₂_eq_eval_map, is_root.def] using is_root_cyclotomic hpos h
end
/-- `cyclotomic n ℤ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. -/
lemma cyclotomic_eq_minpoly {n : ℕ} {K : Type*} [field K] {μ : K}
(h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] :
cyclotomic n ℤ = minpoly ℤ μ :=
begin
refine eq_of_monic_of_dvd_of_nat_degree_le (minpoly.monic (is_integral h hpos))
(cyclotomic.monic n ℤ) (minpoly_dvd_cyclotomic h hpos) _,
simpa [nat_degree_cyclotomic n ℤ] using totient_le_degree_minpoly h hpos
end
/-- `cyclotomic n ℤ` is irreducible. -/
lemma cyclotomic.irreducible {n : ℕ} (hpos : 0 < n) : irreducible (cyclotomic n ℤ) :=
begin
rw [cyclotomic_eq_minpoly (is_primitive_root_exp n hpos.ne') hpos],
apply minpoly.irreducible,
exact (is_primitive_root_exp n hpos.ne').is_integral hpos,
end
end minpoly
end polynomial
|
cd2829f1dfd6d9d70db0733805ed254e370dbe27 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/topology/algebra/affine.lean | 5867622b74c73751a7956e98d58c9d5de3672c90 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,408 | lean | /-
Copyright (c) 2020 Frédéric Dupuis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Frédéric Dupuis
-/
import topology.continuous_function.algebra
import linear_algebra.affine_space.affine_map
/-!
# Topological properties of affine spaces and maps
For now, this contains only a few facts regarding the continuity of affine maps in the special
case when the point space and vector space are the same.
-/
variables {R E F : Type*}
[ring R]
[add_comm_group E] [semimodule R E] [topological_space E]
[add_comm_group F] [semimodule R F] [topological_space F] [topological_add_group F]
namespace affine_map
/-
TODO: Deal with the case where the point spaces are different from the vector spaces.
-/
/-- An affine map is continuous iff its underlying linear map is continuous. -/
lemma continuous_iff {f : E →ᵃ[R] F} :
continuous f ↔ continuous f.linear :=
begin
split,
{ intro hc,
rw decomp' f,
have := hc.sub continuous_const,
exact this, },
{ intro hc,
rw decomp f,
have := hc.add continuous_const,
exact this }
end
/-- The line map is continuous. -/
lemma line_map_continuous [topological_space R] [has_continuous_smul R F] {p v : F} :
continuous ⇑(line_map p v : R →ᵃ[R] F) :=
continuous_iff.mpr $ (continuous_id.smul continuous_const).add $
@continuous_const _ _ _ _ (0 : F)
end affine_map
|
bdf20859159ebe71b55db59854905fc9f377807c | 206422fb9edabf63def0ed2aa3f489150fb09ccb | /src/algebra/group/basic.lean | e5084c533773e3e244b167a6054cef1d7dbebc9b | [
"Apache-2.0"
] | permissive | hamdysalah1/mathlib | b915f86b2503feeae268de369f1b16932321f097 | 95454452f6b3569bf967d35aab8d852b1ddf8017 | refs/heads/master | 1,677,154,116,545 | 1,611,797,994,000 | 1,611,797,994,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,298 | 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, Simon Hudon, Mario Carneiro
-/
import algebra.group.defs
import logic.function.basic
universe u
section associative
variables {α : Type u} (f : α → α → α) [is_associative α f] (x y : α)
/--
Composing two associative operations of `f : α → α → α` on the left
is equal to an associative operation on the left.
-/
lemma comp_assoc_left : (f x) ∘ (f y) = (f (f x y)) :=
by { ext z, rw [function.comp_apply, @is_associative.assoc _ f] }
/--
Composing two associative operations of `f : α → α → α` on the right
is equal to an associative operation on the right.
-/
lemma comp_assoc_right : (λ z, f z x) ∘ (λ z, f z y) = (λ z, f z (f y x)) :=
by { ext z, rw [function.comp_apply, @is_associative.assoc _ f] }
end associative
section semigroup
variables {α : Type*}
/--
Composing two multiplications on the left by `y` then `x`
is equal to a multiplication on the left by `x * y`.
-/
@[simp, to_additive
"Composing two additions on the left by `y` then `x`
is equal to a addition on the left by `x + y`."]
lemma comp_mul_left [semigroup α] (x y : α) :
((*) x) ∘ ((*) y) = ((*) (x * y)) :=
comp_assoc_left _ _ _
/--
Composing two multiplications on the right by `y` and `x`
is equal to a multiplication on the right by `y * x`.
-/
@[simp, to_additive
"Composing two additions on the right by `y` and `x`
is equal to a addition on the right by `y + x`."]
lemma comp_mul_right [semigroup α] (x y : α) :
(* x) ∘ (* y) = (* (y * x)) :=
comp_assoc_right _ _ _
end semigroup
section monoid
variables {M : Type u} [monoid M]
@[to_additive]
lemma ite_mul_one {P : Prop} [decidable P] {a b : M} :
ite P (a * b) 1 = ite P a 1 * ite P b 1 :=
by { by_cases h : P; simp [h], }
@[to_additive]
lemma eq_one_iff_eq_one_of_mul_eq_one {a b : M} (h : a * b = 1) : a = 1 ↔ b = 1 :=
by split; { rintro rfl, simpa using h }
end monoid
section comm_semigroup
variables {G : Type u} [comm_semigroup G]
@[no_rsimp, to_additive]
lemma mul_left_comm : ∀ a b c : G, a * (b * c) = b * (a * c) :=
left_comm has_mul.mul mul_comm mul_assoc
attribute [no_rsimp] add_left_comm
@[to_additive]
lemma mul_right_comm : ∀ a b c : G, a * b * c = a * c * b :=
right_comm has_mul.mul mul_comm mul_assoc
@[to_additive]
theorem mul_mul_mul_comm (a b c d : G) : (a * b) * (c * d) = (a * c) * (b * d) :=
by simp only [mul_left_comm, mul_assoc]
end comm_semigroup
local attribute [simp] mul_assoc sub_eq_add_neg
section add_monoid
variables {M : Type u} [add_monoid M] {a b c : M}
@[simp] lemma bit0_zero : bit0 (0 : M) = 0 := add_zero _
@[simp] lemma bit1_zero [has_one M] : bit1 (0 : M) = 1 :=
by rw [bit1, bit0_zero, zero_add]
end add_monoid
section comm_monoid
variables {M : Type u} [comm_monoid M] {x y z : M}
@[to_additive] lemma inv_unique (hy : x * y = 1) (hz : x * z = 1) : y = z :=
left_inv_eq_right_inv (trans (mul_comm _ _) hy) hz
end comm_monoid
section left_cancel_monoid
variables {M : Type u} [left_cancel_monoid M] {a b : M}
@[simp, to_additive] lemma mul_eq_left_iff : a * b = a ↔ b = 1 :=
calc a * b = a ↔ a * b = a * 1 : by rw mul_one
... ↔ b = 1 : mul_left_cancel_iff
@[simp, to_additive] lemma left_eq_mul_iff : a = a * b ↔ b = 1 :=
eq_comm.trans mul_eq_left_iff
end left_cancel_monoid
section right_cancel_monoid
variables {M : Type u} [right_cancel_monoid M] {a b : M}
@[simp, to_additive] lemma mul_eq_right_iff : a * b = b ↔ a = 1 :=
calc a * b = b ↔ a * b = 1 * b : by rw one_mul
... ↔ a = 1 : mul_right_cancel_iff
@[simp, to_additive] lemma right_eq_mul_iff : b = a * b ↔ a = 1 :=
eq_comm.trans mul_eq_right_iff
end right_cancel_monoid
section div_inv_monoid
variables {G : Type u} [div_inv_monoid G]
@[to_additive]
lemma inv_eq_one_div (x : G) :
x⁻¹ = 1 / x :=
by rw [div_eq_mul_inv, one_mul]
@[to_additive]
lemma mul_one_div (x y : G) :
x * (1 / y) = x / y :=
by rw [div_eq_mul_inv, one_mul, div_eq_mul_inv]
lemma mul_div_assoc {a b c : G} : a * b / c = a * (b / c) :=
by rw [div_eq_mul_inv, div_eq_mul_inv, mul_assoc _ _ _]
lemma mul_div_assoc' (a b c : G) : a * (b / c) = (a * b) / c :=
mul_div_assoc.symm
@[simp, to_additive] lemma one_div (a : G) : 1 / a = a⁻¹ :=
(inv_eq_one_div a).symm
end div_inv_monoid
section group
variables {G : Type u} [group G] {a b c : G}
@[simp, to_additive]
lemma inv_mul_cancel_right (a b : G) : a * b⁻¹ * b = a :=
by simp [mul_assoc]
@[simp, to_additive neg_zero]
lemma one_inv : 1⁻¹ = (1 : G) :=
inv_eq_of_mul_eq_one (one_mul 1)
@[to_additive]
theorem left_inverse_inv (G) [group G] :
function.left_inverse (λ a : G, a⁻¹) (λ a, a⁻¹) :=
inv_inv
@[simp, to_additive]
lemma inv_involutive : function.involutive (has_inv.inv : G → G) := inv_inv
@[to_additive]
lemma inv_injective : function.injective (has_inv.inv : G → G) :=
inv_involutive.injective
@[simp, to_additive] theorem inv_inj : a⁻¹ = b⁻¹ ↔ a = b := inv_injective.eq_iff
@[simp, to_additive]
lemma mul_inv_cancel_left (a b : G) : a * (a⁻¹ * b) = b :=
by rw [← mul_assoc, mul_right_inv, one_mul]
@[to_additive]
theorem mul_left_surjective (a : G) : function.surjective ((*) a) :=
λ x, ⟨a⁻¹ * x, mul_inv_cancel_left a x⟩
@[to_additive]
theorem mul_right_surjective (a : G) : function.surjective (λ x, x * a) :=
λ x, ⟨x * a⁻¹, inv_mul_cancel_right x a⟩
@[simp, to_additive neg_add_rev]
lemma mul_inv_rev (a b : G) : (a * b)⁻¹ = b⁻¹ * a⁻¹ :=
inv_eq_of_mul_eq_one $ by simp
@[to_additive]
lemma eq_inv_of_eq_inv (h : a = b⁻¹) : b = a⁻¹ :=
by simp [h]
@[to_additive]
lemma eq_inv_of_mul_eq_one (h : a * b = 1) : a = b⁻¹ :=
have a⁻¹ = b, from inv_eq_of_mul_eq_one h,
by simp [this.symm]
@[to_additive]
lemma eq_mul_inv_of_mul_eq (h : a * c = b) : a = b * c⁻¹ :=
by simp [h.symm]
@[to_additive]
lemma eq_inv_mul_of_mul_eq (h : b * a = c) : a = b⁻¹ * c :=
by simp [h.symm]
@[to_additive]
lemma inv_mul_eq_of_eq_mul (h : b = a * c) : a⁻¹ * b = c :=
by simp [h]
@[to_additive]
lemma mul_inv_eq_of_eq_mul (h : a = c * b) : a * b⁻¹ = c :=
by simp [h]
@[to_additive]
lemma eq_mul_of_mul_inv_eq (h : a * c⁻¹ = b) : a = b * c :=
by simp [h.symm]
@[to_additive]
lemma eq_mul_of_inv_mul_eq (h : b⁻¹ * a = c) : a = b * c :=
by simp [h.symm, mul_inv_cancel_left]
@[to_additive]
lemma mul_eq_of_eq_inv_mul (h : b = a⁻¹ * c) : a * b = c :=
by rw [h, mul_inv_cancel_left]
@[to_additive]
lemma mul_eq_of_eq_mul_inv (h : a = c * b⁻¹) : a * b = c :=
by simp [h]
@[to_additive]
theorem mul_self_iff_eq_one : a * a = a ↔ a = 1 :=
by have := @mul_right_inj _ _ a a 1; rwa mul_one at this
@[simp, to_additive]
theorem inv_eq_one : a⁻¹ = 1 ↔ a = 1 :=
by rw [← @inv_inj _ _ a 1, one_inv]
@[simp, to_additive]
theorem one_eq_inv : 1 = a⁻¹ ↔ a = 1 :=
by rw [eq_comm, inv_eq_one]
@[to_additive]
theorem inv_ne_one : a⁻¹ ≠ 1 ↔ a ≠ 1 :=
not_congr inv_eq_one
@[to_additive]
theorem eq_inv_iff_eq_inv : a = b⁻¹ ↔ b = a⁻¹ :=
⟨eq_inv_of_eq_inv, eq_inv_of_eq_inv⟩
@[to_additive]
theorem inv_eq_iff_inv_eq : a⁻¹ = b ↔ b⁻¹ = a :=
eq_comm.trans $ eq_inv_iff_eq_inv.trans eq_comm
@[to_additive]
theorem mul_eq_one_iff_eq_inv : a * b = 1 ↔ a = b⁻¹ :=
by simpa [mul_left_inv, -mul_left_inj] using @mul_left_inj _ _ b a (b⁻¹)
@[to_additive]
theorem mul_eq_one_iff_inv_eq : a * b = 1 ↔ a⁻¹ = b :=
by rw [mul_eq_one_iff_eq_inv, eq_inv_iff_eq_inv, eq_comm]
@[to_additive]
theorem eq_inv_iff_mul_eq_one : a = b⁻¹ ↔ a * b = 1 :=
mul_eq_one_iff_eq_inv.symm
@[to_additive]
theorem inv_eq_iff_mul_eq_one : a⁻¹ = b ↔ a * b = 1 :=
mul_eq_one_iff_inv_eq.symm
@[to_additive]
theorem eq_mul_inv_iff_mul_eq : a = b * c⁻¹ ↔ a * c = b :=
⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩
@[to_additive]
theorem eq_inv_mul_iff_mul_eq : a = b⁻¹ * c ↔ b * a = c :=
⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩
@[to_additive]
theorem inv_mul_eq_iff_eq_mul : a⁻¹ * b = c ↔ b = a * c :=
⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩
@[to_additive]
theorem mul_inv_eq_iff_eq_mul : a * b⁻¹ = c ↔ a = c * b :=
⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩
@[to_additive]
theorem mul_inv_eq_one : a * b⁻¹ = 1 ↔ a = b :=
by rw [mul_eq_one_iff_eq_inv, inv_inv]
@[to_additive]
theorem inv_mul_eq_one : a⁻¹ * b = 1 ↔ a = b :=
by rw [mul_eq_one_iff_eq_inv, inv_inj]
@[simp, to_additive]
lemma mul_left_eq_self : a * b = b ↔ a = 1 :=
⟨λ h, @mul_right_cancel _ _ a b 1 (by simp [h]), λ h, by simp [h]⟩
@[simp, to_additive]
lemma mul_right_eq_self : a * b = a ↔ b = 1 :=
⟨λ h, @mul_left_cancel _ _ a b 1 (by simp [h]), λ h, by simp [h]⟩
@[to_additive]
lemma div_left_injective : function.injective (λ a, a / b) :=
by simpa only [div_eq_mul_inv] using λ a a' h, mul_left_injective (b⁻¹) h
@[to_additive]
lemma div_right_injective : function.injective (λ a, b / a) :=
by simpa only [div_eq_mul_inv] using λ a a' h, inv_injective (mul_right_injective b h)
end group
section add_group
variables {G : Type u} [add_group G] {a b c d : G}
@[simp] lemma sub_self (a : G) : a - a = 0 :=
by rw [sub_eq_add_neg, add_right_neg a]
@[simp] lemma sub_add_cancel (a b : G) : a - b + b = a :=
by rw [sub_eq_add_neg, neg_add_cancel_right a b]
@[simp] lemma add_sub_cancel (a b : G) : a + b - b = a :=
by rw [sub_eq_add_neg, add_neg_cancel_right a b]
lemma add_sub_assoc (a b c : G) : a + b - c = a + (b - c) :=
by rw [sub_eq_add_neg, add_assoc, ←sub_eq_add_neg]
lemma eq_of_sub_eq_zero (h : a - b = 0) : a = b :=
have 0 + b = b, by rw zero_add,
have (a - b) + b = b, by rwa h,
by rwa [sub_eq_add_neg, neg_add_cancel_right] at this
lemma sub_eq_zero_of_eq (h : a = b) : a - b = 0 :=
by rw [h, sub_self]
lemma sub_eq_zero_iff_eq : a - b = 0 ↔ a = b :=
⟨eq_of_sub_eq_zero, sub_eq_zero_of_eq⟩
@[simp] lemma sub_zero (a : G) : a - 0 = a :=
by rw [sub_eq_add_neg, neg_zero, add_zero]
lemma sub_ne_zero_of_ne (h : a ≠ b) : a - b ≠ 0 :=
begin
intro hab,
apply h,
apply eq_of_sub_eq_zero hab
end
@[simp] lemma sub_neg_eq_add (a b : G) : a - (-b) = a + b :=
by rw [sub_eq_add_neg, neg_neg]
@[simp] lemma neg_sub (a b : G) : -(a - b) = b - a :=
neg_eq_of_add_eq_zero (by rw [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left,
add_right_neg])
local attribute [simp] add_assoc
lemma add_sub (a b c : G) : a + (b - c) = a + b - c :=
by simp
lemma sub_add_eq_sub_sub_swap (a b c : G) : a - (b + c) = a - c - b :=
by simp
@[simp] lemma add_sub_add_right_eq_sub (a b c : G) : (a + c) - (b + c) = a - b :=
by rw [sub_add_eq_sub_sub_swap]; simp
lemma eq_sub_of_add_eq (h : a + c = b) : a = b - c :=
by simp [h.symm]
lemma sub_eq_of_eq_add (h : a = c + b) : a - b = c :=
by simp [h]
lemma eq_add_of_sub_eq (h : a - c = b) : a = b + c :=
by simp [h.symm]
lemma add_eq_of_eq_sub (h : a = c - b) : a + b = c :=
by simp [h]
@[simp] lemma sub_right_inj : a - b = a - c ↔ b = c :=
sub_right_injective.eq_iff
@[simp] lemma sub_left_inj : b - a = c - a ↔ b = c :=
by { rw [sub_eq_add_neg, sub_eq_add_neg], exact add_left_inj _ }
lemma sub_add_sub_cancel (a b c : G) : (a - b) + (b - c) = a - c :=
by rw [← add_sub_assoc, sub_add_cancel]
lemma sub_sub_sub_cancel_right (a b c : G) : (a - c) - (b - c) = a - b :=
by rw [← neg_sub c b, sub_neg_eq_add, sub_add_sub_cancel]
theorem sub_sub_assoc_swap : a - (b - c) = a + c - b :=
by simp
theorem sub_eq_zero : a - b = 0 ↔ a = b :=
⟨eq_of_sub_eq_zero, λ h, by rw [h, sub_self]⟩
theorem sub_ne_zero : a - b ≠ 0 ↔ a ≠ b :=
not_congr sub_eq_zero
theorem eq_sub_iff_add_eq : a = b - c ↔ a + c = b :=
by rw [sub_eq_add_neg, eq_add_neg_iff_add_eq]
theorem sub_eq_iff_eq_add : a - b = c ↔ a = c + b :=
by rw [sub_eq_add_neg, add_neg_eq_iff_eq_add]
theorem eq_iff_eq_of_sub_eq_sub (H : a - b = c - d) : a = b ↔ c = d :=
by rw [← sub_eq_zero, H, sub_eq_zero]
theorem left_inverse_sub_add_left (c : G) : function.left_inverse (λ x, x - c) (λ x, x + c) :=
assume x, add_sub_cancel x c
theorem left_inverse_add_left_sub (c : G) : function.left_inverse (λ x, x + c) (λ x, x - c) :=
assume x, sub_add_cancel x c
theorem left_inverse_add_right_neg_add (c : G) :
function.left_inverse (λ x, c + x) (λ x, - c + x) :=
assume x, add_neg_cancel_left c x
theorem left_inverse_neg_add_add_right (c : G) :
function.left_inverse (λ x, - c + x) (λ x, c + x) :=
assume x, neg_add_cancel_left c x
end add_group
section comm_group
variables {G : Type u} [comm_group G]
@[to_additive neg_add]
lemma mul_inv (a b : G) : (a * b)⁻¹ = a⁻¹ * b⁻¹ :=
by rw [mul_inv_rev, mul_comm]
end comm_group
section add_comm_group
variables {G : Type u} [add_comm_group G] {a b c d : G}
local attribute [simp] add_assoc add_comm add_left_comm sub_eq_add_neg
lemma sub_add_eq_sub_sub (a b c : G) : a - (b + c) = a - b - c :=
by simp
lemma neg_add_eq_sub (a b : G) : -a + b = b - a :=
by simp
lemma sub_add_eq_add_sub (a b c : G) : a - b + c = a + c - b :=
by simp
lemma sub_sub (a b c : G) : a - b - c = a - (b + c) :=
by simp
lemma sub_add (a b c : G) : a - b + c = a - (b - c) :=
by simp
@[simp] lemma add_sub_add_left_eq_sub (a b c : G) : (c + a) - (c + b) = a - b :=
by simp
lemma eq_sub_of_add_eq' (h : c + a = b) : a = b - c :=
by simp [h.symm]
lemma sub_eq_of_eq_add' (h : a = b + c) : a - b = c :=
begin simp [h], rw [add_left_comm], simp end
lemma eq_add_of_sub_eq' (h : a - b = c) : a = b + c :=
by simp [h.symm]
lemma add_eq_of_eq_sub' (h : b = c - a) : a + b = c :=
begin simp [h], rw [add_comm c, add_neg_cancel_left] end
lemma sub_sub_self (a b : G) : a - (a - b) = b :=
begin simp, rw [add_comm b, add_neg_cancel_left] end
lemma add_sub_comm (a b c d : G) : a + b - (c + d) = (a - c) + (b - d) :=
by simp
lemma sub_eq_sub_add_sub (a b c : G) : a - b = c - b + (a - c) :=
begin simp, rw [add_left_comm c], simp end
lemma neg_neg_sub_neg (a b : G) : - (-a - -b) = a - b :=
by simp
@[simp] lemma sub_sub_cancel (a b : G) : a - (a - b) = b := sub_sub_self a b
lemma sub_eq_neg_add (a b : G) : a - b = -b + a :=
by rw [sub_eq_add_neg, add_comm _ _]
theorem neg_add' (a b : G) : -(a + b) = -a - b :=
by rw [sub_eq_add_neg, neg_add a b]
@[simp]
lemma neg_sub_neg (a b : G) : -a - -b = b - a :=
by simp [sub_eq_neg_add, add_comm]
lemma eq_sub_iff_add_eq' : a = b - c ↔ c + a = b :=
by rw [eq_sub_iff_add_eq, add_comm]
lemma sub_eq_iff_eq_add' : a - b = c ↔ a = b + c :=
by rw [sub_eq_iff_eq_add, add_comm]
@[simp]
lemma add_sub_cancel' (a b : G) : a + b - a = b :=
by rw [sub_eq_neg_add, neg_add_cancel_left]
@[simp]
lemma add_sub_cancel'_right (a b : G) : a + (b - a) = b :=
by rw [← add_sub_assoc, add_sub_cancel']
-- This lemma is in the `simp` set under the name `add_neg_cancel_comm_assoc`,
-- defined in `algebra/group/commute`
lemma add_add_neg_cancel'_right (a b : G) : a + (b + -a) = b :=
by rw [← sub_eq_add_neg, add_sub_cancel'_right a b]
lemma sub_right_comm (a b c : G) : a - b - c = a - c - b :=
by { repeat { rw sub_eq_add_neg }, exact add_right_comm _ _ _ }
@[simp] lemma add_add_sub_cancel (a b c : G) : (a + c) + (b - c) = a + b :=
by rw [add_assoc, add_sub_cancel'_right]
@[simp] lemma sub_add_add_cancel (a b c : G) : (a - c) + (b + c) = a + b :=
by rw [add_left_comm, sub_add_cancel, add_comm]
@[simp] lemma sub_add_sub_cancel' (a b c : G) : (a - b) + (c - a) = c - b :=
by rw add_comm; apply sub_add_sub_cancel
@[simp] lemma add_sub_sub_cancel (a b c : G) : (a + b) - (a - c) = b + c :=
by rw [← sub_add, add_sub_cancel']
@[simp] lemma sub_sub_sub_cancel_left (a b c : G) : (c - a) - (c - b) = b - a :=
by rw [← neg_sub b c, sub_neg_eq_add, add_comm, sub_add_sub_cancel]
lemma sub_eq_sub_iff_add_eq_add : a - b = c - d ↔ a + d = c + b :=
begin
rw [sub_eq_iff_eq_add, sub_add_eq_add_sub, eq_comm, sub_eq_iff_eq_add'],
simp only [add_comm, eq_comm]
end
lemma sub_eq_sub_iff_sub_eq_sub : a - b = c - d ↔ a - c = b - d :=
by rw [sub_eq_iff_eq_add, sub_add_eq_add_sub, sub_eq_iff_eq_add', add_sub_assoc]
end add_comm_group
|
fd0f86060ff964bd98f9d3135c4a63e34cba409e | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/topology/algebra/continuous_functions.lean | abf60795469f5a529e5960e849ab806f1dfdad03 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 2,289 | 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 topology.basic
import topology.algebra.ring
import ring_theory.subring
universes u v
local attribute [elab_simple] continuous.comp
@[to_additive continuous_add_submonoid]
instance continuous_submonoid (α : Type u) (β : Type v) [topological_space α] [topological_space β]
[monoid β] [topological_monoid β] : is_submonoid { f : α → β | continuous f } :=
{ one_mem := @continuous_const _ _ _ _ 1,
mul_mem :=
λ f g fc gc, continuous.comp (continuous.prod_mk fc gc) (topological_monoid.continuous_mul β) }.
@[to_additive continuous_add_subgroup]
instance continuous_subgroup (α : Type u) (β : Type v) [topological_space α] [topological_space β]
[group β] [topological_group β] : is_subgroup { f : α → β | continuous f } :=
{ inv_mem := λ f fc, continuous.comp fc (topological_group.continuous_inv β),
..continuous_submonoid α β, }.
@[to_additive continuous_add_monoid]
instance continuous_monoid {α : Type u} {β : Type v} [topological_space α] [topological_space β]
[monoid β] [topological_monoid β] : monoid { f : α → β | continuous f } :=
subtype.monoid
@[to_additive continuous_add_group]
instance continuous_group {α : Type u} {β : Type v} [topological_space α] [topological_space β]
[group β] [topological_group β] : group { f : α → β | continuous f } :=
subtype.group
instance continuous_subring (α : Type u) (β : Type v) [topological_space α] [topological_space β]
[ring β] [topological_ring β] : is_subring { f : α → β | continuous f } :=
{ ..continuous_add_subgroup α β,
..continuous_submonoid α β }.
instance continuous_ring {α : Type u} {β : Type v} [topological_space α] [topological_space β]
[ring β] [topological_ring β] : ring { f : α → β | continuous f } :=
@subtype.ring _ _ _ (continuous_subring α β) -- infer_instance doesn't work?!
instance continuous_comm_ring {α : Type u} {β : Type v} [topological_space α] [topological_space β]
[comm_ring β] [topological_ring β] : comm_ring { f : α → β | continuous f } :=
@subtype.comm_ring _ _ _ (continuous_subring α β) -- infer_instance doesn't work?!
|
47c160fb680aca550f9c9d19b4dcd017df799397 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/meta/level.lean | fcf4df56365c1fbe28006c66fc973ec0822f1fed | [] | 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 | 408 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.meta.name
import Mathlib.Lean3Lib.init.meta.format
namespace Mathlib
/-- A type universe term. eg `max u v`. Reflect a C++ level object. The VM replaces it with the C++ implementation. -/
|
914fea40f47ff1abdbd0480245d6fb12f5c22d2b | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/analysis/normed_space/finite_dimension.lean | c0404de8b352d522b8561f847871679e241de540 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 21,715 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.normed_space.operator_norm
import analysis.normed_space.add_torsor
import topology.bases
import linear_algebra.finite_dimensional
/-!
# Finite dimensional normed spaces over complete fields
Over a complete nondiscrete field, in finite dimension, all norms are equivalent and all linear maps
are continuous. Moreover, a finite-dimensional subspace is always complete and closed.
## Main results:
* `linear_map.continuous_of_finite_dimensional` : a linear map on a finite-dimensional space over a
complete field is continuous.
* `finite_dimensional.complete` : a finite-dimensional space over a complete field is complete. This
is not registered as an instance, as the field would be an unknown metavariable in typeclass
resolution.
* `submodule.closed_of_finite_dimensional` : a finite-dimensional subspace over a complete field is
closed
* `finite_dimensional.proper` : a finite-dimensional space over a proper field is proper. This
is not registered as an instance, as the field would be an unknown metavariable in typeclass
resolution. It is however registered as an instance for `𝕜 = ℝ` and `𝕜 = ℂ`. As properness
implies completeness, there is no need to also register `finite_dimensional.complete` on `ℝ` or
`ℂ`.
## Implementation notes
The fact that all norms are equivalent is not written explicitly, as it would mean having two norms
on a single space, which is not the way type classes work. However, if one has a
finite-dimensional vector space `E` with a norm, and a copy `E'` of this type with another norm,
then the identities from `E` to `E'` and from `E'`to `E` are continuous thanks to
`linear_map.continuous_of_finite_dimensional`. This gives the desired norm equivalence.
-/
universes u v w x
open set finite_dimensional topological_space
open_locale classical big_operators
noncomputable theory
/-- A linear map on `ι → 𝕜` (where `ι` is a fintype) is continuous -/
lemma linear_map.continuous_on_pi {ι : Type w} [fintype ι] {𝕜 : Type u} [normed_field 𝕜]
{E : Type v} [add_comm_group E] [vector_space 𝕜 E] [topological_space E]
[topological_add_group E] [has_continuous_smul 𝕜 E] (f : (ι → 𝕜) →ₗ[𝕜] E) : continuous f :=
begin
-- for the proof, write `f` in the standard basis, and use that each coordinate is a continuous
-- function.
have : (f : (ι → 𝕜) → E) =
(λx, ∑ i : ι, x i • (f (λj, if i = j then 1 else 0))),
by { ext x, exact f.pi_apply_eq_sum_univ x },
rw this,
refine continuous_finset_sum _ (λi hi, _),
exact (continuous_apply i).smul continuous_const
end
section complete_field
variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜]
{E : Type v} [normed_group E] [normed_space 𝕜 E]
{F : Type w} [normed_group F] [normed_space 𝕜 F]
{F' : Type x} [add_comm_group F'] [vector_space 𝕜 F'] [topological_space F']
[topological_add_group F'] [has_continuous_smul 𝕜 F']
[complete_space 𝕜]
/-- In finite dimension over a complete field, the canonical identification (in terms of a basis)
with `𝕜^n` together with its sup norm is continuous. This is the nontrivial part in the fact that
all norms are equivalent in finite dimension.
This statement is superceded by the fact that every linear map on a finite-dimensional space is
continuous, in `linear_map.continuous_of_finite_dimensional`. -/
lemma continuous_equiv_fun_basis {ι : Type v} [fintype ι] (ξ : ι → E) (hξ : is_basis 𝕜 ξ) :
continuous hξ.equiv_fun :=
begin
unfreezingI { induction hn : fintype.card ι with n IH generalizing ι E },
{ apply linear_map.continuous_of_bound _ 0 (λx, _),
have : hξ.equiv_fun x = 0,
by { ext i, exact (fintype.card_eq_zero_iff.1 hn i).elim },
change ∥hξ.equiv_fun x∥ ≤ 0 * ∥x∥,
rw this,
simp [norm_nonneg] },
{ haveI : finite_dimensional 𝕜 E := of_fintype_basis hξ,
-- first step: thanks to the inductive assumption, any n-dimensional subspace is equivalent
-- to a standard space of dimension n, hence it is complete and therefore closed.
have H₁ : ∀s : submodule 𝕜 E, findim 𝕜 s = n → is_closed (s : set E),
{ assume s s_dim,
rcases exists_is_basis_finite 𝕜 s with ⟨b, b_basis, b_finite⟩,
letI : fintype b := finite.fintype b_finite,
have U : uniform_embedding b_basis.equiv_fun.symm.to_equiv,
{ have : fintype.card b = n,
by { rw ← s_dim, exact (findim_eq_card_basis b_basis).symm },
have : continuous b_basis.equiv_fun := IH (subtype.val : b → s) b_basis this,
exact b_basis.equiv_fun.symm.uniform_embedding (linear_map.continuous_on_pi _) this },
have : is_complete (s : set E),
from complete_space_coe_iff_is_complete.1 ((complete_space_congr U).1 (by apply_instance)),
exact this.is_closed },
-- second step: any linear form is continuous, as its kernel is closed by the first step
have H₂ : ∀f : E →ₗ[𝕜] 𝕜, continuous f,
{ assume f,
have : findim 𝕜 f.ker = n ∨ findim 𝕜 f.ker = n.succ,
{ have Z := f.findim_range_add_findim_ker,
rw [findim_eq_card_basis hξ, hn] at Z,
by_cases H : findim 𝕜 f.range = 0,
{ right,
rw H at Z,
simpa using Z },
{ left,
have : findim 𝕜 f.range = 1,
{ refine le_antisymm _ (zero_lt_iff.mpr H),
simpa [findim_of_field] using f.range.findim_le },
rw [this, add_comm, nat.add_one] at Z,
exact nat.succ.inj Z } },
have : is_closed (f.ker : set E),
{ cases this,
{ exact H₁ _ this },
{ have : f.ker = ⊤,
by { apply eq_top_of_findim_eq, rw [findim_eq_card_basis hξ, hn, this] },
simp [this] } },
exact linear_map.continuous_iff_is_closed_ker.2 this },
-- third step: applying the continuity to the linear form corresponding to a coefficient in the
-- basis decomposition, deduce that all such coefficients are controlled in terms of the norm
have : ∀i:ι, ∃C, 0 ≤ C ∧ ∀(x:E), ∥hξ.equiv_fun x i∥ ≤ C * ∥x∥,
{ assume i,
let f : E →ₗ[𝕜] 𝕜 := (linear_map.proj i).comp hξ.equiv_fun,
let f' : E →L[𝕜] 𝕜 := { cont := H₂ f, ..f },
exact ⟨∥f'∥, norm_nonneg _, λx, continuous_linear_map.le_op_norm f' x⟩ },
-- fourth step: combine the bound on each coefficient to get a global bound and the continuity
choose C0 hC0 using this,
let C := ∑ i, C0 i,
have C_nonneg : 0 ≤ C := finset.sum_nonneg (λi hi, (hC0 i).1),
have C0_le : ∀i, C0 i ≤ C :=
λi, finset.single_le_sum (λj hj, (hC0 j).1) (finset.mem_univ _),
apply linear_map.continuous_of_bound _ C (λx, _),
rw pi_norm_le_iff,
{ exact λi, le_trans ((hC0 i).2 x) (mul_le_mul_of_nonneg_right (C0_le i) (norm_nonneg _)) },
{ exact mul_nonneg C_nonneg (norm_nonneg _) } }
end
/-- Any linear map on a finite dimensional space over a complete field is continuous. -/
theorem linear_map.continuous_of_finite_dimensional [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F') :
continuous f :=
begin
-- for the proof, go to a model vector space `b → 𝕜` thanks to `continuous_equiv_fun_basis`, and
-- argue that all linear maps there are continuous.
rcases exists_is_basis_finite 𝕜 E with ⟨b, b_basis, b_finite⟩,
letI : fintype b := finite.fintype b_finite,
have A : continuous b_basis.equiv_fun :=
continuous_equiv_fun_basis _ b_basis,
have B : continuous (f.comp (b_basis.equiv_fun.symm : (b → 𝕜) →ₗ[𝕜] E)) :=
linear_map.continuous_on_pi _,
have : continuous ((f.comp (b_basis.equiv_fun.symm : (b → 𝕜) →ₗ[𝕜] E))
∘ b_basis.equiv_fun) := B.comp A,
convert this,
ext x,
dsimp,
rw linear_equiv.symm_apply_apply
end
theorem affine_map.continuous_of_finite_dimensional {PE PF : Type*}
[metric_space PE] [normed_add_torsor E PE] [metric_space PF] [normed_add_torsor F PF]
[finite_dimensional 𝕜 E] (f : PE →ᵃ[𝕜] PF) : continuous f :=
affine_map.continuous_linear_iff.1 f.linear.continuous_of_finite_dimensional
namespace linear_map
variables [finite_dimensional 𝕜 E]
/-- The continuous linear map induced by a linear map on a finite dimensional space -/
def to_continuous_linear_map : (E →ₗ[𝕜] F') ≃ₗ[𝕜] E →L[𝕜] F' :=
{ to_fun := λ f, ⟨f, f.continuous_of_finite_dimensional⟩,
inv_fun := coe,
map_add' := λ f g, rfl,
map_smul' := λ c f, rfl,
left_inv := λ f, rfl,
right_inv := λ f, continuous_linear_map.coe_injective rfl }
@[simp] lemma coe_to_continuous_linear_map' (f : E →ₗ[𝕜] F') :
⇑f.to_continuous_linear_map = f := rfl
@[simp] lemma coe_to_continuous_linear_map (f : E →ₗ[𝕜] F') :
(f.to_continuous_linear_map : E →ₗ[𝕜] F') = f := rfl
@[simp] lemma coe_to_continuous_linear_map_symm :
⇑(to_continuous_linear_map : (E →ₗ[𝕜] F') ≃ₗ[𝕜] E →L[𝕜] F').symm = coe := rfl
end linear_map
/-- The continuous linear equivalence induced by a linear equivalence on a finite dimensional
space. -/
def linear_equiv.to_continuous_linear_equiv [finite_dimensional 𝕜 E] (e : E ≃ₗ[𝕜] F) : E ≃L[𝕜] F :=
{ continuous_to_fun := e.to_linear_map.continuous_of_finite_dimensional,
continuous_inv_fun := begin
haveI : finite_dimensional 𝕜 F := e.finite_dimensional,
exact e.symm.to_linear_map.continuous_of_finite_dimensional
end,
..e }
/-- Two finite-dimensional normed spaces are continuously linearly equivalent if they have the same
(finite) dimension. -/
theorem finite_dimensional.nonempty_continuous_linear_equiv_of_findim_eq
[finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] (cond : findim 𝕜 E = findim 𝕜 F) :
nonempty (E ≃L[𝕜] F) :=
(nonempty_linear_equiv_of_findim_eq cond).map linear_equiv.to_continuous_linear_equiv
/-- Two finite-dimensional normed spaces are continuously linearly equivalent if and only if they
have the same (finite) dimension. -/
theorem finite_dimensional.nonempty_continuous_linear_equiv_iff_findim_eq
[finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] :
nonempty (E ≃L[𝕜] F) ↔ findim 𝕜 E = findim 𝕜 F :=
⟨ λ ⟨h⟩, h.to_linear_equiv.findim_eq,
λ h, finite_dimensional.nonempty_continuous_linear_equiv_of_findim_eq h ⟩
/-- A continuous linear equivalence between two finite-dimensional normed spaces of the same
(finite) dimension. -/
def continuous_linear_equiv.of_findim_eq [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F]
(cond : findim 𝕜 E = findim 𝕜 F) :
E ≃L[𝕜] F :=
(linear_equiv.of_findim_eq E F cond).to_continuous_linear_equiv
variables {ι : Type*} [fintype ι]
/-- Construct a continuous linear map given the value at a finite basis. -/
def is_basis.constrL {v : ι → E} (hv : is_basis 𝕜 v) (f : ι → F) :
E →L[𝕜] F :=
by haveI : finite_dimensional 𝕜 E := finite_dimensional.of_fintype_basis hv;
exact (hv.constr f).to_continuous_linear_map
@[simp, norm_cast] lemma is_basis.coe_constrL {v : ι → E} (hv : is_basis 𝕜 v) (f : ι → F) :
(hv.constrL f : E →ₗ[𝕜] F) = hv.constr f := rfl
/-- The continuous linear equivalence between a vector space over `𝕜` with a finite basis and
functions from its basis indexing type to `𝕜`. -/
def is_basis.equiv_funL {v : ι → E} (hv : is_basis 𝕜 v) : E ≃L[𝕜] (ι → 𝕜) :=
{ continuous_to_fun := begin
haveI : finite_dimensional 𝕜 E := finite_dimensional.of_fintype_basis hv,
apply linear_map.continuous_of_finite_dimensional,
end,
continuous_inv_fun := begin
change continuous hv.equiv_fun.symm.to_fun,
apply linear_map.continuous_of_finite_dimensional,
end,
..hv.equiv_fun }
@[simp] lemma is_basis.constrL_apply {v : ι → E} (hv : is_basis 𝕜 v) (f : ι → F) (e : E) :
(hv.constrL f) e = ∑ i, (hv.equiv_fun e i) • f i :=
hv.constr_apply_fintype _ _
@[simp] lemma is_basis.constrL_basis {v : ι → E} (hv : is_basis 𝕜 v) (f : ι → F) (i : ι) :
(hv.constrL f) (v i) = f i :=
constr_basis _
lemma is_basis.sup_norm_le_norm {v : ι → E} (hv : is_basis 𝕜 v) :
∃ C > (0 : ℝ), ∀ e : E, ∑ i, ∥hv.equiv_fun e i∥ ≤ C * ∥e∥ :=
begin
set φ := hv.equiv_funL.to_continuous_linear_map,
set C := ∥φ∥ * (fintype.card ι),
use [max C 1, lt_of_lt_of_le (zero_lt_one) (le_max_right C 1)],
intros e,
calc ∑ i, ∥φ e i∥ ≤ ∑ i : ι, ∥φ e∥ : by { apply finset.sum_le_sum,
exact λ i hi, norm_le_pi_norm (φ e) i }
... = ∥φ e∥*(fintype.card ι) : by simpa only [mul_comm, finset.sum_const, nsmul_eq_mul]
... ≤ ∥φ∥ * ∥e∥ * (fintype.card ι) : mul_le_mul_of_nonneg_right (φ.le_op_norm e)
(fintype.card ι).cast_nonneg
... = ∥φ∥ * (fintype.card ι) * ∥e∥ : by ring
... ≤ max C 1 * ∥e∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _)
end
lemma is_basis.op_norm_le {ι : Type*} [fintype ι] {v : ι → E} (hv : is_basis 𝕜 v) :
∃ C > (0 : ℝ), ∀ {u : E →L[𝕜] F} {M : ℝ}, 0 ≤ M → (∀ i, ∥u (v i)∥ ≤ M) → ∥u∥ ≤ C*M :=
begin
obtain ⟨C, C_pos, hC⟩ : ∃ C > (0 : ℝ), ∀ (e : E), ∑ i, ∥hv.equiv_fun e i∥ ≤ C * ∥e∥,
from hv.sup_norm_le_norm,
use [C, C_pos],
intros u M hM hu,
apply u.op_norm_le_bound (mul_nonneg (le_of_lt C_pos) hM),
intros e,
calc
∥u e∥ = ∥u (∑ i, hv.equiv_fun e i • v i)∥ : by conv_lhs { rw ← hv.equiv_fun_total e }
... = ∥∑ i, (hv.equiv_fun e i) • (u $ v i)∥ : by simp [u.map_sum, linear_map.map_smul]
... ≤ ∑ i, ∥(hv.equiv_fun e i) • (u $ v i)∥ : norm_sum_le _ _
... = ∑ i, ∥hv.equiv_fun e i∥ * ∥u (v i)∥ : by simp only [norm_smul]
... ≤ ∑ i, ∥hv.equiv_fun e i∥ * M : finset.sum_le_sum (λ i hi,
mul_le_mul_of_nonneg_left (hu i) (norm_nonneg _))
... = (∑ i, ∥hv.equiv_fun e i∥) * M : finset.sum_mul.symm
... ≤ C * ∥e∥ * M : mul_le_mul_of_nonneg_right (hC e) hM
... = C * M * ∥e∥ : by ring
end
instance [finite_dimensional 𝕜 E] [second_countable_topology F] :
second_countable_topology (E →L[𝕜] F) :=
begin
set d := finite_dimensional.findim 𝕜 E,
suffices :
∀ ε > (0 : ℝ), ∃ n : (E →L[𝕜] F) → fin d → ℕ, ∀ (f g : E →L[𝕜] F), n f = n g → dist f g ≤ ε,
from metric.second_countable_of_countable_discretization
(λ ε ε_pos, ⟨fin d → ℕ, by apply_instance, this ε ε_pos⟩),
intros ε ε_pos,
obtain ⟨u : ℕ → F, hu : dense_range u⟩ := exists_dense_seq F,
obtain ⟨v : fin d → E, hv : is_basis 𝕜 v⟩ := finite_dimensional.fin_basis 𝕜 E,
obtain ⟨C : ℝ, C_pos : 0 < C,
hC : ∀ {φ : E →L[𝕜] F} {M : ℝ}, 0 ≤ M → (∀ i, ∥φ (v i)∥ ≤ M) → ∥φ∥ ≤ C * M⟩ :=
hv.op_norm_le,
have h_2C : 0 < 2*C := mul_pos zero_lt_two C_pos,
have hε2C : 0 < ε/(2*C) := div_pos ε_pos h_2C,
have : ∀ φ : E →L[𝕜] F, ∃ n : fin d → ℕ, ∥φ - (hv.constrL $ u ∘ n)∥ ≤ ε/2,
{ intros φ,
have : ∀ i, ∃ n, ∥φ (v i) - u n∥ ≤ ε/(2*C),
{ simp only [norm_sub_rev],
intro i,
have : φ (v i) ∈ closure (range u) := hu _,
obtain ⟨n, hn⟩ : ∃ n, ∥u n - φ (v i)∥ < ε / (2 * C),
{ rw mem_closure_iff_nhds_basis metric.nhds_basis_ball at this,
specialize this (ε/(2*C)) hε2C,
simpa [dist_eq_norm] },
exact ⟨n, le_of_lt hn⟩ },
choose n hn using this,
use n,
replace hn : ∀ i : fin d, ∥(φ - (hv.constrL $ u ∘ n)) (v i)∥ ≤ ε / (2 * C), by simp [hn],
have : C * (ε / (2 * C)) = ε/2,
{ rw [eq_div_iff (two_ne_zero : (2 : ℝ) ≠ 0), mul_comm, ← mul_assoc,
mul_div_cancel' _ (ne_of_gt h_2C)] },
specialize hC (le_of_lt hε2C) hn,
rwa this at hC },
choose n hn using this,
set Φ := λ φ : E →L[𝕜] F, (hv.constrL $ u ∘ (n φ)),
change ∀ z, dist z (Φ z) ≤ ε/2 at hn,
use n,
intros x y hxy,
calc dist x y ≤ dist x (Φ x) + dist (Φ x) y : dist_triangle _ _ _
... = dist x (Φ x) + dist y (Φ y) : by simp [Φ, hxy, dist_comm]
... ≤ ε : by linarith [hn x, hn y]
end
/-- Any finite-dimensional vector space over a complete field is complete.
We do not register this as an instance to avoid an instance loop when trying to prove the
completeness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance
explicitly when needed. -/
variables (𝕜 E)
lemma finite_dimensional.complete [finite_dimensional 𝕜 E] : complete_space E :=
begin
set e := continuous_linear_equiv.of_findim_eq (@findim_fin_fun 𝕜 _ (findim 𝕜 E)).symm,
have : uniform_embedding e.to_linear_equiv.to_equiv.symm := e.symm.uniform_embedding,
exact (complete_space_congr this).1 (by apply_instance)
end
variables {𝕜 E}
/-- A finite-dimensional subspace is complete. -/
lemma submodule.complete_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] :
is_complete (s : set E) :=
complete_space_coe_iff_is_complete.1 (finite_dimensional.complete 𝕜 s)
/-- A finite-dimensional subspace is closed. -/
lemma submodule.closed_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] :
is_closed (s : set E) :=
s.complete_of_finite_dimensional.is_closed
lemma continuous_linear_map.exists_right_inverse_of_surjective [finite_dimensional 𝕜 F]
(f : E →L[𝕜] F) (hf : f.range = ⊤) :
∃ g : F →L[𝕜] E, f.comp g = continuous_linear_map.id 𝕜 F :=
let ⟨g, hg⟩ := (f : E →ₗ[𝕜] F).exists_right_inverse_of_surjective hf in
⟨g.to_continuous_linear_map, continuous_linear_map.ext $ linear_map.ext_iff.1 hg⟩
lemma closed_embedding_smul_left {c : E} (hc : c ≠ 0) : closed_embedding (λ x : 𝕜, x • c) :=
begin
haveI : finite_dimensional 𝕜 (submodule.span 𝕜 {c}) :=
finite_dimensional.span_of_finite 𝕜 (finite_singleton c),
have m1 : closed_embedding (coe : submodule.span 𝕜 {c} → E) :=
(submodule.span 𝕜 {c}).closed_of_finite_dimensional.closed_embedding_subtype_coe,
have m2 : closed_embedding
(linear_equiv.to_span_nonzero_singleton 𝕜 E c hc : 𝕜 → submodule.span 𝕜 {c}) :=
(continuous_linear_equiv.to_span_nonzero_singleton 𝕜 c hc).to_homeomorph.closed_embedding,
exact m1.comp m2
end
/- `smul` is a closed map in the first argument. -/
lemma is_closed_map_smul_left (c : E) : is_closed_map (λ x : 𝕜, x • c) :=
begin
by_cases hc : c = 0,
{ simp_rw [hc, smul_zero], exact is_closed_map_const },
{ exact (closed_embedding_smul_left hc).is_closed_map }
end
end complete_field
section proper_field
variables (𝕜 : Type u) [nondiscrete_normed_field 𝕜]
(E : Type v) [normed_group E] [normed_space 𝕜 E] [proper_space 𝕜]
/-- Any finite-dimensional vector space over a proper field is proper.
We do not register this as an instance to avoid an instance loop when trying to prove the
properness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance
explicitly when needed. -/
lemma finite_dimensional.proper [finite_dimensional 𝕜 E] : proper_space E :=
begin
set e := continuous_linear_equiv.of_findim_eq (@findim_fin_fun 𝕜 _ (findim 𝕜 E)).symm,
exact e.symm.antilipschitz.proper_space e.symm.continuous e.symm.surjective
end
end proper_field
/- Over the real numbers, we can register the previous statement as an instance as it will not
cause problems in instance resolution since the properness of `ℝ` is already known. -/
instance finite_dimensional.proper_real
(E : Type u) [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] : proper_space E :=
finite_dimensional.proper ℝ E
attribute [instance, priority 900] finite_dimensional.proper_real
/-- In a finite dimensional vector space over `ℝ`, the series `∑ x, ∥f x∥` is unconditionally
summable if and only if the series `∑ x, f x` is unconditionally summable. One implication holds in
any complete normed space, while the other holds only in finite dimensional spaces. -/
lemma summable_norm_iff {α E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E]
{f : α → E} : summable (λ x, ∥f x∥) ↔ summable f :=
begin
refine ⟨summable_of_summable_norm, λ hf, _⟩,
-- First we use a finite basis to reduce the problem to the case `E = fin N → ℝ`
suffices : ∀ {N : ℕ} {g : α → fin N → ℝ}, summable g → summable (λ x, ∥g x∥),
{ rcases fin_basis ℝ E with ⟨v, hv⟩,
set e := hv.equiv_funL,
have : summable (λ x, ∥e (f x)∥) := this (e.summable.2 hf),
refine summable_of_norm_bounded _ (this.mul_left
↑(nnnorm (e.symm : (fin (findim ℝ E) → ℝ) →L[ℝ] E))) (λ i, _),
simpa using (e.symm : (fin (findim ℝ E) → ℝ) →L[ℝ] E).le_op_norm (e $ f i) },
unfreezingI { clear_dependent E },
-- Now we deal with `g : α → fin N → ℝ`
intros N g hg,
have : ∀ i, summable (λ x, ∥g x i∥) := λ i, (pi.summable.1 hg i).abs,
refine summable_of_norm_bounded _ (summable_sum (λ i (hi : i ∈ finset.univ), this i)) (λ x, _),
rw [norm_norm, pi_norm_le_iff],
{ refine λ i, finset.single_le_sum (λ i hi, _) (finset.mem_univ i),
exact norm_nonneg (g x i) },
{ exact finset.sum_nonneg (λ _ _, norm_nonneg _) }
end
|
a00dd20ef0bea6362e8eefc47c81514af3e0e16c | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/playground/parser/parser.lean | ed89a833a54e17229a623b83a37c860d55f8ea7e | [
"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 | 32,496 | lean | import init.lean.name init.lean.parser.trie init.lean.parser.identifier
import syntax filemap
open Lean
export Lean.Parser (Trie)
-- namespace Lean
namespace Parser
/-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/
def TokenMap (α : Type) := RBMap Name (List α) Name.quickLt
namespace TokenMap
def insert {α : Type} (map : TokenMap α) (k : Name) (v : α) : TokenMap α :=
match map.find k with
| none := map.insert k [v]
| some vs := map.insert k (v::vs)
def ofListAux {α : Type} : List (Name × α) → TokenMap α → TokenMap α
| [] m := m
| (⟨k,v⟩::xs) m := ofListAux xs (m.insert k v)
def ofList {α : Type} (es : List (Name × α)) : TokenMap α :=
ofListAux es RBMap.empty
end TokenMap
structure FrontendConfig :=
(filename : String)
(input : String)
(fileMap : FileMap)
structure TokenConfig :=
(val : String)
(lbp : Nat := 0)
namespace TokenConfig
def beq : TokenConfig → TokenConfig → Bool
| ⟨val₁, lbp₁⟩ ⟨val₂, lbp₂⟩ := val₁ == val₂ && lbp₁ == lbp₂
instance : BEq TokenConfig :=
⟨beq⟩
end TokenConfig
structure TokenCacheEntry :=
(startPos stopPos : String.Pos)
(token : Syntax)
structure ParserCache :=
(tokenCache : Option TokenCacheEntry := none)
structure ParserConfig extends FrontendConfig :=
(tokens : Trie TokenConfig)
structure ParserData :=
(stxStack : Array Syntax) (pos : String.Pos) (cache : ParserCache) (errorMsg : Option String)
@[inline] def ParserData.hasError (d : ParserData) : Bool :=
d.errorMsg != none
@[inline] def ParserData.stackSize (d : ParserData) : Nat :=
d.stxStack.size
def ParserData.restore (d : ParserData) (iniStackSz : Nat) (iniPos : Nat) : ParserData :=
{ stxStack := d.stxStack.shrink iniStackSz, errorMsg := none, pos := iniPos, .. d}
def ParserData.setPos (d : ParserData) (pos : Nat) : ParserData :=
{ pos := pos, .. d }
def ParserData.setCache (d : ParserData) (cache : ParserCache) : ParserData :=
{ cache := cache, .. d }
def ParserData.pushSyntax (d : ParserData) (n : Syntax) : ParserData :=
{ stxStack := d.stxStack.push n, .. d }
def ParserData.shrinkStack (d : ParserData) (iniStackSz : Nat) : ParserData :=
{ stxStack := d.stxStack.shrink iniStackSz, .. d }
def ParserData.next (d : ParserData) (s : String) (pos : Nat) : ParserData :=
{ pos := s.next pos, .. d }
def ParserData.toErrorMsg (d : ParserData) (cfg : ParserConfig) : String :=
match d.errorMsg with
| none := ""
| some msg :=
let pos := cfg.fileMap.toPosition d.pos in
cfg.filename ++ ":" ++ toString pos.line ++ ":" ++ toString pos.column ++ " " ++ msg
def ParserFn := String → ParserData → ParserData
instance : Inhabited ParserFn :=
⟨λ s, id⟩
structure ParserInfo :=
(updateTokens : Trie TokenConfig → Trie TokenConfig := λ tks, tks)
(firstTokens : List TokenConfig := [])
@[inline] def andthenFn (p q : ParserFn) : ParserFn
| s d :=
let d := p s d in
if d.hasError then d else q s d
@[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo :=
{ updateTokens := q.updateTokens ∘ p.updateTokens,
firstTokens := p.firstTokens }
def ParserData.mkNode (d : ParserData) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserData :=
match d with
| ⟨stack, pos, cache, err⟩ :=
if err != none && stack.size == iniStackSz then
-- If there is an error but there are no new nodes on the stack, we just return `d`
d
else
let newNode := Syntax.node k (stack.extract iniStackSz stack.size) [] in
let stack := stack.shrink iniStackSz in
let stack := stack.push newNode in
⟨stack, pos, cache, err⟩
@[inline] def nodeFn (k : SyntaxNodeKind) (p : ParserFn) : ParserFn
| s d :=
let iniSz := d.stackSize in
let d := p s d in
d.mkNode k iniSz
@[noinline] def nodeInfo (p : ParserInfo) : ParserInfo :=
{ updateTokens := p.updateTokens,
firstTokens := p.firstTokens }
@[inline] def orelseFn (p q : ParserFn) : ParserFn
| s d :=
let iniSz := d.stackSize in
let iniPos := d.pos in
let d := p s d in
if d.hasError && d.pos == iniPos then q s (d.restore iniSz iniPos) else d
@[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo :=
{ updateTokens := q.updateTokens ∘ p.updateTokens,
firstTokens := p.firstTokens ++ q.firstTokens }
@[inline] def tryFn (p : ParserFn) : ParserFn
| s d :=
let iniSz := d.stackSize in
let iniPos := d.pos in
match p s d with
| ⟨stack, _, cache, some msg⟩ := ⟨stack.shrink iniSz, iniPos, cache, some msg⟩
| other := other
@[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo :=
{ updateTokens := info.updateTokens,
firstTokens := [] }
@[inline] def optionalFn (p : ParserFn) : ParserFn :=
λ s d,
let iniSz := d.stackSize in
let iniPos := d.pos in
let d := p s d in
let d := if d.hasError then d.restore iniSz iniPos else d in
d.mkNode nullKind iniSz
def ParserData.mkError (d : ParserData) (msg : String) : ParserData :=
match d with
| ⟨stack, pos, cache, _⟩ := ⟨stack, pos, cache, some msg⟩
def ParserData.mkEOIError (d : ParserData) : ParserData :=
d.mkError "end of input"
def ParserData.mkErrorAt (d : ParserData) (msg : String) (pos : String.Pos) : ParserData :=
match d with
| ⟨stack, _, cache, _⟩ := ⟨stack, pos, cache, some msg⟩
@[specialize] partial def manyAux (p : ParserFn) : String → ParserData → ParserData
| s d :=
let iniSz := d.stackSize in
let iniPos := d.pos in
let d := p s d in
if d.hasError then d.restore iniSz iniPos
else if iniPos == d.pos then d.mkError "invalid 'many' parser combinator application, parser did not consume anything"
else manyAux s d
@[inline] def manyFn (p : ParserFn) : ParserFn
| s d :=
let iniSz := d.stackSize in
let d := manyAux p s d in
d.mkNode nullKind iniSz
@[specialize] private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool) (iniSz : Nat) : Bool → ParserFn
| pOpt s d :=
let sz := d.stackSize in
let pos := d.pos in
let d := p s d in
if d.hasError then
let d := d.restore sz pos in
if pOpt then
d.mkNode nullKind iniSz
else
-- append `Syntax.missing` to make clear that List is incomplete
let d := d.pushSyntax Syntax.missing in
d.mkNode nullKind iniSz
else
let sz := d.stackSize in
let pos := d.pos in
let d := sep s d in
if d.hasError then
let d := d.restore sz pos in
d.mkNode nullKind iniSz
else
sepByFnAux allowTrailingSep s d
@[specialize] def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn
| s d :=
let iniSz := d.stackSize in
sepByFnAux p sep allowTrailingSep iniSz true s d
@[specialize] def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn
| s d :=
let iniSz := d.stackSize in
sepByFnAux p sep allowTrailingSep iniSz false s d
@[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo :=
{ updateTokens := sep.updateTokens ∘ p.updateTokens,
firstTokens := [] }
@[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo :=
{ updateTokens := sep.updateTokens ∘ p.updateTokens,
firstTokens := p.firstTokens }
@[specialize] partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : ParserFn
| s d :=
let i := d.pos in
if s.atEnd i then d.mkEOIError
else
let c := s.get i in
if p c then d.next s i
else d.mkError errorMsg
@[specialize] partial def takeUntilFn (p : Char → Bool) : ParserFn
| s d :=
let i := d.pos in
if s.atEnd i then d
else
let c := s.get i in
if p c then d
else takeUntilFn s (d.next s i)
@[specialize] def takeWhileFn (p : Char → Bool) : ParserFn :=
takeUntilFn (λ c, !p c)
@[inline] def takeWhile1Fn (p : Char → Bool) (errorMsg : String) : ParserFn :=
andthenFn (satisfyFn p errorMsg) (takeWhileFn p)
partial def finishCommentBlock : Nat → ParserFn
| nesting s d :=
let i := d.pos in
if s.atEnd i then d.mkEOIError
else
let c := s.get i in
let i := s.next i in
if c == '-' then
if s.atEnd i then d.mkEOIError
else
let c := s.get i in
if c == '/' then -- "-/" end of comment
if nesting == 1 then d.next s i
else finishCommentBlock (nesting-1) s (d.next s i)
else
finishCommentBlock nesting s (d.next s i)
else if c == '/' then
if s.atEnd i then d.mkEOIError
else
let c := s.get i in
if c == '-' then finishCommentBlock (nesting+1) s (d.next s i)
else finishCommentBlock nesting s (d.setPos i)
else finishCommentBlock nesting s (d.setPos i)
/- Consume whitespace and comments -/
partial def whitespace : ParserFn
| s d :=
let i := d.pos in
if s.atEnd i then d
else
let c := s.get i in
if c.isWhitespace then whitespace s (d.next s i)
else if c == '-' then
let i := s.next i in
let c := s.get i in
if c == '-' then andthenFn (takeUntilFn (= '\n')) whitespace s (d.next s i)
else d
else if c == '/' then
let i := s.next i in
let c := s.get i in
if c == '-' then
let i := s.next i in
let c := s.get i in
if c == '-' then d -- "/--" doc comment is an actual token
else andthenFn (finishCommentBlock 1) whitespace s (d.next s i)
else d
else d
def mkEmptySubstringAt (s : String) (p : Nat) : Substring :=
{str := s, startPos := p, stopPos := p }
private def rawAux (startPos : Nat) (trailingWs : Bool) : ParserFn
| s d :=
let stopPos := d.pos in
let leading := mkEmptySubstringAt s startPos in
let val := s.extract startPos stopPos in
if trailingWs then
let d := whitespace s d in
let stopPos' := d.pos in
let trailing : Substring := { str := s, startPos := stopPos, stopPos := stopPos' } in
let atom := Syntax.atom (some { leading := leading, pos := startPos, trailing := trailing }) val in
d.pushSyntax atom
else
let trailing := mkEmptySubstringAt s stopPos in
let atom := Syntax.atom (some { leading := leading, pos := startPos, trailing := trailing }) val in
d.pushSyntax atom
/-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/
@[inline] def rawFn (p : ParserFn) (trailingWs := false) : ParserFn
| s d :=
let startPos := d.pos in
let d := p s d in
if d.hasError then d else rawAux startPos trailingWs s d
def hexDigitFn : ParserFn
| s d :=
let i := d.pos in
if s.atEnd i then d.mkEOIError
else
let c := s.get i in
let i := s.next i in
if c.isDigit || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F') then d.setPos i
else d.mkError "invalid hexadecimal numeral, hexadecimal digit expected"
def quotedCharFn : ParserFn
| s d :=
let i := d.pos in
if s.atEnd i then d.mkEOIError
else
let c := s.get i in
if c == '\\' || c == '\"' || c == '\'' || c == '\n' || c == '\t' then
d.next s i
else if c == 'x' then
andthenFn hexDigitFn hexDigitFn s (d.next s i)
else if c == 'u' then
andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) s (d.next s i)
else
d.mkError "invalid escape sequence"
def mkStrLitKind : IO SyntaxNodeKind := nextKind `strLit
@[init mkStrLitKind] constant strLitKind : SyntaxNodeKind := default _
/-- Push `(Syntax.node tk <new-atom>)` into syntax stack -/
def mkNodeToken (k : SyntaxNodeKind) (startPos : Nat) (s : String) (d : ParserData) : ParserData :=
let stopPos := d.pos in
let leading := mkEmptySubstringAt s startPos in
let val := s.extract startPos stopPos in
let d := whitespace s d in
let wsStopPos := d.pos in
let trailing := { Substring . str := s, startPos := stopPos, stopPos := wsStopPos } in
let atom := Syntax.atom (some { leading := leading, pos := startPos, trailing := trailing }) val in
let tk := Syntax.node k (Array.singleton atom) [] in
d.pushSyntax tk
partial def strLitFnAux (startPos : Nat) : ParserFn
| s d :=
let i := d.pos in
if s.atEnd i then d.mkEOIError
else
let c := s.get i in
let d := d.setPos (s.next i) in
if c == '\"' then
mkNodeToken strLitKind startPos s d
else if c == '\\' then andthenFn quotedCharFn strLitFnAux s d
else strLitFnAux s d
def mkNumberKind : IO SyntaxNodeKind := nextKind `number
@[init mkNumberKind] constant numberKind : SyntaxNodeKind := default _
def decimalNumberFn (startPos : Nat) : ParserFn
| s d :=
let d := takeWhileFn (λ c, c.isDigit) s d in
let i := d.pos in
let c := s.get i in
let d :=
if c == '.' then
let i := s.next i in
let c := s.get i in
if c.isDigit then
takeWhileFn (λ c, c.isDigit) s (d.setPos i)
else
d
else
d in
mkNodeToken numberKind startPos s d
def binNumberFn (startPos : Nat) : ParserFn
| s d :=
let d := takeWhile1Fn (λ c, c == '0' || c == '1') "expected binary number" s d in
mkNodeToken numberKind startPos s d
def octalNumberFn (startPos : Nat) : ParserFn
| s d :=
let d := takeWhile1Fn (λ c, '0' ≤ c && c ≤ '7') "expected octal number" s d in
mkNodeToken numberKind startPos s d
def hexNumberFn (startPos : Nat) : ParserFn
| s d :=
let d := takeWhile1Fn (λ c, ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "expected hexadecimal number" s d in
mkNodeToken numberKind startPos s d
def numberFnAux : ParserFn
| s d :=
let startPos := d.pos in
if s.atEnd startPos then d.mkEOIError
else
let c := s.get startPos in
if c == '0' then
let i := s.next startPos in
let c := s.get i in
if c == 'b' || c == 'B' then
binNumberFn startPos s (d.next s i)
else if c == 'o' || c == 'O' then
octalNumberFn startPos s (d.next s i)
else if c == 'x' || c == 'X' then
hexNumberFn startPos s (d.next s i)
else
decimalNumberFn startPos s (d.setPos i)
else if c.isDigit then
decimalNumberFn startPos s (d.next s startPos)
else
d.mkError "expected numeral"
def isIdCont : String → ParserData → Bool
| s d :=
let i := d.pos in
let c := s.get i in
if c == '.' then
let i := s.next i in
if s.atEnd i then
false
else
let c := s.get i in
isIdFirst c || isIdBeginEscape c
else
false
private def isToken (idStartPos idStopPos : Nat) (tk : Option TokenConfig) : Bool :=
match tk with
| none := false
| some tk :=
-- if a token is both a symbol and a valid identifier (i.e. a keyword),
-- we want it to be recognized as a symbol
tk.val.bsize ≥ idStopPos - idStopPos
def mkTokenAndFixPos (startPos : Nat) (tk : Option TokenConfig) (s : String) (d : ParserData) : ParserData :=
match tk with
| none := d.mkErrorAt "token expected" startPos
| some tk :=
let leading := mkEmptySubstringAt s startPos in
let val := tk.val in
let stopPos := startPos + val.bsize in
let d := d.setPos stopPos in
let d := whitespace s d in
let wsStopPos := d.pos in
let trailing := { Substring . str := s, startPos := stopPos, stopPos := wsStopPos } in
let atom := Syntax.atom (some { leading := leading, pos := startPos, trailing := trailing }) val in
d.pushSyntax atom
def mkIdResult (startPos : Nat) (tk : Option TokenConfig) (val : Name) (s : String) (d : ParserData) : ParserData :=
let stopPos := d.pos in
if isToken startPos stopPos tk then
mkTokenAndFixPos startPos tk s d
else
let rawVal : Substring := { str := s, startPos := startPos, stopPos := stopPos } in
let d := whitespace s d in
let trailingStopPos := d.pos in
let leading := mkEmptySubstringAt s startPos in
let trailing : Substring := { str := s, startPos := stopPos, stopPos := trailingStopPos } in
let info : SourceInfo := {leading := leading, trailing := trailing, pos := startPos} in
let atom := Syntax.ident (some info) rawVal val [] [] in
d.pushSyntax atom
partial def identFnAux (startPos : Nat) (tk : Option TokenConfig) : Name → ParserFn
| r s d :=
let i := d.pos in
if s.atEnd i then d.mkEOIError
else
let c := s.get i in
if isIdBeginEscape c then
let startPart := s.next i in
let d := takeUntilFn isIdEndEscape s (d.setPos startPart) in
let stopPart := d.pos in
let d := satisfyFn isIdEndEscape "end of escaped identifier expected" s d in
if d.hasError then d
else
let r := Name.mkString r (s.extract startPart stopPart) in
if isIdCont s d then
identFnAux r s d
else
mkIdResult startPos tk r s d
else if isIdFirst c then
let startPart := i in
let d := takeWhileFn isIdRest s (d.next s i) in
let stopPart := d.pos in
let r := Name.mkString r (s.extract startPart stopPart) in
if isIdCont s d then
identFnAux r s d
else
mkIdResult startPart tk r s d
else
mkTokenAndFixPos startPos tk s d
def ParserData.keepNewError (d : ParserData) (oldStackSize : Nat) : ParserData :=
match d with
| ⟨stack, pos, cache, err⟩ := ⟨stack.shrink oldStackSize, pos, cache, err⟩
def ParserData.keepPrevError (d : ParserData) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option String) : ParserData :=
match d with
| ⟨stack, _, cache, _⟩ := ⟨stack.shrink oldStackSize, oldStopPos, cache, oldError⟩
def ParserData.mergeErrors (d : ParserData) (oldStackSize : Nat) (oldError : String) : ParserData :=
match d with
| ⟨stack, pos, cache, some err⟩ := ⟨stack.shrink oldStackSize, pos, cache, some (err ++ "; " ++ oldError)⟩
| other := other
def ParserData.mkLongestNodeAlt (d : ParserData) (startSize : Nat) : ParserData :=
match d with
| ⟨stack, pos, cache, _⟩ :=
if stack.size == startSize then ⟨stack.push Syntax.missing, pos, cache, none⟩ -- parser did not create any node, then we just add `Syntax.missing`
else if stack.size == startSize + 1 then d
else
-- parser created more than one node, combine them into a single node
let node := Syntax.node nullKind (stack.extract startSize stack.size) [] in
let stack := stack.shrink startSize in
⟨stack.push node, pos, cache, none⟩
def ParserData.keepLatest (d : ParserData) (startStackSize : Nat) : ParserData :=
match d with
| ⟨stack, pos, cache, _⟩ :=
let node := stack.back in
let stack := stack.shrink startStackSize in
let stack := stack.push node in
⟨stack, pos, cache, none⟩
def ParserData.replaceLongest (d : ParserData) (startStackSize : Nat) (prevStackSize : Nat) : ParserData :=
let d := d.mkLongestNodeAlt prevStackSize in
d.keepLatest startStackSize
def longestMatchStep (startSize : Nat) (startPos : String.Pos) (p : ParserFn) : ParserFn :=
λ s d,
let prevErrorMsg := d.errorMsg in
let prevStopPos := d.pos in
let prevSize := d.stackSize in
let d := d.restore prevSize startPos in
let d := p s d in
match prevErrorMsg, d.errorMsg with
| none, none := -- both succeeded
if d.pos > prevStopPos then d.replaceLongest startSize prevSize -- replace
else if d.pos < prevStopPos then d.restore prevSize prevStopPos -- keep prev
else d.mkLongestNodeAlt prevSize -- keep both
| none, some _ := -- prev succeeded, current failed
d.restore prevSize prevStopPos
| some oldError, some _ := -- both failed
if d.pos > prevStopPos then d.keepNewError prevSize
else if d.pos < prevStopPos then d.keepPrevError prevSize prevStopPos prevErrorMsg
else d.mergeErrors prevSize oldError
| some _, none := -- prev failed, current succeeded
d.mkLongestNodeAlt startSize
def longestMatchMkResult (startSize : Nat) (d : ParserData) : ParserData :=
if !d.hasError && d.stackSize > startSize + 1 then d.mkNode choiceKind startSize else d
def longestMatchFnAux (startSize : Nat) (startPos : String.Pos) : List ParserFn → ParserFn
| [] := λ _ d, longestMatchMkResult startSize d
| (p::ps) := λ s d,
let d := longestMatchStep startSize startPos p s d in
longestMatchFnAux ps s d
def longestMatchFn₁ (p : ParserFn) : ParserFn :=
λ s d,
let startSize := d.stackSize in
let d := p s d in
if d.hasError then d else d.mkLongestNodeAlt startSize
def longestMatchFn₂ (p q : ParserFn) : ParserFn :=
λ s d,
let startSize := d.stackSize in
let startPos := d.pos in
let d := p s d in
let d := if d.hasError then d.shrinkStack startSize else d.mkLongestNodeAlt startSize in
let d := longestMatchStep startSize startPos q s d in
longestMatchMkResult startSize d
def longestMatchFn : List ParserFn → ParserFn
| [] := λ _ d, d.mkError "longest match: empty list"
| [p] := longestMatchFn₁ p
| (p::ps) := λ s d,
let startSize := d.stackSize in
let startPos := d.pos in
let d := p s d in
if d.hasError then
let d := d.shrinkStack startSize in
longestMatchFnAux startSize startPos ps s d
else
let d := d.mkLongestNodeAlt startSize in
longestMatchFnAux startSize startPos ps s d
structure AbsParser (ρ : Type) :=
(info : ParserInfo := {})
(fn : ρ)
abbrev Parser := AbsParser ParserFn
class ParserFnLift (ρ : Type) :=
(lift {} : ParserFn → ρ)
(map : (ParserFn → ParserFn) → ρ → ρ)
(map₂ : (ParserFn → ParserFn → ParserFn) → ρ → ρ → ρ)
(mapList : (List ParserFn → ParserFn) → List ρ → ρ)
instance parserLiftInhabited {ρ : Type} [ParserFnLift ρ] : Inhabited ρ :=
⟨ParserFnLift.lift (default _)⟩
instance idParserLift : ParserFnLift ParserFn :=
{ lift := λ p, p,
map := λ m p, m p,
map₂ := λ m p1 p2, m p1 p2,
mapList := λ m ps, m ps }
@[inline]
def liftParser {ρ : Type} [ParserFnLift ρ] (info : ParserInfo) (fn : ParserFn) : AbsParser ρ :=
{ info := info, fn := ParserFnLift.lift fn }
@[inline]
def mapParser {ρ : Type} [ParserFnLift ρ] (infoFn : ParserInfo → ParserInfo) (pFn : ParserFn → ParserFn) : AbsParser ρ → AbsParser ρ :=
λ p, { info := infoFn p.info, fn := ParserFnLift.map pFn p.fn }
@[inline]
def mapParser₂ {ρ : Type} [ParserFnLift ρ] (infoFn : ParserInfo → ParserInfo → ParserInfo) (pFn : ParserFn → ParserFn → ParserFn)
: AbsParser ρ → AbsParser ρ → AbsParser ρ :=
λ p q, { info := infoFn p.info q.info, fn := ParserFnLift.map₂ pFn p.fn q.fn }
def EnvParserFn (α : Type) (ρ : Type) :=
α → ρ
def RecParserFn (α ρ : Type) :=
EnvParserFn (α → ρ) ρ
instance envParserLift (α ρ : Type) [ParserFnLift ρ] : ParserFnLift (EnvParserFn α ρ) :=
{ lift := λ p a, ParserFnLift.lift p,
map := λ m p a, ParserFnLift.map m (p a),
map₂ := λ m p1 p2 a, ParserFnLift.map₂ m (p1 a) (p2 a),
mapList := λ m ps a, ParserFnLift.mapList m (ps.map (λ p, p a)) }
instance recParserLift (α ρ : Type) [ParserFnLift ρ] : ParserFnLift (RecParserFn α ρ) :=
inferInstanceAs (ParserFnLift (EnvParserFn (α → ρ) ρ))
namespace RecParserFn
variable {α ρ : Type}
@[inline] def recurse (a : α) : RecParserFn α ρ :=
λ p, p a
@[inline] def run [ParserFnLift ρ] (x : RecParserFn α ρ) (rec : α → RecParserFn α ρ) : ρ :=
x (fix (λ f a, rec a f))
end RecParserFn
@[inline] def andthen {ρ : Type} [ParserFnLift ρ] : AbsParser ρ → AbsParser ρ → AbsParser ρ :=
mapParser₂ andthenInfo andthenFn
instance absParserAndThen {ρ : Type} [ParserFnLift ρ] : AndThen (AbsParser ρ) :=
⟨andthen⟩
@[inline] def node {ρ : Type} [ParserFnLift ρ] (k : SyntaxNodeKind) : AbsParser ρ → AbsParser ρ :=
mapParser nodeInfo (nodeFn k)
@[inline] def orelse {ρ : Type} [ParserFnLift ρ] : AbsParser ρ → AbsParser ρ → AbsParser ρ :=
mapParser₂ orelseInfo orelseFn
instance absParserOrElse {ρ : Type} [ParserFnLift ρ] : OrElse (AbsParser ρ) :=
⟨orelse⟩
@[inline] def try {ρ : Type} [ParserFnLift ρ] : AbsParser ρ → AbsParser ρ :=
mapParser noFirstTokenInfo tryFn
@[inline] def many {ρ : Type} [ParserFnLift ρ] : AbsParser ρ → AbsParser ρ :=
mapParser noFirstTokenInfo manyFn
@[inline] def optional {ρ : Type} [ParserFnLift ρ] : AbsParser ρ → AbsParser ρ :=
mapParser noFirstTokenInfo optionalFn
@[inline] def many1 {ρ : Type} [ParserFnLift ρ] (p : AbsParser ρ) : AbsParser ρ :=
andthen p (many p)
@[inline] def sepBy {ρ : Type} [ParserFnLift ρ] (p sep : AbsParser ρ) (allowTrailingSep : Bool := false) : AbsParser ρ :=
mapParser₂ sepByInfo (sepByFn allowTrailingSep) p sep
@[inline] def sepBy1 {ρ : Type} [ParserFnLift ρ] (p sep : AbsParser ρ) (allowTrailingSep : Bool := false) : AbsParser ρ :=
mapParser₂ sepBy1Info (sepBy1Fn allowTrailingSep) p sep
def longestMatchInfo {ρ : Type} (ps : List (AbsParser ρ)) : ParserInfo :=
{ updateTokens := λ trie, ps.foldl (λ trie p, p.info.updateTokens trie) trie,
firstTokens := ps.foldl (λ tks p, p.info.firstTokens ++ tks) [] }
def liftLongestMatchFn {ρ : Type} [ParserFnLift ρ] : List (AbsParser ρ) → ρ
| [] := ParserFnLift.lift (longestMatchFn [])
| [p] := ParserFnLift.map longestMatchFn₁ p.fn
| [p, q] := ParserFnLift.map₂ longestMatchFn₂ p.fn q.fn
| ps := ParserFnLift.mapList longestMatchFn (ps.map (λ p, p.fn))
@[inline] def longestMatch {ρ : Type} [ParserFnLift ρ] (ps : List (AbsParser ρ)) : AbsParser ρ :=
{ info := longestMatchInfo ps,
fn := liftLongestMatchFn ps }
abbrev BasicParserFn : Type := EnvParserFn ParserConfig ParserFn
abbrev BasicParser : Type := AbsParser BasicParserFn
abbrev CmdParserFn (ρ : Type) : Type := EnvParserFn ρ (RecParserFn Unit ParserFn)
abbrev TermParserFn : Type := RecParserFn Nat (CmdParserFn ParserConfig)
abbrev TermParser : Type := AbsParser TermParserFn
abbrev TrailingTermParserFn : Type := EnvParserFn Syntax TermParserFn
abbrev TrailingTermParser : Type := AbsParser TrailingTermParserFn
structure TermParsingTables :=
(leadingTermParsers : TokenMap TermParserFn)
(trailingTermParsers : TokenMap TrailingTermParserFn)
-- local Term parsers (such as from `local notation`) hide previous parsers instead of overloading them
(localLeadingTermParsers : TokenMap TermParserFn := RBMap.empty)
(localTrailingTermParsers : TokenMap TrailingTermParserFn := RBMap.empty)
structure CommandParserConfig extends ParserConfig :=
(pTables : TermParsingTables)
abbrev CommandParserFn : Type := CmdParserFn CommandParserConfig
abbrev CommandParser : Type := AbsParser CommandParserFn
@[inline] def Term.parser (rbp : Nat := 0) : TermParser :=
{ fn := RecParserFn.recurse rbp }
@[inline] def Command.parser : CommandParser :=
{ fn := λ _, RecParserFn.recurse () }
@[inline] def basicParser2TermParser (p : BasicParser) : TermParser :=
{ info := p.info, fn := λ _ cfg _, p.fn cfg }
instance basic2term : HasCoe BasicParser TermParser :=
⟨basicParser2TermParser⟩
@[inline] def basicParser2CmdParser (p : BasicParser) : CommandParser :=
{ info := p.info, fn := λ cfg _, p.fn cfg.toParserConfig }
instance basicmd : HasCoe BasicParser CommandParser :=
⟨basicParser2CmdParser⟩
private def tokenFnAux : BasicParserFn
| cfg s d :=
let i := d.pos in
let c := s.get i in
if c == '\"' then
strLitFnAux i s (d.next s i)
else if c.isDigit then
numberFnAux s d
else
let (_, tk) := cfg.tokens.matchPrefix s i in
identFnAux i tk Name.anonymous s d
private def updateCache (startPos : Nat) (d : ParserData) : ParserData :=
match d with
| ⟨stack, pos, cache, none⟩ :=
if stack.size == 0 then d
else
let tk := stack.back in
⟨stack, pos, { tokenCache := some { startPos := startPos, stopPos := pos, token := tk } }, none⟩
| other := other
def tokenFn : BasicParserFn
| cfg s d :=
let i := d.pos in
if s.atEnd i then d.mkEOIError
else
match d.cache with
| { tokenCache := some tkc } :=
if tkc.startPos == i then
let d := d.pushSyntax tkc.token in
d.setPos tkc.stopPos
else
let d := tokenFnAux cfg s d in
updateCache i d
| _ :=
let d := tokenFnAux cfg s d in
updateCache i d
@[inline] def satisfySymbolFn (p : String → Bool) (errorMsg : String) : BasicParserFn
| cfg s d :=
let startPos := d.pos in
let d := tokenFn cfg s d in
if d.hasError then
d.mkErrorAt errorMsg startPos
else
match d.stxStack.back with
| Syntax.atom _ sym := if p sym then d else d.mkErrorAt errorMsg startPos
| _ := d.mkErrorAt errorMsg startPos
def symbolFnAux (sym : String) (errorMsg : String) : BasicParserFn :=
satisfySymbolFn (== sym) errorMsg
@[inline] def symbolFn (sym : String) : BasicParserFn :=
symbolFnAux sym ("expected '" ++ sym ++ "'")
def symbolInfo (sym : String) (lbp : Nat) : ParserInfo :=
{ updateTokens := λ trie, trie.insert sym { val := sym, lbp := lbp },
firstTokens := [ { val := sym, lbp := lbp } ] }
@[inline] def symbol (sym : String) (lbp : Nat := 0) : BasicParser :=
{ info := symbolInfo sym lbp,
fn := symbolFn sym }
def unicodeSymbolFnAux (sym asciiSym : String) (errorMsg : String) : BasicParserFn :=
satisfySymbolFn (λ s, s == sym || s == asciiSym) errorMsg
@[inline] def unicodeSymbolFn (sym asciiSym : String) : BasicParserFn :=
unicodeSymbolFnAux sym asciiSym ("expected '" ++ sym ++ "' or '" ++ asciiSym ++ "'")
def unicodeSymbolInfo (sym asciiSym : String) (lbp : Nat) : ParserInfo :=
{ updateTokens := λ trie,
let trie := trie.insert sym { val := sym, lbp := lbp } in
trie.insert sym { val := asciiSym, lbp := lbp },
firstTokens := [ { val := sym, lbp := lbp },
{ val := asciiSym, lbp := lbp } ] }
@[inline] def unicodeSymbol (sym asciiSym : String) (lbp : Nat := 0) : BasicParser :=
{ info := unicodeSymbolInfo sym asciiSym lbp,
fn := unicodeSymbolFn sym asciiSym }
def numberFn : BasicParserFn
| cfg s d :=
let d := tokenFn cfg s d in
if d.hasError || !(d.stxStack.back.isOfKind numberKind) then
d.mkError "expected numeral"
else
d
@[inline] def number : BasicParser :=
{ fn := numberFn }
def strLitFn : BasicParserFn
| cfg s d :=
let d := tokenFn cfg s d in
if d.hasError || !(d.stxStack.back.isOfKind strLitKind) then
d.mkError "expected string literal"
else
d
@[inline] def strLit : BasicParser :=
{ fn := numberFn }
def identFn : BasicParserFn
| cfg s d :=
let d := tokenFn cfg s d in
if d.hasError || !(d.stxStack.back.isIdent) then
d.mkError "expected identifier"
else
d
@[inline] def ident : BasicParser :=
{ fn := identFn }
instance string2basic : HasCoe String BasicParser :=
⟨symbol⟩
def mkFrontendConfig (filename input : String) : FrontendConfig :=
{ filename := filename,
input := input,
fileMap := input.toFileMap }
def BasicParser.run (p : BasicParser) (input : String) (filename : String := "<input>") : Except String Syntax :=
let frontendCfg := mkFrontendConfig filename input in
let tokens := p.info.updateTokens {} in
let cfg : ParserConfig := { tokens := tokens, .. frontendCfg } in
let d : ParserData := { stxStack := Array.empty, pos := 0, cache := {}, errorMsg := none } in
let d := p.fn cfg input d in
if d.hasError then
Except.error (d.toErrorMsg cfg)
else
Except.ok d.stxStack.back
-- Helper function for testing (non-recursive) term parsers
def TermParser.test (p : TermParser) (input : String) (filename : String := "<input>") : Except String Syntax :=
let frontendCfg := mkFrontendConfig filename input in
let tokens := p.info.updateTokens {} in
let cfg : ParserConfig := { tokens := tokens, .. frontendCfg } in
let d : ParserData := { stxStack := Array.empty, pos := 0, cache := {}, errorMsg := none } in
let dummyCmdParser : Unit → ParserFn := λ _ _ d, d.mkError "no command parser" in
let dummyTermParser : ℕ → CmdParserFn ParserConfig := λ _ _ _ _ d, d.mkError "no term parser" in
let d := p.fn dummyTermParser cfg dummyCmdParser input d in
if d.hasError then
Except.error (d.toErrorMsg cfg)
else
Except.ok d.stxStack.back
-- Stopped here
@[noinline] def termPrattParser (tbl : TermParsingTables) (rbp : Nat) : TermParserFn :=
λ g, g 0 -- TODO(Leo)
@[specialize] def TermParserFn.run (p : TermParserFn) : CommandParserFn
| cfg r s d :=
let p := RecParserFn.run p (termPrattParser cfg.pTables) in
p cfg.toParserConfig r s d
def parseExpr (rbp : Nat) : CommandParserFn :=
TermParserFn.run (RecParserFn.recurse rbp)
end Parser
-- end Lean
|
1da39392fc9e25092957918427a654b7e0492766 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/linear_algebra/finite_dimensional.lean | ecafdced9e372c1e461ddafab9adfa3b27a2abd7 | [
"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 | 63,070 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import algebra.algebra.subalgebra.basic
import field_theory.finiteness
import linear_algebra.free_module.finite.rank
import tactic.interval_cases
/-!
# Finite dimensional vector spaces
Definition and basic properties of finite dimensional vector spaces, of their dimensions, and
of linear maps on such spaces.
## Main definitions
Assume `V` is a vector space over a division ring `K`. There are (at least) three equivalent
definitions of finite-dimensionality of `V`:
- it admits a finite basis.
- it is finitely generated.
- it is noetherian, i.e., every subspace is finitely generated.
We introduce a typeclass `finite_dimensional K V` capturing this property. For ease of transfer of
proof, it is defined using the second point of view, i.e., as `finite`. However, we prove
that all these points of view are equivalent, with the following lemmas
(in the namespace `finite_dimensional`):
- `fintype_basis_index` states that a finite-dimensional
vector space has a finite basis
- `finite_dimensional.fin_basis` and `finite_dimensional.fin_basis_of_finrank_eq`
are bases for finite dimensional vector spaces, where the index type
is `fin`
- `of_fintype_basis` states that the existence of a basis indexed by a
finite type implies finite-dimensionality
- `of_finite_basis` states that the existence of a basis indexed by a
finite set implies finite-dimensionality
- `is_noetherian.iff_fg` states that the space is finite-dimensional if and only if
it is noetherian
We make use of `finrank`, the dimension of a finite dimensional space, returning a `nat`, as
opposed to `module.rank`, which returns a `cardinal`. When the space has infinite dimension, its
`finrank` is by convention set to `0`. `finrank` is not defined using `finite_dimensional`.
For basic results that do not need the `finite_dimensional` class, import `linear_algebra.finrank`.
Preservation of finite-dimensionality and formulas for the dimension are given for
- submodules
- quotients (for the dimension of a quotient, see `finrank_quotient_add_finrank`)
- linear equivs, in `linear_equiv.finite_dimensional`
- image under a linear map (the rank-nullity formula is in `finrank_range_add_finrank_ker`)
Basic properties of linear maps of a finite-dimensional vector space are given. Notably, the
equivalence of injectivity and surjectivity is proved in `linear_map.injective_iff_surjective`,
and the equivalence between left-inverse and right-inverse in `linear_map.mul_eq_one_comm`
and `linear_map.comp_eq_id_comm`.
## Implementation notes
Most results are deduced from the corresponding results for the general dimension (as a cardinal),
in `dimension.lean`. Not all results have been ported yet.
You should not assume that there has been any effort to state lemmas as generally as possible.
One of the characterizations of finite-dimensionality is in terms of finite generation. This
property is currently defined only for submodules, so we express it through the fact that the
maximal submodule (which, as a set, coincides with the whole space) is finitely generated. This is
not very convenient to use, although there are some helper functions. However, this becomes very
convenient when speaking of submodules which are finite-dimensional, as this notion coincides with
the fact that the submodule is finitely generated (as a submodule of the whole space). This
equivalence is proved in `submodule.fg_iff_finite_dimensional`.
-/
universes u v v' w
open_locale classical cardinal
open cardinal submodule module function
/-- `finite_dimensional` vector spaces are defined to be finite modules.
Use `finite_dimensional.of_fintype_basis` to prove finite dimension from another definition. -/
@[reducible] def finite_dimensional (K V : Type*) [division_ring K]
[add_comm_group V] [module K V] := module.finite K V
variables {K : Type u} {V : Type v}
namespace finite_dimensional
open is_noetherian
section division_ring
variables [division_ring K] [add_comm_group V] [module K V]
{V₂ : Type v'} [add_comm_group V₂] [module K V₂]
/-- If the codomain of an injective linear map is finite dimensional, the domain must be as well. -/
lemma of_injective (f : V →ₗ[K] V₂) (w : function.injective f)
[finite_dimensional K V₂] : finite_dimensional K V :=
have is_noetherian K V₂ := is_noetherian.iff_fg.mpr ‹_›, by exactI module.finite.of_injective f w
/-- If the domain of a surjective linear map is finite dimensional, the codomain must be as well. -/
lemma of_surjective (f : V →ₗ[K] V₂) (w : function.surjective f)
[finite_dimensional K V] : finite_dimensional K V₂ :=
module.finite.of_surjective f w
variables (K V)
instance finite_dimensional_pi {ι : Type*} [_root_.finite ι] : finite_dimensional K (ι → K) :=
iff_fg.1 is_noetherian_pi
instance finite_dimensional_pi' {ι : Type*} [_root_.finite ι] (M : ι → Type*)
[∀ i, add_comm_group (M i)] [∀ i, module K (M i)] [I : ∀ i, finite_dimensional K (M i)] :
finite_dimensional K (Π i, M i) :=
begin
haveI : ∀ i : ι, is_noetherian K (M i) := λ i, iff_fg.2 (I i),
exact iff_fg.1 is_noetherian_pi
end
/-- A finite dimensional vector space over a finite field is finite -/
noncomputable def fintype_of_fintype [fintype K] [finite_dimensional K V] : fintype V :=
module.fintype_of_fintype (@finset_basis K V _ _ _ (iff_fg.2 infer_instance))
lemma finite_of_finite [_root_.finite K] [finite_dimensional K V] : _root_.finite V :=
by { casesI nonempty_fintype K, haveI := fintype_of_fintype K V, apply_instance }
variables {K V}
/-- If a vector space has a finite basis, then it is finite-dimensional. -/
lemma of_fintype_basis {ι : Type w} [_root_.finite ι] (h : basis ι K V) : finite_dimensional K V :=
by { casesI nonempty_fintype ι, exact ⟨⟨finset.univ.image h, by { convert h.span_eq, simp } ⟩⟩ }
/-- If a vector space is `finite_dimensional`, all bases are indexed by a finite type -/
noncomputable
def fintype_basis_index {ι : Type*} [finite_dimensional K V] (b : basis ι K V) : fintype ι :=
begin
letI : is_noetherian K V := is_noetherian.iff_fg.2 infer_instance,
exact is_noetherian.fintype_basis_index b,
end
/-- If a vector space is `finite_dimensional`, `basis.of_vector_space` is indexed by
a finite type.-/
noncomputable instance [finite_dimensional K V] : fintype (basis.of_vector_space_index K V) :=
begin
letI : is_noetherian K V := is_noetherian.iff_fg.2 infer_instance,
apply_instance
end
/-- If a vector space has a basis indexed by elements of a finite set, then it is
finite-dimensional. -/
lemma of_finite_basis {ι : Type w} {s : set ι} (h : basis s K V) (hs : set.finite s) :
finite_dimensional K V :=
by haveI := hs.fintype; exact of_fintype_basis h
/-- A subspace of a finite-dimensional space is also finite-dimensional. -/
instance finite_dimensional_submodule [finite_dimensional K V] (S : submodule K V) :
finite_dimensional K S :=
begin
letI : is_noetherian K V := iff_fg.2 _,
exact iff_fg.1
(is_noetherian.iff_dim_lt_aleph_0.2 (lt_of_le_of_lt (dim_submodule_le _) (dim_lt_aleph_0 K V))),
apply_instance,
end
/-- A quotient of a finite-dimensional space is also finite-dimensional. -/
instance finite_dimensional_quotient [finite_dimensional K V] (S : submodule K V) :
finite_dimensional K (V ⧸ S) :=
module.finite.of_surjective (submodule.mkq S) $ surjective_quot_mk _
variables (K V)
/-- In a finite-dimensional space, its dimension (seen as a cardinal) coincides with its
`finrank`. -/
lemma finrank_eq_dim [finite_dimensional K V] :
(finrank K V : cardinal.{v}) = module.rank K V :=
begin
letI : is_noetherian K V := iff_fg.2 infer_instance,
rw [finrank, cast_to_nat_of_lt_aleph_0 (dim_lt_aleph_0 K V)]
end
variables {K V}
lemma finrank_of_infinite_dimensional (h : ¬finite_dimensional K V) : finrank K V = 0 :=
dif_neg $ mt is_noetherian.iff_dim_lt_aleph_0.2 $ (not_iff_not.2 iff_fg).2 h
lemma finite_dimensional_of_finrank (h : 0 < finrank K V) : finite_dimensional K V :=
by { contrapose h, simp [finrank_of_infinite_dimensional h] }
lemma finite_dimensional_of_finrank_eq_succ
{n : ℕ} (hn : finrank K V = n.succ) : finite_dimensional K V :=
finite_dimensional_of_finrank $ by rw hn; exact n.succ_pos
/-- We can infer `finite_dimensional K V` in the presence of `[fact (finrank K V = n + 1)]`. Declare
this as a local instance where needed. -/
lemma fact_finite_dimensional_of_finrank_eq_succ
(n : ℕ) [fact (finrank K V = n + 1)] : finite_dimensional K V :=
finite_dimensional_of_finrank $ by convert nat.succ_pos n; apply fact.out
lemma finite_dimensional_iff_of_rank_eq_nsmul {W} [add_comm_group W] [module K W]
{n : ℕ} (hn : n ≠ 0) (hVW : module.rank K V = n • module.rank K W) :
finite_dimensional K V ↔ finite_dimensional K W :=
by simp only [finite_dimensional, ← is_noetherian.iff_fg, is_noetherian.iff_dim_lt_aleph_0, hVW,
cardinal.nsmul_lt_aleph_0_iff_of_ne_zero hn]
/-- If a vector space is finite-dimensional, then the cardinality of any basis is equal to its
`finrank`. -/
lemma finrank_eq_card_basis' [finite_dimensional K V] {ι : Type w} (h : basis ι K V) :
(finrank K V : cardinal.{w}) = #ι :=
begin
haveI : is_noetherian K V := iff_fg.2 infer_instance,
haveI : fintype ι := fintype_basis_index h,
rw [cardinal.mk_fintype, finrank_eq_card_basis h]
end
variables (K V)
/-- A finite dimensional vector space has a basis indexed by `fin (finrank K V)`. -/
noncomputable def fin_basis [finite_dimensional K V] : basis (fin (finrank K V)) K V :=
have h : fintype.card (@finset_basis_index K V _ _ _ (iff_fg.2 infer_instance)) = finrank K V,
from (finrank_eq_card_basis (@finset_basis K V _ _ _ (iff_fg.2 infer_instance))).symm,
(@finset_basis K V _ _ _ (iff_fg.2 infer_instance)).reindex (fintype.equiv_fin_of_card_eq h)
/-- An `n`-dimensional vector space has a basis indexed by `fin n`. -/
noncomputable def fin_basis_of_finrank_eq [finite_dimensional K V] {n : ℕ} (hn : finrank K V = n) :
basis (fin n) K V :=
(fin_basis K V).reindex (fin.cast hn).to_equiv
variables {K V}
/-- A module with dimension 1 has a basis with one element. -/
noncomputable def basis_unique (ι : Type*) [unique ι] (h : finrank K V = 1) :
basis ι K V :=
begin
haveI := finite_dimensional_of_finrank (_root_.zero_lt_one.trans_le h.symm.le),
exact (fin_basis_of_finrank_eq K V h).reindex (equiv.equiv_of_unique _ _)
end
@[simp]
lemma basis_unique.repr_eq_zero_iff {ι : Type*} [unique ι] {h : finrank K V = 1}
{v : V} {i : ι} : (basis_unique ι h).repr v i = 0 ↔ v = 0 :=
⟨λ hv, (basis_unique ι h).repr.map_eq_zero_iff.mp (finsupp.ext $ λ j, subsingleton.elim i j ▸ hv),
λ hv, by rw [hv, linear_equiv.map_zero, finsupp.zero_apply]⟩
lemma cardinal_mk_le_finrank_of_linear_independent
[finite_dimensional K V] {ι : Type w} {b : ι → V} (h : linear_independent K b) :
#ι ≤ finrank K V :=
begin
rw ← lift_le.{_ (max v w)},
simpa [← finrank_eq_dim, -module.free.finrank_eq_rank] using
cardinal_lift_le_dim_of_linear_independent.{_ _ _ (max v w)} h
end
lemma fintype_card_le_finrank_of_linear_independent
[finite_dimensional K V] {ι : Type*} [fintype ι] {b : ι → V} (h : linear_independent K b) :
fintype.card ι ≤ finrank K V :=
by simpa using cardinal_mk_le_finrank_of_linear_independent h
lemma finset_card_le_finrank_of_linear_independent [finite_dimensional K V] {b : finset V}
(h : linear_independent K (λ x, x : b → V)) :
b.card ≤ finrank K V :=
begin
rw ←fintype.card_coe,
exact fintype_card_le_finrank_of_linear_independent h,
end
lemma lt_aleph_0_of_linear_independent {ι : Type w} [finite_dimensional K V]
{v : ι → V} (h : linear_independent K v) :
#ι < ℵ₀ :=
begin
apply cardinal.lift_lt.1,
apply lt_of_le_of_lt,
apply cardinal_lift_le_dim_of_linear_independent h,
rw [←finrank_eq_dim, cardinal.lift_aleph_0, cardinal.lift_nat_cast],
apply cardinal.nat_lt_aleph_0,
end
lemma _root_.linear_independent.finite [finite_dimensional K V] {b : set V}
(h : linear_independent K (λ (x:b), (x:V))) : b.finite :=
cardinal.lt_aleph_0_iff_set_finite.mp (finite_dimensional.lt_aleph_0_of_linear_independent h)
lemma not_linear_independent_of_infinite {ι : Type w} [inf : infinite ι] [finite_dimensional K V]
(v : ι → V) : ¬ linear_independent K v :=
begin
intro h_lin_indep,
have : ¬ ℵ₀ ≤ #ι := not_le.mpr (lt_aleph_0_of_linear_independent h_lin_indep),
have : ℵ₀ ≤ #ι := infinite_iff.mp inf,
contradiction
end
/-- A finite dimensional space has positive `finrank` iff it has a nonzero element. -/
lemma finrank_pos_iff_exists_ne_zero [finite_dimensional K V] : 0 < finrank K V ↔ ∃ x : V, x ≠ 0 :=
iff.trans (by { rw ← finrank_eq_dim, norm_cast }) (@dim_pos_iff_exists_ne_zero K V _ _ _ _ _)
/-- A finite dimensional space has positive `finrank` iff it is nontrivial. -/
lemma finrank_pos_iff [finite_dimensional K V] : 0 < finrank K V ↔ nontrivial V :=
iff.trans (by { rw ← finrank_eq_dim, norm_cast }) (@dim_pos_iff_nontrivial K V _ _ _ _ _)
/-- A nontrivial finite dimensional space has positive `finrank`. -/
lemma finrank_pos [finite_dimensional K V] [h : nontrivial V] : 0 < finrank K V :=
finrank_pos_iff.mpr h
/-- A finite dimensional space has zero `finrank` iff it is a subsingleton.
This is the `finrank` version of `dim_zero_iff`. -/
lemma finrank_zero_iff [finite_dimensional K V] :
finrank K V = 0 ↔ subsingleton V :=
iff.trans (by { rw ← finrank_eq_dim, norm_cast }) (@dim_zero_iff K V _ _ _ _ _)
/-- If a submodule has maximal dimension in a finite dimensional space, then it is equal to the
whole space. -/
lemma eq_top_of_finrank_eq [finite_dimensional K V] {S : submodule K V}
(h : finrank K S = finrank K V) : S = ⊤ :=
begin
haveI : is_noetherian K V := iff_fg.2 infer_instance,
set bS := basis.of_vector_space K S with bS_eq,
have : linear_independent K (coe : (coe '' basis.of_vector_space_index K S : set V) → V),
from @linear_independent.image_subtype _ _ _ _ _ _ _ _ _
(submodule.subtype S) (by simpa using bS.linear_independent) (by simp),
set b := basis.extend this with b_eq,
letI : fintype (this.extend _) :=
(finite_of_linear_independent (by simpa using b.linear_independent)).fintype,
letI : fintype (coe '' basis.of_vector_space_index K S) :=
(finite_of_linear_independent this).fintype,
letI : fintype (basis.of_vector_space_index K S) :=
(finite_of_linear_independent (by simpa using bS.linear_independent)).fintype,
have : coe '' (basis.of_vector_space_index K S) = this.extend (set.subset_univ _),
from set.eq_of_subset_of_card_le (this.subset_extend _)
(by rw [set.card_image_of_injective _ subtype.coe_injective, ← finrank_eq_card_basis bS,
← finrank_eq_card_basis b, h]; apply_instance),
rw [← b.span_eq, b_eq, basis.coe_extend, subtype.range_coe, ← this, ← submodule.coe_subtype,
span_image],
have := bS.span_eq,
rw [bS_eq, basis.coe_of_vector_space, subtype.range_coe] at this,
rw [this, map_top (submodule.subtype S), range_subtype],
end
variable (K)
instance finite_dimensional_self : finite_dimensional K K :=
by apply_instance
/-- The submodule generated by a finite set is finite-dimensional. -/
theorem span_of_finite {A : set V} (hA : set.finite A) :
finite_dimensional K (submodule.span K A) :=
iff_fg.1 $ is_noetherian_span_of_finite K hA
/-- The submodule generated by a single element is finite-dimensional. -/
instance span_singleton (x : V) : finite_dimensional K (K ∙ x) :=
span_of_finite K $ set.finite_singleton _
/-- The submodule generated by a finset is finite-dimensional. -/
instance span_finset (s : finset V) : finite_dimensional K (span K (s : set V)) :=
span_of_finite K $ s.finite_to_set
/-- Pushforwards of finite-dimensional submodules are finite-dimensional. -/
instance (f : V →ₗ[K] V₂) (p : submodule K V) [h : finite_dimensional K p] :
finite_dimensional K (p.map f) :=
begin
unfreezingI { rw [finite_dimensional, ← iff_fg, is_noetherian.iff_dim_lt_aleph_0] at h ⊢ },
rw [← cardinal.lift_lt.{v' v}],
rw [← cardinal.lift_lt.{v v'}] at h,
rw [cardinal.lift_aleph_0] at h ⊢,
exact (lift_dim_map_le f p).trans_lt h
end
/-- Pushforwards of finite-dimensional submodules have a smaller finrank. -/
lemma finrank_map_le (f : V →ₗ[K] V₂) (p : submodule K V) [finite_dimensional K p] :
finrank K (p.map f) ≤ finrank K p :=
by simpa [← finrank_eq_dim, -module.free.finrank_eq_rank] using lift_dim_map_le f p
variable {K}
lemma _root_.complete_lattice.independent.subtype_ne_bot_le_finrank_aux [finite_dimensional K V]
{ι : Type w} {p : ι → submodule K V} (hp : complete_lattice.independent p) :
#{i // p i ≠ ⊥} ≤ (finrank K V : cardinal.{w}) :=
begin
suffices : cardinal.lift.{v} (#{i // p i ≠ ⊥}) ≤ cardinal.lift.{v} (finrank K V : cardinal.{w}),
{ rwa cardinal.lift_le at this },
calc cardinal.lift.{v} (# {i // p i ≠ ⊥})
≤ cardinal.lift.{w} (module.rank K V) : hp.subtype_ne_bot_le_rank
... = cardinal.lift.{w} (finrank K V : cardinal.{v}) : by rw finrank_eq_dim
... = cardinal.lift.{v} (finrank K V : cardinal.{w}) : by simp
end
/-- If `p` is an independent family of subspaces of a finite-dimensional space `V`, then the
number of nontrivial subspaces in the family `p` is finite. -/
noncomputable def _root_.complete_lattice.independent.fintype_ne_bot_of_finite_dimensional
[finite_dimensional K V] {ι : Type w} {p : ι → submodule K V}
(hp : complete_lattice.independent p) :
fintype {i : ι // p i ≠ ⊥} :=
begin
suffices : #{i // p i ≠ ⊥} < (ℵ₀ : cardinal.{w}),
{ rw cardinal.lt_aleph_0_iff_fintype at this,
exact this.some },
refine lt_of_le_of_lt hp.subtype_ne_bot_le_finrank_aux _,
simp [cardinal.nat_lt_aleph_0],
end
/-- If `p` is an independent family of subspaces of a finite-dimensional space `V`, then the
number of nontrivial subspaces in the family `p` is bounded above by the dimension of `V`.
Note that the `fintype` hypothesis required here can be provided by
`complete_lattice.independent.fintype_ne_bot_of_finite_dimensional`. -/
lemma _root_.complete_lattice.independent.subtype_ne_bot_le_finrank
[finite_dimensional K V] {ι : Type w} {p : ι → submodule K V}
(hp : complete_lattice.independent p) [fintype {i // p i ≠ ⊥}] :
fintype.card {i // p i ≠ ⊥} ≤ finrank K V :=
by simpa using hp.subtype_ne_bot_le_finrank_aux
section
open_locale big_operators
open finset
/--
If a finset has cardinality larger than the dimension of the space,
then there is a nontrivial linear relation amongst its elements.
-/
lemma exists_nontrivial_relation_of_dim_lt_card
[finite_dimensional K V] {t : finset V} (h : finrank K V < t.card) :
∃ f : V → K, ∑ e in t, f e • e = 0 ∧ ∃ x ∈ t, f x ≠ 0 :=
begin
have := mt finset_card_le_finrank_of_linear_independent (by { simpa using h }),
rw not_linear_independent_iff at this,
obtain ⟨s, g, sum, z, zm, nonzero⟩ := this,
-- Now we have to extend `g` to all of `t`, then to all of `V`.
let f : V → K :=
λ x, if h : x ∈ t then if (⟨x, h⟩ : t) ∈ s then g ⟨x, h⟩ else 0 else 0,
-- and finally clean up the mess caused by the extension.
refine ⟨f, _, _⟩,
{ dsimp [f],
rw ← sum,
fapply sum_bij_ne_zero (λ v hvt _, (⟨v, hvt⟩ : {v // v ∈ t})),
{ intros v hvt H, dsimp,
rw [dif_pos hvt] at H,
contrapose! H,
rw [if_neg H, zero_smul], },
{ intros _ _ _ _ _ _, exact subtype.mk.inj, },
{ intros b hbs hb,
use b,
simpa only [hbs, exists_prop, dif_pos, finset.mk_coe, and_true, if_true, finset.coe_mem,
eq_self_iff_true, exists_prop_of_true, ne.def] using hb, },
{ intros a h₁, dsimp, rw [dif_pos h₁],
intro h₂, rw [if_pos], contrapose! h₂,
rw [if_neg h₂, zero_smul], }, },
{ refine ⟨z, z.2, _⟩, dsimp only [f], erw [dif_pos z.2, if_pos]; rwa [subtype.coe_eta] },
end
/--
If a finset has cardinality larger than `finrank + 1`,
then there is a nontrivial linear relation amongst its elements,
such that the coefficients of the relation sum to zero.
-/
lemma exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card
[finite_dimensional K V] {t : finset V} (h : finrank K V + 1 < t.card) :
∃ f : V → K, ∑ e in t, f e • e = 0 ∧ ∑ e in t, f e = 0 ∧ ∃ x ∈ t, f x ≠ 0 :=
begin
-- Pick an element x₀ ∈ t,
have card_pos : 0 < t.card := lt_trans (nat.succ_pos _) h,
obtain ⟨x₀, m⟩ := (finset.card_pos.1 card_pos).bex,
-- and apply the previous lemma to the {xᵢ - x₀}
let shift : V ↪ V := ⟨λ x, x - x₀, sub_left_injective⟩,
let t' := (t.erase x₀).map shift,
have h' : finrank K V < t'.card,
{ simp only [t', card_map, finset.card_erase_of_mem m],
exact nat.lt_pred_iff.mpr h, },
-- to obtain a function `g`.
obtain ⟨g, gsum, x₁, x₁_mem, nz⟩ := exists_nontrivial_relation_of_dim_lt_card h',
-- Then obtain `f` by translating back by `x₀`,
-- and setting the value of `f` at `x₀` to ensure `∑ e in t, f e = 0`.
let f : V → K := λ z, if z = x₀ then - ∑ z in (t.erase x₀), g (z - x₀) else g (z - x₀),
refine ⟨f, _ ,_ ,_⟩,
-- After this, it's a matter of verifiying the properties,
-- based on the corresponding properties for `g`.
{ show ∑ (e : V) in t, f e • e = 0,
-- We prove this by splitting off the `x₀` term of the sum,
-- which is itself a sum over `t.erase x₀`,
-- combining the two sums, and
-- observing that after reindexing we have exactly
-- ∑ (x : V) in t', g x • x = 0.
simp only [f],
conv_lhs { apply_congr, skip, rw [ite_smul], },
rw [finset.sum_ite],
conv { congr, congr, apply_congr, simp [filter_eq', m], },
conv { congr, congr, skip, apply_congr, simp [filter_ne'], },
rw [sum_singleton, neg_smul, add_comm, ←sub_eq_add_neg, sum_smul, ←sum_sub_distrib],
simp only [←smul_sub],
-- At the end we have to reindex the sum, so we use `change` to
-- express the summand using `shift`.
change (∑ (x : V) in t.erase x₀, (λ e, g e • e) (shift x)) = 0,
rw ←sum_map _ shift,
exact gsum, },
{ show ∑ (e : V) in t, f e = 0,
-- Again we split off the `x₀` term,
-- observing that it exactly cancels the other terms.
rw [← insert_erase m, sum_insert (not_mem_erase x₀ t)],
dsimp [f],
rw [if_pos rfl],
conv_lhs { congr, skip, apply_congr, skip, rw if_neg (show x ≠ x₀, from (mem_erase.mp H).1), },
exact neg_add_self _, },
{ show ∃ (x : V) (H : x ∈ t), f x ≠ 0,
-- We can use x₁ + x₀.
refine ⟨x₁ + x₀, _, _⟩,
{ rw finset.mem_map at x₁_mem,
rcases x₁_mem with ⟨x₁, x₁_mem, rfl⟩,
rw mem_erase at x₁_mem,
simp only [x₁_mem, sub_add_cancel, function.embedding.coe_fn_mk], },
{ dsimp only [f],
rwa [if_neg, add_sub_cancel],
rw [add_left_eq_self], rintro rfl,
simpa only [sub_eq_zero, exists_prop, finset.mem_map, embedding.coe_fn_mk, eq_self_iff_true,
mem_erase, not_true, exists_eq_right, ne.def, false_and] using x₁_mem, } },
end
section
variables {L : Type*} [linear_ordered_field L]
variables {W : Type v} [add_comm_group W] [module L W]
/--
A slight strengthening of `exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card`
available when working over an ordered field:
we can ensure a positive coefficient, not just a nonzero coefficient.
-/
lemma exists_relation_sum_zero_pos_coefficient_of_dim_succ_lt_card
[finite_dimensional L W] {t : finset W} (h : finrank L W + 1 < t.card) :
∃ f : W → L, ∑ e in t, f e • e = 0 ∧ ∑ e in t, f e = 0 ∧ ∃ x ∈ t, 0 < f x :=
begin
obtain ⟨f, sum, total, nonzero⟩ := exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card h,
exact ⟨f, sum, total, exists_pos_of_sum_zero_of_exists_nonzero f total nonzero⟩,
end
end
end
/-- In a vector space with dimension 1, each set {v} is a basis for `v ≠ 0`. -/
@[simps]
noncomputable def basis_singleton (ι : Type*) [unique ι]
(h : finrank K V = 1) (v : V) (hv : v ≠ 0) :
basis ι K V :=
let b := basis_unique ι h in
let h : b.repr v default ≠ 0 := mt basis_unique.repr_eq_zero_iff.mp hv in
basis.of_repr
{ to_fun := λ w, finsupp.single default (b.repr w default / b.repr v default),
inv_fun := λ f, f default • v,
map_add' := by simp [add_div],
map_smul' := by simp [mul_div],
left_inv := λ w, begin
apply_fun b.repr using b.repr.to_equiv.injective,
apply_fun equiv.finsupp_unique,
simp only [linear_equiv.map_smulₛₗ, finsupp.coe_smul, finsupp.single_eq_same, ring_hom.id_apply,
smul_eq_mul, pi.smul_apply, equiv.finsupp_unique_apply],
exact div_mul_cancel _ h,
end ,
right_inv := λ f, begin
ext,
simp only [linear_equiv.map_smulₛₗ, finsupp.coe_smul, finsupp.single_eq_same, ring_hom.id_apply,
smul_eq_mul, pi.smul_apply],
exact mul_div_cancel _ h,
end, }
@[simp] lemma basis_singleton_apply (ι : Type*) [unique ι]
(h : finrank K V = 1) (v : V) (hv : v ≠ 0) (i : ι) :
basis_singleton ι h v hv i = v :=
by { cases unique.uniq ‹unique ι› i, simp [basis_singleton], }
@[simp] lemma range_basis_singleton (ι : Type*) [unique ι]
(h : finrank K V = 1) (v : V) (hv : v ≠ 0) :
set.range (basis_singleton ι h v hv) = {v} :=
by rw [set.range_unique, basis_singleton_apply]
end division_ring
end finite_dimensional
variables {K V}
section zero_dim
variables [division_ring K] [add_comm_group V] [module K V]
open finite_dimensional
lemma finite_dimensional_of_dim_eq_nat {n : ℕ} (h : module.rank K V = n) : finite_dimensional K V :=
begin
rw [finite_dimensional, ← is_noetherian.iff_fg, is_noetherian.iff_dim_lt_aleph_0, h],
exact nat_lt_aleph_0 n,
end
/- TODO: generalize to free modules over general rings. -/
lemma finite_dimensional_of_dim_eq_zero (h : module.rank K V = 0) : finite_dimensional K V :=
finite_dimensional_of_dim_eq_nat $ h.trans nat.cast_zero.symm
lemma finite_dimensional_of_dim_eq_one (h : module.rank K V = 1) : finite_dimensional K V :=
finite_dimensional_of_dim_eq_nat $ h.trans nat.cast_one.symm
lemma finrank_eq_zero_of_dim_eq_zero [finite_dimensional K V] (h : module.rank K V = 0) :
finrank K V = 0 :=
begin
convert finrank_eq_dim K V,
rw h, norm_cast
end
variables (K V)
instance finite_dimensional_bot : finite_dimensional K (⊥ : submodule K V) :=
finite_dimensional_of_dim_eq_zero $ by simp
variables {K V}
lemma bot_eq_top_of_dim_eq_zero (h : module.rank K V = 0) : (⊥ : submodule K V) = ⊤ :=
begin
haveI := finite_dimensional_of_dim_eq_zero h,
apply eq_top_of_finrank_eq,
rw [finrank_bot, finrank_eq_zero_of_dim_eq_zero h]
end
@[simp] theorem dim_eq_zero {S : submodule K V} : module.rank K S = 0 ↔ S = ⊥ :=
⟨λ h, (submodule.eq_bot_iff _).2 $ λ x hx, congr_arg subtype.val $
((submodule.eq_bot_iff _).1 $ eq.symm $ bot_eq_top_of_dim_eq_zero h) ⟨x, hx⟩ submodule.mem_top,
λ h, by rw [h, dim_bot]⟩
@[simp] theorem finrank_eq_zero {S : submodule K V} [finite_dimensional K S] :
finrank K S = 0 ↔ S = ⊥ :=
by rw [← dim_eq_zero, ← finrank_eq_dim, ← @nat.cast_zero cardinal, cardinal.nat_cast_inj]
end zero_dim
namespace submodule
open is_noetherian finite_dimensional
section division_ring
variables [division_ring K] [add_comm_group V] [module K V]
/-- A submodule is finitely generated if and only if it is finite-dimensional -/
theorem fg_iff_finite_dimensional (s : submodule K V) :
s.fg ↔ finite_dimensional K s :=
⟨λ h, module.finite_def.2 $ (fg_top s).2 h, λ h, (fg_top s).1 $ module.finite_def.1 h⟩
/-- A submodule contained in a finite-dimensional submodule is
finite-dimensional. -/
lemma finite_dimensional_of_le {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (h : S₁ ≤ S₂) :
finite_dimensional K S₁ :=
begin
haveI : is_noetherian K S₂ := iff_fg.2 infer_instance,
exact iff_fg.1 (is_noetherian.iff_dim_lt_aleph_0.2
(lt_of_le_of_lt (dim_le_of_submodule _ _ h) (dim_lt_aleph_0 K S₂))),
end
/-- The inf of two submodules, the first finite-dimensional, is
finite-dimensional. -/
instance finite_dimensional_inf_left (S₁ S₂ : submodule K V) [finite_dimensional K S₁] :
finite_dimensional K (S₁ ⊓ S₂ : submodule K V) :=
finite_dimensional_of_le inf_le_left
/-- The inf of two submodules, the second finite-dimensional, is
finite-dimensional. -/
instance finite_dimensional_inf_right (S₁ S₂ : submodule K V) [finite_dimensional K S₂] :
finite_dimensional K (S₁ ⊓ S₂ : submodule K V) :=
finite_dimensional_of_le inf_le_right
/-- The sup of two finite-dimensional submodules is
finite-dimensional. -/
instance finite_dimensional_sup (S₁ S₂ : submodule K V) [h₁ : finite_dimensional K S₁]
[h₂ : finite_dimensional K S₂] : finite_dimensional K (S₁ ⊔ S₂ : submodule K V) :=
begin
unfold finite_dimensional at *,
rw [finite_def] at *,
exact (fg_top _).2 (((fg_top S₁).1 h₁).sup ((fg_top S₂).1 h₂)),
end
/-- The submodule generated by a finite supremum of finite dimensional submodules is
finite-dimensional.
Note that strictly this only needs `∀ i ∈ s, finite_dimensional K (S i)`, but that doesn't
work well with typeclass search. -/
instance finite_dimensional_finset_sup {ι : Type*} (s : finset ι) (S : ι → submodule K V)
[Π i, finite_dimensional K (S i)] : finite_dimensional K (s.sup S : submodule K V) :=
begin
refine @finset.sup_induction _ _ _ _ s S (λ i, finite_dimensional K ↥i)
(finite_dimensional_bot K V) _ (λ i hi, by apply_instance),
{ introsI S₁ hS₁ S₂ hS₂,
exact submodule.finite_dimensional_sup S₁ S₂ },
end
/-- The submodule generated by a supremum of finite dimensional submodules, indexed by a finite
type is finite-dimensional. -/
instance finite_dimensional_supr {ι : Type*} [_root_.finite ι] (S : ι → submodule K V)
[Π i, finite_dimensional K (S i)] : finite_dimensional K ↥(⨆ i, S i) :=
begin
casesI nonempty_fintype ι,
rw ←finset.sup_univ_eq_supr,
exact submodule.finite_dimensional_finset_sup _ _,
end
/-- The submodule generated by a supremum indexed by a proposition is finite-dimensional if
the submodule is. -/
instance finite_dimensional_supr_prop {P : Prop} (S : P → submodule K V)
[Π h, finite_dimensional K (S h)] : finite_dimensional K ↥(⨆ h, S h) :=
begin
by_cases hp : P,
{ rw supr_pos hp,
apply_instance },
{ rw supr_neg hp,
apply_instance },
end
/-- The dimension of a submodule is bounded by the dimension of the ambient space. -/
lemma finrank_le [finite_dimensional K V] (s : submodule K V) : finrank K s ≤ finrank K V :=
by simpa only [cardinal.nat_cast_le, ←finrank_eq_dim] using
s.subtype.dim_le_of_injective (injective_subtype s)
/-- The dimension of a quotient is bounded by the dimension of the ambient space. -/
lemma finrank_quotient_le [finite_dimensional K V] (s : submodule K V) :
finrank K (V ⧸ s) ≤ finrank K V :=
by simpa only [cardinal.nat_cast_le, ←finrank_eq_dim] using
(mkq s).dim_le_of_surjective (surjective_quot_mk _)
/-- In a finite-dimensional vector space, the dimensions of a submodule and of the corresponding
quotient add up to the dimension of the space. -/
theorem finrank_quotient_add_finrank [finite_dimensional K V] (s : submodule K V) :
finrank K (V ⧸ s) + finrank K s = finrank K V :=
begin
have := dim_quotient_add_dim s,
rw [← finrank_eq_dim, ← finrank_eq_dim, ← finrank_eq_dim] at this,
exact_mod_cast this
end
/-- The dimension of a strict submodule is strictly bounded by the dimension of the ambient
space. -/
lemma finrank_lt [finite_dimensional K V] {s : submodule K V} (h : s < ⊤) :
finrank K s < finrank K V :=
begin
rw [← s.finrank_quotient_add_finrank, add_comm],
exact nat.lt_add_of_zero_lt_left _ _ (finrank_pos_iff.mpr (quotient.nontrivial_of_lt_top _ h))
end
/-- The sum of the dimensions of s + t and s ∩ t is the sum of the dimensions of s and t -/
theorem dim_sup_add_dim_inf_eq (s t : submodule K V)
[finite_dimensional K s] [finite_dimensional K t] :
finrank K ↥(s ⊔ t) + finrank K ↥(s ⊓ t) = finrank K ↥s + finrank K ↥t :=
begin
have key : module.rank K ↥(s ⊔ t) + module.rank K ↥(s ⊓ t) =
module.rank K s + module.rank K t := dim_sup_add_dim_inf_eq s t,
repeat { rw ←finrank_eq_dim at key },
norm_cast at key,
exact key
end
lemma dim_add_le_dim_add_dim (s t : submodule K V)
[finite_dimensional K s] [finite_dimensional K t] :
finrank K (s ⊔ t : submodule K V) ≤ finrank K s + finrank K t :=
by { rw [← dim_sup_add_dim_inf_eq], exact self_le_add_right _ _ }
lemma eq_top_of_disjoint [finite_dimensional K V] (s t : submodule K V)
(hdim : finrank K s + finrank K t = finrank K V)
(hdisjoint : disjoint s t) : s ⊔ t = ⊤ :=
begin
have h_finrank_inf : finrank K ↥(s ⊓ t) = 0,
{ rw [disjoint_iff_inf_le, le_bot_iff] at hdisjoint,
rw [hdisjoint, finrank_bot] },
apply eq_top_of_finrank_eq,
rw ←hdim,
convert s.dim_sup_add_dim_inf_eq t,
rw h_finrank_inf,
refl,
end
end division_ring
end submodule
namespace linear_equiv
open finite_dimensional
variables [division_ring K] [add_comm_group V] [module K V]
{V₂ : Type v'} [add_comm_group V₂] [module K V₂]
/-- Finite dimensionality is preserved under linear equivalence. -/
protected theorem finite_dimensional (f : V ≃ₗ[K] V₂) [finite_dimensional K V] :
finite_dimensional K V₂ :=
module.finite.equiv f
variables {R M M₂ : Type*} [ring R] [add_comm_group M] [add_comm_group M₂]
variables [module R M] [module R M₂]
end linear_equiv
section
variables [division_ring K] [add_comm_group V] [module K V]
instance finite_dimensional_finsupp {ι : Type*} [_root_.finite ι] [h : finite_dimensional K V] :
finite_dimensional K (ι →₀ V) :=
(finsupp.linear_equiv_fun_on_finite K V ι).symm.finite_dimensional
end
namespace finite_dimensional
section division_ring
variables [division_ring K] [add_comm_group V] [module K V]
{V₂ : Type v'} [add_comm_group V₂] [module K V₂]
/--
Two finite-dimensional vector spaces are isomorphic if they have the same (finite) dimension.
-/
theorem nonempty_linear_equiv_of_finrank_eq [finite_dimensional K V] [finite_dimensional K V₂]
(cond : finrank K V = finrank K V₂) : nonempty (V ≃ₗ[K] V₂) :=
nonempty_linear_equiv_of_lift_dim_eq $ by simp only [← finrank_eq_dim, cond, lift_nat_cast]
/--
Two finite-dimensional vector spaces are isomorphic if and only if they have the same (finite)
dimension.
-/
theorem nonempty_linear_equiv_iff_finrank_eq [finite_dimensional K V] [finite_dimensional K V₂] :
nonempty (V ≃ₗ[K] V₂) ↔ finrank K V = finrank K V₂ :=
⟨λ ⟨h⟩, h.finrank_eq, λ h, nonempty_linear_equiv_of_finrank_eq h⟩
variables (V V₂)
/--
Two finite-dimensional vector spaces are isomorphic if they have the same (finite) dimension.
-/
noncomputable def linear_equiv.of_finrank_eq [finite_dimensional K V] [finite_dimensional K V₂]
(cond : finrank K V = finrank K V₂) : V ≃ₗ[K] V₂ :=
classical.choice $ nonempty_linear_equiv_of_finrank_eq cond
variables {V}
lemma eq_of_le_of_finrank_le {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (hle : S₁ ≤ S₂)
(hd : finrank K S₂ ≤ finrank K S₁) : S₁ = S₂ :=
begin
rw ←linear_equiv.finrank_eq (submodule.comap_subtype_equiv_of_le hle) at hd,
exact le_antisymm hle (submodule.comap_subtype_eq_top.1 (eq_top_of_finrank_eq
(le_antisymm (comap (submodule.subtype S₂) S₁).finrank_le hd))),
end
/-- If a submodule is less than or equal to a finite-dimensional
submodule with the same dimension, they are equal. -/
lemma eq_of_le_of_finrank_eq {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (hle : S₁ ≤ S₂)
(hd : finrank K S₁ = finrank K S₂) : S₁ = S₂ :=
eq_of_le_of_finrank_le hle hd.ge
@[simp]
lemma finrank_map_subtype_eq (p : submodule K V) (q : submodule K p) :
finite_dimensional.finrank K (q.map p.subtype) = finite_dimensional.finrank K q :=
(submodule.equiv_subtype_map p q).symm.finrank_eq
variables {V₂} [finite_dimensional K V] [finite_dimensional K V₂]
/-- Given isomorphic subspaces `p q` of vector spaces `V` and `V₁` respectively,
`p.quotient` is isomorphic to `q.quotient`. -/
noncomputable def linear_equiv.quot_equiv_of_equiv
{p : subspace K V} {q : subspace K V₂}
(f₁ : p ≃ₗ[K] q) (f₂ : V ≃ₗ[K] V₂) : (V ⧸ p) ≃ₗ[K] (V₂ ⧸ q) :=
linear_equiv.of_finrank_eq _ _
begin
rw [← @add_right_cancel_iff _ _ (finrank K p), submodule.finrank_quotient_add_finrank,
linear_equiv.finrank_eq f₁, submodule.finrank_quotient_add_finrank,
linear_equiv.finrank_eq f₂],
end
/- TODO: generalize to the case where one of `p` and `q` is finite-dimensional. -/
/-- Given the subspaces `p q`, if `p.quotient ≃ₗ[K] q`, then `q.quotient ≃ₗ[K] p` -/
noncomputable def linear_equiv.quot_equiv_of_quot_equiv
{p q : subspace K V} (f : (V ⧸ p) ≃ₗ[K] q) : (V ⧸ q) ≃ₗ[K] p :=
linear_equiv.of_finrank_eq _ _
begin
rw [← @add_right_cancel_iff _ _ (finrank K q), submodule.finrank_quotient_add_finrank,
← linear_equiv.finrank_eq f, add_comm, submodule.finrank_quotient_add_finrank]
end
end division_ring
end finite_dimensional
namespace linear_map
open finite_dimensional
section division_ring
variables [division_ring K] [add_comm_group V] [module K V]
{V₂ : Type v'} [add_comm_group V₂] [module K V₂]
/-- On a finite-dimensional space, an injective linear map is surjective. -/
lemma surjective_of_injective [finite_dimensional K V] {f : V →ₗ[K] V}
(hinj : injective f) : surjective f :=
begin
have h := dim_eq_of_injective _ hinj,
rw [← finrank_eq_dim, ← finrank_eq_dim, nat_cast_inj] at h,
exact range_eq_top.1 (eq_top_of_finrank_eq h.symm)
end
/-- The image under an onto linear map of a finite-dimensional space is also finite-dimensional. -/
lemma finite_dimensional_of_surjective [finite_dimensional K V]
(f : V →ₗ[K] V₂) (hf : f.range = ⊤) : finite_dimensional K V₂ :=
module.finite.of_surjective f $ range_eq_top.1 hf
/-- The range of a linear map defined on a finite-dimensional space is also finite-dimensional. -/
instance finite_dimensional_range [finite_dimensional K V] (f : V →ₗ[K] V₂) :
finite_dimensional K f.range :=
f.quot_ker_equiv_range.finite_dimensional
/-- On a finite-dimensional space, a linear map is injective if and only if it is surjective. -/
lemma injective_iff_surjective [finite_dimensional K V] {f : V →ₗ[K] V} :
injective f ↔ surjective f :=
⟨surjective_of_injective,
λ hsurj, let ⟨g, hg⟩ := f.exists_right_inverse_of_surjective (range_eq_top.2 hsurj) in
have function.right_inverse g f, from linear_map.ext_iff.1 hg,
(left_inverse_of_surjective_of_right_inverse
(surjective_of_injective this.injective) this).injective⟩
lemma ker_eq_bot_iff_range_eq_top [finite_dimensional K V] {f : V →ₗ[K] V} :
f.ker = ⊥ ↔ f.range = ⊤ :=
by rw [range_eq_top, ker_eq_bot, injective_iff_surjective]
/-- In a finite-dimensional space, if linear maps are inverse to each other on one side then they
are also inverse to each other on the other side. -/
lemma mul_eq_one_of_mul_eq_one [finite_dimensional K V] {f g : V →ₗ[K] V} (hfg : f * g = 1) :
g * f = 1 :=
have ginj : injective g, from has_left_inverse.injective
⟨f, (λ x, show (f * g) x = (1 : V →ₗ[K] V) x, by rw hfg; refl)⟩,
let ⟨i, hi⟩ := g.exists_right_inverse_of_surjective
(range_eq_top.2 (injective_iff_surjective.1 ginj)) in
have f * (g * i) = f * 1, from congr_arg _ hi,
by rw [← mul_assoc, hfg, one_mul, mul_one] at this; rwa ← this
/-- In a finite-dimensional space, linear maps are inverse to each other on one side if and only if
they are inverse to each other on the other side. -/
lemma mul_eq_one_comm [finite_dimensional K V] {f g : V →ₗ[K] V} : f * g = 1 ↔ g * f = 1 :=
⟨mul_eq_one_of_mul_eq_one, mul_eq_one_of_mul_eq_one⟩
/-- In a finite-dimensional space, linear maps are inverse to each other on one side if and only if
they are inverse to each other on the other side. -/
lemma comp_eq_id_comm [finite_dimensional K V] {f g : V →ₗ[K] V} : f.comp g = id ↔ g.comp f = id :=
mul_eq_one_comm
/-- rank-nullity theorem : the dimensions of the kernel and the range of a linear map add up to
the dimension of the source space. -/
theorem finrank_range_add_finrank_ker [finite_dimensional K V] (f : V →ₗ[K] V₂) :
finrank K f.range + finrank K f.ker = finrank K V :=
by { rw [← f.quot_ker_equiv_range.finrank_eq], exact submodule.finrank_quotient_add_finrank _ }
end division_ring
end linear_map
namespace linear_equiv
open finite_dimensional
variables [division_ring K] [add_comm_group V] [module K V]
variables [finite_dimensional K V]
/-- The linear equivalence corresponging to an injective endomorphism. -/
noncomputable def of_injective_endo (f : V →ₗ[K] V) (h_inj : injective f) : V ≃ₗ[K] V :=
linear_equiv.of_bijective f h_inj $ linear_map.injective_iff_surjective.mp h_inj
@[simp] lemma coe_of_injective_endo (f : V →ₗ[K] V) (h_inj : injective f) :
⇑(of_injective_endo f h_inj) = f := rfl
@[simp] lemma of_injective_endo_right_inv (f : V →ₗ[K] V) (h_inj : injective f) :
f * (of_injective_endo f h_inj).symm = 1 :=
linear_map.ext $ (of_injective_endo f h_inj).apply_symm_apply
@[simp] lemma of_injective_endo_left_inv (f : V →ₗ[K] V) (h_inj : injective f) :
((of_injective_endo f h_inj).symm : V →ₗ[K] V) * f = 1 :=
linear_map.ext $ (of_injective_endo f h_inj).symm_apply_apply
end linear_equiv
namespace linear_map
variables [division_ring K] [add_comm_group V] [module K V]
lemma is_unit_iff_ker_eq_bot [finite_dimensional K V] (f : V →ₗ[K] V): is_unit f ↔ f.ker = ⊥ :=
begin
split,
{ rintro ⟨u, rfl⟩,
exact linear_map.ker_eq_bot_of_inverse u.inv_mul },
{ intro h_inj, rw ker_eq_bot at h_inj,
exact ⟨⟨f, (linear_equiv.of_injective_endo f h_inj).symm.to_linear_map,
linear_equiv.of_injective_endo_right_inv f h_inj,
linear_equiv.of_injective_endo_left_inv f h_inj⟩, rfl⟩ }
end
lemma is_unit_iff_range_eq_top [finite_dimensional K V] (f : V →ₗ[K] V): is_unit f ↔ f.range = ⊤ :=
by rw [is_unit_iff_ker_eq_bot, ker_eq_bot_iff_range_eq_top]
end linear_map
open module finite_dimensional
section
variables [division_ring K] [add_comm_group V] [module K V]
lemma finrank_zero_iff_forall_zero [finite_dimensional K V] :
finrank K V = 0 ↔ ∀ x : V, x = 0 :=
finrank_zero_iff.trans (subsingleton_iff_forall_eq 0)
/-- If `ι` is an empty type and `V` is zero-dimensional, there is a unique `ι`-indexed basis. -/
noncomputable def basis_of_finrank_zero [finite_dimensional K V]
{ι : Type*} [is_empty ι] (hV : finrank K V = 0) :
basis ι K V :=
begin
haveI : subsingleton V := finrank_zero_iff.1 hV,
exact basis.empty _
end
end
namespace linear_map
variables [division_ring K] [add_comm_group V] [module K V]
{V₂ : Type v'} [add_comm_group V₂] [module K V₂]
theorem injective_iff_surjective_of_finrank_eq_finrank [finite_dimensional K V]
[finite_dimensional K V₂] (H : finrank K V = finrank K V₂) {f : V →ₗ[K] V₂} :
function.injective f ↔ function.surjective f :=
begin
have := finrank_range_add_finrank_ker f,
rw [← ker_eq_bot, ← range_eq_top], refine ⟨λ h, _, λ h, _⟩,
{ rw [h, finrank_bot, add_zero, H] at this, exact eq_top_of_finrank_eq this },
{ rw [h, finrank_top, H] at this, exact finrank_eq_zero.1 (add_right_injective _ this) }
end
lemma ker_eq_bot_iff_range_eq_top_of_finrank_eq_finrank [finite_dimensional K V]
[finite_dimensional K V₂] (H : finrank K V = finrank K V₂) {f : V →ₗ[K] V₂} :
f.ker = ⊥ ↔ f.range = ⊤ :=
by rw [range_eq_top, ker_eq_bot, injective_iff_surjective_of_finrank_eq_finrank H]
theorem finrank_le_finrank_of_injective [finite_dimensional K V] [finite_dimensional K V₂]
{f : V →ₗ[K] V₂} (hf : function.injective f) : finrank K V ≤ finrank K V₂ :=
calc finrank K V
= finrank K f.range + finrank K f.ker : (finrank_range_add_finrank_ker f).symm
... = finrank K f.range : by rw [ker_eq_bot.2 hf, finrank_bot, add_zero]
... ≤ finrank K V₂ : submodule.finrank_le _
/-- Given a linear map `f` between two vector spaces with the same dimension, if
`ker f = ⊥` then `linear_equiv_of_injective` is the induced isomorphism
between the two vector spaces. -/
noncomputable def linear_equiv_of_injective
[finite_dimensional K V] [finite_dimensional K V₂]
(f : V →ₗ[K] V₂) (hf : injective f) (hdim : finrank K V = finrank K V₂) : V ≃ₗ[K] V₂ :=
linear_equiv.of_bijective f hf $
(linear_map.injective_iff_surjective_of_finrank_eq_finrank hdim).mp hf
@[simp] lemma linear_equiv_of_injective_apply
[finite_dimensional K V] [finite_dimensional K V₂]
{f : V →ₗ[K] V₂} (hf : injective f) (hdim : finrank K V = finrank K V₂) (x : V) :
f.linear_equiv_of_injective hf hdim x = f x := rfl
end linear_map
section
/-- A domain that is module-finite as an algebra over a field is a division ring. -/
noncomputable def division_ring_of_finite_dimensional
(F K : Type*) [field F] [ring K] [is_domain K]
[algebra F K] [finite_dimensional F K] : division_ring K :=
{ inv := λ x, if H : x = 0 then 0 else classical.some $
(show function.surjective (linear_map.mul_left F x), from
linear_map.injective_iff_surjective.1 $ λ _ _, (mul_right_inj' H).1) 1,
mul_inv_cancel := λ x hx, show x * dite _ _ _ = _, by { rw dif_neg hx,
exact classical.some_spec ((show function.surjective (linear_map.mul_left F x), from
linear_map.injective_iff_surjective.1 $ λ _ _, (mul_right_inj' hx).1) 1) },
inv_zero := dif_pos rfl,
.. ‹is_domain K›,
.. ‹ring K› }
/-- An integral domain that is module-finite as an algebra over a field is a field. -/
noncomputable def field_of_finite_dimensional
(F K : Type*) [field F] [comm_ring K] [is_domain K]
[algebra F K] [finite_dimensional F K] : field K :=
{ .. division_ring_of_finite_dimensional F K,
.. ‹comm_ring K› }
end
namespace submodule
section division_ring
variables [division_ring K] [add_comm_group V] [module K V]
{V₂ : Type v'} [add_comm_group V₂] [module K V₂]
lemma eq_top_of_finrank_eq [finite_dimensional K V] {S : submodule K V}
(h : finrank K S = finrank K V) :
S = ⊤ := finite_dimensional.eq_of_le_of_finrank_eq le_top (by simp [h, finrank_top])
lemma finrank_le_finrank_of_le {s t : submodule K V} [finite_dimensional K t]
(hst : s ≤ t) : finrank K s ≤ finrank K t :=
calc finrank K s = finrank K (comap t.subtype s) : (comap_subtype_equiv_of_le hst).finrank_eq.symm
... ≤ finrank K t : finrank_le _
lemma finrank_mono [finite_dimensional K V] :
monotone (λ (s : submodule K V), finrank K s) :=
λ s t, finrank_le_finrank_of_le
lemma finrank_lt_finrank_of_lt {s t : submodule K V} [finite_dimensional K t]
(hst : s < t) : finrank K s < finrank K t :=
(comap_subtype_equiv_of_le hst.le).finrank_eq.symm.trans_lt $
finrank_lt (le_top.lt_of_ne $ hst.not_le ∘ comap_subtype_eq_top.1)
lemma finrank_strict_mono [finite_dimensional K V] :
strict_mono (λ s : submodule K V, finrank K s) :=
λ s t, finrank_lt_finrank_of_lt
lemma finrank_add_eq_of_is_compl
[finite_dimensional K V] {U W : submodule K V} (h : is_compl U W) :
finrank K U + finrank K W = finrank K V :=
begin
rw [← dim_sup_add_dim_inf_eq, h.codisjoint.eq_top, h.disjoint.eq_bot, finrank_bot, add_zero],
exact finrank_top
end
end division_ring
end submodule
section division_ring
variables [division_ring K] [add_comm_group V] [module K V]
section span
open submodule
lemma finrank_span_singleton {v : V} (hv : v ≠ 0) : finrank K (K ∙ v) = 1 :=
begin
apply le_antisymm,
{ exact finrank_span_le_card ({v} : set V) },
{ rw [nat.succ_le_iff, finrank_pos_iff],
use [⟨v, mem_span_singleton_self v⟩, 0],
simp [hv] }
end
lemma set.finrank_mono [finite_dimensional K V] {s t : set V} (h : s ⊆ t) :
s.finrank K ≤ t.finrank K := finrank_mono (span_mono h)
end span
section basis
lemma span_eq_top_of_linear_independent_of_card_eq_finrank
{ι : Type*} [hι : nonempty ι] [fintype ι] {b : ι → V}
(lin_ind : linear_independent K b) (card_eq : fintype.card ι = finrank K V) :
span K (set.range b) = ⊤ :=
begin
by_cases fin : (finite_dimensional K V),
{ haveI := fin,
by_contra ne_top,
have lt_top : span K (set.range b) < ⊤ := lt_of_le_of_ne le_top ne_top,
exact ne_of_lt (submodule.finrank_lt lt_top) (trans (finrank_span_eq_card lin_ind) card_eq) },
{ exfalso,
apply ne_of_lt (fintype.card_pos_iff.mpr hι),
symmetry,
replace fin := (not_iff_not.2 is_noetherian.iff_fg).2 fin,
calc fintype.card ι = finrank K V : card_eq
... = 0 : dif_neg (mt is_noetherian.iff_dim_lt_aleph_0.mpr fin) }
end
/-- A linear independent family of `finrank K V` vectors forms a basis. -/
@[simps]
noncomputable def basis_of_linear_independent_of_card_eq_finrank
{ι : Type*} [nonempty ι] [fintype ι] {b : ι → V}
(lin_ind : linear_independent K b) (card_eq : fintype.card ι = finrank K V) :
basis ι K V :=
basis.mk lin_ind $
(span_eq_top_of_linear_independent_of_card_eq_finrank lin_ind card_eq).ge
@[simp] lemma coe_basis_of_linear_independent_of_card_eq_finrank
{ι : Type*} [nonempty ι] [fintype ι] {b : ι → V}
(lin_ind : linear_independent K b) (card_eq : fintype.card ι = finrank K V) :
⇑(basis_of_linear_independent_of_card_eq_finrank lin_ind card_eq) = b :=
basis.coe_mk _ _
/-- A linear independent finset of `finrank K V` vectors forms a basis. -/
@[simps]
noncomputable def finset_basis_of_linear_independent_of_card_eq_finrank
{s : finset V} (hs : s.nonempty)
(lin_ind : linear_independent K (coe : s → V)) (card_eq : s.card = finrank K V) :
basis s K V :=
@basis_of_linear_independent_of_card_eq_finrank _ _ _ _ _ _
⟨(⟨hs.some, hs.some_spec⟩ : s)⟩ _ _
lin_ind
(trans (fintype.card_coe _) card_eq)
@[simp] lemma coe_finset_basis_of_linear_independent_of_card_eq_finrank
{s : finset V} (hs : s.nonempty)
(lin_ind : linear_independent K (coe : s → V)) (card_eq : s.card = finrank K V) :
⇑(finset_basis_of_linear_independent_of_card_eq_finrank hs lin_ind card_eq) = coe :=
basis.coe_mk _ _
/-- A linear independent set of `finrank K V` vectors forms a basis. -/
@[simps]
noncomputable def set_basis_of_linear_independent_of_card_eq_finrank
{s : set V} [nonempty s] [fintype s]
(lin_ind : linear_independent K (coe : s → V)) (card_eq : s.to_finset.card = finrank K V) :
basis s K V :=
basis_of_linear_independent_of_card_eq_finrank lin_ind (trans s.to_finset_card.symm card_eq)
@[simp] lemma coe_set_basis_of_linear_independent_of_card_eq_finrank
{s : set V} [nonempty s] [fintype s]
(lin_ind : linear_independent K (coe : s → V)) (card_eq : s.to_finset.card = finrank K V) :
⇑(set_basis_of_linear_independent_of_card_eq_finrank lin_ind card_eq) = coe :=
basis.coe_mk _ _
end basis
/-!
We now give characterisations of `finrank K V = 1` and `finrank K V ≤ 1`.
-/
section finrank_eq_one
/--
A vector space with a nonzero vector `v` has dimension 1 iff `v` spans.
-/
lemma finrank_eq_one_iff_of_nonzero (v : V) (nz : v ≠ 0) :
finrank K V = 1 ↔ span K ({v} : set V) = ⊤ :=
⟨λ h, by simpa using (basis_singleton punit h v nz).span_eq,
λ s, finrank_eq_card_basis (basis.mk (linear_independent_singleton nz) (by { convert s, simp }))⟩
/--
A module with a nonzero vector `v` has dimension 1 iff every vector is a multiple of `v`.
-/
lemma finrank_eq_one_iff_of_nonzero' (v : V) (nz : v ≠ 0) :
finrank K V = 1 ↔ ∀ w : V, ∃ c : K, c • v = w :=
begin
rw finrank_eq_one_iff_of_nonzero v nz,
apply span_singleton_eq_top_iff,
end
/--
A module has dimension 1 iff there is some `v : V` so `{v}` is a basis.
-/
lemma finrank_eq_one_iff (ι : Type*) [unique ι] :
finrank K V = 1 ↔ nonempty (basis ι K V) :=
begin
fsplit,
{ intro h,
haveI := finite_dimensional_of_finrank (_root_.zero_lt_one.trans_le h.symm.le),
exact ⟨basis_unique ι h⟩ },
{ rintro ⟨b⟩,
simpa using finrank_eq_card_basis b }
end
/--
A module has dimension 1 iff there is some nonzero `v : V` so every vector is a multiple of `v`.
-/
lemma finrank_eq_one_iff' :
finrank K V = 1 ↔ ∃ (v : V) (n : v ≠ 0), ∀ w : V, ∃ c : K, c • v = w :=
begin
convert finrank_eq_one_iff punit,
simp only [exists_prop, eq_iff_iff, ne.def],
convert (basis.basis_singleton_iff punit).symm,
funext v,
simp,
apply_instance, apply_instance, -- Not sure why this aren't found automatically.
end
/--
A finite dimensional module has dimension at most 1 iff
there is some `v : V` so every vector is a multiple of `v`.
-/
lemma finrank_le_one_iff [finite_dimensional K V] :
finrank K V ≤ 1 ↔ ∃ (v : V), ∀ w : V, ∃ c : K, c • v = w :=
begin
fsplit,
{ intro h,
by_cases h' : finrank K V = 0,
{ use 0, intro w, use 0, haveI := finrank_zero_iff.mp h', apply subsingleton.elim, },
{ replace h' := zero_lt_iff.mpr h', have : finrank K V = 1, { linarith },
obtain ⟨v, -, p⟩ := finrank_eq_one_iff'.mp this,
use ⟨v, p⟩, }, },
{ rintro ⟨v, p⟩,
exact finrank_le_one v p, }
end
lemma submodule.finrank_le_one_iff_is_principal (W : submodule K V) [finite_dimensional K W] :
finrank K W ≤ 1 ↔ W.is_principal :=
by rw [← W.rank_le_one_iff_is_principal, ← finrank_eq_dim, ← cardinal.nat_cast_le, nat.cast_one]
lemma module.finrank_le_one_iff_top_is_principal [finite_dimensional K V] :
finrank K V ≤ 1 ↔ (⊤ : submodule K V).is_principal :=
by rw [← module.rank_le_one_iff_top_is_principal, ← finrank_eq_dim,
← cardinal.nat_cast_le, nat.cast_one]
-- We use the `linear_map.compatible_smul` typeclass here, to encompass two situations:
-- * `A = K`
-- * `[field K] [algebra K A] [is_scalar_tower K A V] [is_scalar_tower K A W]`
lemma surjective_of_nonzero_of_finrank_eq_one {W A : Type*} [semiring A]
[module A V] [add_comm_group W] [module K W] [module A W] [linear_map.compatible_smul V W K A]
(h : finrank K W = 1) {f : V →ₗ[A] W} (w : f ≠ 0) : surjective f :=
begin
change surjective (f.restrict_scalars K),
obtain ⟨v, n⟩ := fun_like.ne_iff.mp w,
intro z,
obtain ⟨c, rfl⟩ := (finrank_eq_one_iff_of_nonzero' (f v) n).mp h z,
exact ⟨c • v, by simp⟩,
end
/-- Any `K`-algebra module that is 1-dimensional over `K` is simple. -/
lemma is_simple_module_of_finrank_eq_one {A} [semiring A] [module A V] [has_smul K A]
[is_scalar_tower K A V] (h : finrank K V = 1) : is_simple_order (submodule A V) :=
begin
haveI := nontrivial_of_finrank_eq_succ h,
refine ⟨λ S, or_iff_not_imp_left.2 (λ hn, _)⟩,
rw ← restrict_scalars_inj K at hn ⊢,
haveI := finite_dimensional_of_finrank_eq_succ h,
refine eq_top_of_finrank_eq ((submodule.finrank_le _).antisymm _),
simpa only [h, finrank_bot] using submodule.finrank_strict_mono (ne.bot_lt hn),
end
end finrank_eq_one
end division_ring
section subalgebra_dim
open module
variables {F E : Type*} [field F] [ring E] [algebra F E]
/-- A `subalgebra` is `finite_dimensional` iff it is finite_dimensional as a submodule. -/
lemma subalgebra.finite_dimensional_to_submodule {S : subalgebra F E} :
finite_dimensional F S.to_submodule ↔ finite_dimensional F S := iff.rfl
alias subalgebra.finite_dimensional_to_submodule ↔
finite_dimensional.of_subalgebra_to_submodule finite_dimensional.subalgebra_to_submodule
instance finite_dimensional.finite_dimensional_subalgebra [finite_dimensional F E]
(S : subalgebra F E) : finite_dimensional F S :=
finite_dimensional.of_subalgebra_to_submodule infer_instance
instance subalgebra.finite_dimensional_bot : finite_dimensional F (⊥ : subalgebra F E) :=
by { nontriviality E, exact finite_dimensional_of_dim_eq_one subalgebra.dim_bot }
lemma subalgebra.eq_bot_of_dim_le_one {S : subalgebra F E} (h : module.rank F S ≤ 1) : S = ⊥ :=
begin
nontriviality E,
obtain ⟨m, hm, he⟩ := cardinal.exists_nat_eq_of_le_nat (h.trans_eq nat.cast_one.symm),
haveI := finite_dimensional_of_dim_eq_nat he,
rw [← not_bot_lt_iff, ← subalgebra.to_submodule.lt_iff_lt],
haveI := (S.to_submodule_equiv).symm.finite_dimensional,
refine λ hl, (submodule.finrank_lt_finrank_of_lt hl).not_le (nat_cast_le.1 _),
iterate 2 { rw [subalgebra.finrank_to_submodule, finrank_eq_dim] },
exact h.trans_eq subalgebra.dim_bot.symm,
end
lemma subalgebra.eq_bot_of_finrank_one {S : subalgebra F E} (h : finrank F S = 1) : S = ⊥ :=
subalgebra.eq_bot_of_dim_le_one $
by { haveI := finite_dimensional_of_finrank_eq_succ h, rw [← finrank_eq_dim, h, nat.cast_one] }
@[simp]
theorem subalgebra.dim_eq_one_iff [nontrivial E] {S : subalgebra F E} :
module.rank F S = 1 ↔ S = ⊥ :=
⟨λ h, subalgebra.eq_bot_of_dim_le_one h.le, λ h, h.symm ▸ subalgebra.dim_bot⟩
@[simp]
theorem subalgebra.finrank_eq_one_iff [nontrivial E] {S : subalgebra F E} :
finrank F S = 1 ↔ S = ⊥ :=
⟨subalgebra.eq_bot_of_finrank_one, λ h, h.symm ▸ subalgebra.finrank_bot⟩
lemma subalgebra.bot_eq_top_iff_dim_eq_one [nontrivial E] :
(⊥ : subalgebra F E) = ⊤ ↔ module.rank F E = 1 :=
by rw [← dim_top, ← subalgebra_top_dim_eq_submodule_top_dim, subalgebra.dim_eq_one_iff, eq_comm]
lemma subalgebra.bot_eq_top_iff_finrank_eq_one [nontrivial E] :
(⊥ : subalgebra F E) = ⊤ ↔ finrank F E = 1 :=
by rw [← finrank_top, ← subalgebra_top_finrank_eq_submodule_top_finrank,
subalgebra.finrank_eq_one_iff, eq_comm]
alias subalgebra.bot_eq_top_iff_dim_eq_one ↔ _ subalgebra.bot_eq_top_of_dim_eq_one
alias subalgebra.bot_eq_top_iff_finrank_eq_one ↔ _ subalgebra.bot_eq_top_of_finrank_eq_one
attribute [simp] subalgebra.bot_eq_top_of_finrank_eq_one subalgebra.bot_eq_top_of_dim_eq_one
lemma subalgebra.is_simple_order_of_finrank (hr : finrank F E = 2) :
is_simple_order (subalgebra F E) :=
let i := nontrivial_of_finrank_pos (zero_lt_two.trans_eq hr.symm) in by exactI
{ to_nontrivial :=
⟨⟨⊥, ⊤, λ h, by cases hr.symm.trans (subalgebra.bot_eq_top_iff_finrank_eq_one.1 h)⟩⟩,
eq_bot_or_eq_top :=
begin
intro S,
haveI : finite_dimensional F E := finite_dimensional_of_finrank_eq_succ hr,
haveI : finite_dimensional F S :=
finite_dimensional.finite_dimensional_submodule S.to_submodule,
have : finrank F S ≤ 2 := hr ▸ S.to_submodule.finrank_le,
have : 0 < finrank F S := finrank_pos_iff.mpr infer_instance,
interval_cases (finrank F S),
{ left, exact subalgebra.eq_bot_of_finrank_one h, },
{ right, rw ← hr at h,
rw ← algebra.to_submodule_eq_top,
exact submodule.eq_top_of_finrank_eq h, },
end }
end subalgebra_dim
namespace module
namespace End
variables [division_ring K] [add_comm_group V] [module K V]
lemma exists_ker_pow_eq_ker_pow_succ [finite_dimensional K V] (f : End K V) :
∃ (k : ℕ), k ≤ finrank K V ∧ (f ^ k).ker = (f ^ k.succ).ker :=
begin
classical,
by_contradiction h_contra,
simp_rw [not_exists, not_and] at h_contra,
have h_le_ker_pow : ∀ (n : ℕ), n ≤ (finrank K V).succ → n ≤ finrank K (f ^ n).ker,
{ intros n hn,
induction n with n ih,
{ exact zero_le (finrank _ _) },
{ have h_ker_lt_ker : (f ^ n).ker < (f ^ n.succ).ker,
{ refine lt_of_le_of_ne _ (h_contra n (nat.le_of_succ_le_succ hn)),
rw pow_succ,
apply linear_map.ker_le_ker_comp },
have h_finrank_lt_finrank : finrank K (f ^ n).ker < finrank K (f ^ n.succ).ker,
{ apply submodule.finrank_lt_finrank_of_lt h_ker_lt_ker },
calc
n.succ ≤ (finrank K ↥(linear_map.ker (f ^ n))).succ :
nat.succ_le_succ (ih (nat.le_of_succ_le hn))
... ≤ finrank K ↥(linear_map.ker (f ^ n.succ)) :
nat.succ_le_of_lt h_finrank_lt_finrank } },
have h_le_finrank_V : ∀ n, finrank K (f ^ n).ker ≤ finrank K V :=
λ n, submodule.finrank_le _,
have h_any_n_lt: ∀ n, n ≤ (finrank K V).succ → n ≤ finrank K V :=
λ n hn, (h_le_ker_pow n hn).trans (h_le_finrank_V n),
show false,
from nat.not_succ_le_self _ (h_any_n_lt (finrank K V).succ (finrank K V).succ.le_refl),
end
lemma ker_pow_constant {f : End K V} {k : ℕ} (h : (f ^ k).ker = (f ^ k.succ).ker) :
∀ m, (f ^ k).ker = (f ^ (k + m)).ker
| 0 := by simp
| (m + 1) :=
begin
apply le_antisymm,
{ rw [add_comm, pow_add],
apply linear_map.ker_le_ker_comp },
{ rw [ker_pow_constant m, add_comm m 1, ←add_assoc, pow_add, pow_add f k m],
change linear_map.ker ((f ^ (k + 1)).comp (f ^ m)) ≤ linear_map.ker ((f ^ k).comp (f ^ m)),
rw [linear_map.ker_comp, linear_map.ker_comp, h, nat.add_one],
exact le_rfl, }
end
lemma ker_pow_eq_ker_pow_finrank_of_le [finite_dimensional K V]
{f : End K V} {m : ℕ} (hm : finrank K V ≤ m) :
(f ^ m).ker = (f ^ finrank K V).ker :=
begin
obtain ⟨k, h_k_le, hk⟩ :
∃ k, k ≤ finrank K V ∧ linear_map.ker (f ^ k) = linear_map.ker (f ^ k.succ) :=
exists_ker_pow_eq_ker_pow_succ f,
calc (f ^ m).ker = (f ^ (k + (m - k))).ker :
by rw add_tsub_cancel_of_le (h_k_le.trans hm)
... = (f ^ k).ker : by rw ker_pow_constant hk _
... = (f ^ (k + (finrank K V - k))).ker : ker_pow_constant hk (finrank K V - k)
... = (f ^ finrank K V).ker : by rw add_tsub_cancel_of_le h_k_le
end
lemma ker_pow_le_ker_pow_finrank [finite_dimensional K V] (f : End K V) (m : ℕ) :
(f ^ m).ker ≤ (f ^ finrank K V).ker :=
begin
by_cases h_cases: m < finrank K V,
{ rw [←add_tsub_cancel_of_le (nat.le_of_lt h_cases), add_comm, pow_add],
apply linear_map.ker_le_ker_comp },
{ rw [ker_pow_eq_ker_pow_finrank_of_le (le_of_not_lt h_cases)],
exact le_rfl }
end
end End
end module
section module
open module
open_locale cardinal
lemma cardinal_mk_eq_cardinal_mk_field_pow_dim
(K V : Type u) [division_ring K] [add_comm_group V] [module K V] [finite_dimensional K V] :
#V = #K ^ module.rank K V :=
begin
let s := basis.of_vector_space_index K V,
let hs := basis.of_vector_space K V,
calc #V = #(s →₀ K) : quotient.sound ⟨hs.repr.to_equiv⟩
... = #(s → K) : quotient.sound ⟨finsupp.equiv_fun_on_finite⟩
... = _ : by rw [← cardinal.lift_inj.1 hs.mk_eq_dim, cardinal.power_def]
end
lemma cardinal_lt_aleph_0_of_finite_dimensional
(K V : Type u) [division_ring K] [add_comm_group V] [module K V]
[_root_.finite K] [finite_dimensional K V] :
#V < ℵ₀ :=
begin
letI : is_noetherian K V := is_noetherian.iff_fg.2 infer_instance,
rw cardinal_mk_eq_cardinal_mk_field_pow_dim K V,
exact cardinal.power_lt_aleph_0 (cardinal.lt_aleph_0_of_finite K)
(is_noetherian.dim_lt_aleph_0 K V),
end
end module
|
a7b7cacc2ba8a7c630687d184b2db4c5ff0d5eab | d8820d2c92be8052d13f9c8f8c483a6e15c5f566 | /src/M40002/sequences.lean | 290a79b6276a30a8a7e493823f12171d263d524f | [] | no_license | JasonKYi/M4000x_LEAN_formalisation | 4a19b84f6d0fe2e214485b8532e21cd34996c4b1 | 6e99793f2fcbe88596e27644f430e46aa2a464df | refs/heads/master | 1,599,755,414,708 | 1,589,494,604,000 | 1,589,494,604,000 | 221,759,483 | 8 | 1 | null | 1,589,494,605,000 | 1,573,755,201,000 | Lean | UTF-8 | Lean | false | false | 21,927 | lean | -- begin header
import M40002.complete
namespace sequences
-- end header
/- Section
Chapter 3. Sequences
-/
/- Sub-section
Definitions
-/
/-
Let $a : ℕ → ℝ$ be a real valued sequence, then we define convergence of $a$ to some
real $l$ in the standard way.
-/
/- Definition
A real valued sequence $a_n : ℕ → ℝ$ is said to converge to $l ∈ ℝ$ if and only if for all
$ε > 0$, there exists $N ∈ ℕ$ such that for all $n ≥ N$, $\left| a_n - l \right| < ε$.
-/
def converges_to (a : ℕ → ℝ) (l : ℝ) := ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, abs (a n - l) < ε
notation a ` ⇒ ` l := converges_to a l
/- Definition
We call $a_n : ℕ → ℝ$ convergent if there exists $l ∈ ℝ$, $a_n$ converges to $l$.
-/
def is_convergent (a : ℕ → ℝ) := ∃ l : ℝ, ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, abs (a n - l) < ε
/- Definition
We call $a_n : ℕ → ℝ$ bounede above if and only if there exists $R ∈ ℝ$ such that for all
$n ∈ ℕ$, $a_n ≤ R$.
-/
def seq_bounded_above (a : ℕ → ℝ) := ∃ R : ℝ, ∀ m : ℕ, a m ≤ R
/- Definition
We definte bounded below in a similar way.
-/
def seq_bounded_below (a : ℕ → ℝ) := ∃ R : ℝ, ∀ m : ℕ, R ≤ a m
/- Definition
We call $a_n : ℕ → ℝ$ bounded if and only if it is bounded above and below.
-/
def seq_bounded (a : ℕ → ℝ) := seq_bounded_above a ∧ seq_bounded_below a
def seq_in (a : ℕ → ℝ) (S : set ℝ) := ∀ n : ℕ, a n ∈ S
notation a ` ⊆ ` S := seq_in a S
example (n : ℕ) (hn : 0 < n) : 0 ≤ 1 / n := by exact bot_le
/- Example
Let $a_n : ℕ → ℝ : n ↦ 1 / n$, then $a_n$ converges to 0.
-/
example : (λ n : ℕ, 1 / n) ⇒ 0 :=
begin
-- We first fix $ε > 0$.
intros ε hε,
-- Then by choosing some $N ∈ ℕ$ such that $N > 1 / ε$,
cases (exists_nat_gt (1 / ε)) with N hN,
-- we now need to show that for all $n ≥ N$, $\left| a_n - 0 \right| < ε$.
refine ⟨N, λ n hn, _⟩,
-- Now as $\left| a_n - 0 \right| = a_n = 1 / n$, it suffices to show that $1 / n < ε$.
rw [sub_zero, abs_of_nonneg, (one_div_lt _ hε)],
{ refine lt_of_lt_of_le hN (by norm_cast; assumption) },
-- But this follows from the transitivity of inequalities as $1 / n ≤ 1 / N ≤ ε$.
{ refine lt_trans (one_div_pos_of_pos hε) (lt_of_lt_of_le hN (by norm_cast; assumption)) },
{ simp [bot_le] }
end
/- Example
Let $a_n : ℕ → ℝ : n ↦ c$ for some $c ∈ ℝ$. Then $a_n$ converges to $c$
-/
theorem cons_conv {c : ℝ} : (λ n : ℕ, c) ⇒ c :=
begin
-- Again we fix $ε > 0$
intros ε hε,
-- Then by simply choosing our $N = 0$,
refine ⟨0, λ n hn, _⟩,
-- it suffices to show that for all $n ∈ ℕ$, $\left| a_n - c \right| < ε$.
-- But $\left| a_n - c \right|$ is simply zero, so we are done!
simpa
end
/-
We will now prove a very useful lemma that will come up now an again.
-/
/- Lemma
If $x_0$ and $x_1$ are real numbers such that for all $ε > 0$, $\left| x₀ - x₁ \right| < ε$,
then $x_0 = x_1$.
-/
lemma dist_zero {x₀ x₁ : ℝ}
(h : ∀ (ε : ℝ) (hε : 0 < ε), abs (x₀ - x₁) < ε ) : x₀ = x₁ :=
begin
-- We will attempt to prove by contradiction, so suppose $x₀ ≠ x₁$.
apply classical.by_contradiction, intro hne,
-- Then by trichotomy, either $x₀ < x₁$ or $x₁ < x₀$.
cases lt_or_gt_of_ne hne with hlt hgt,
-- If $x₀ < x₁$ then by letting $ε = x₁ - x₀$ we have $\left| x₀ - x₁ \right| < x₀ - x₁$.
{ refine not_le.2 (h (x₁ - x₀) (sub_pos.2 hlt)) _,
-- But this is a contradiction as for all $r ∈ ℝ$, \left| r \right| ≥ r$.
rw abs_sub, exact le_abs_self _ },
-- It's a similar story if $x₁ < x₀$.
{ refine not_le.2 (h (x₀ - x₁) (sub_pos.2 hgt)) ( le_abs_self _) }
end
/-
With that, we will present a short proof that the limits of sequences are unique.
-/
/- Theorem
Let $a_n : ℕ → ℝ$ converge to $b$ and $c$ both of which are real. Then $b = c$.
-/
theorem unique_lim {a : ℕ → ℝ} {b c : ℝ} (hb : a ⇒ b) (hc : a ⇒ c) : b = c :=
begin
-- By the previous lemma, it suffices to show that for all $ε > 0, \left| b - c \right| < ε$.
apply dist_zero,
-- So let us fix ε > 0.
intros ε hε,
-- Then as $a_n$ converges to $b$,
-- there exists some $N₀ ∈ ℕ$ for all $n ≥ N₀, \left a_n - b \right < ε / 2$.
cases hb (ε / 2) (half_pos hε) with N₀ hN₀,
-- Similarly there must be some $N₁ ∈ ℕ$ for all $n ≥ N₁, \left a_n - c \right < ε / 2$.
cases hc (ε / 2) (half_pos hε) with N₁ hN₁,
-- So let's $N = \max \{N₀, N₁\}$.
let N := max N₀ N₁,
-- Then by the triangle inequality,
-- we have $\left| b - c \right| ≤ \left| b - a_N \right| + \left| a_N - c \right| < ε / 2 + ε / 2 = ε$.
apply lt_of_le_of_lt (abs_sub_le b (a N) c),
linarith [show abs (b - a N) < ε / 2, by rw abs_sub; from hN₀ N (le_max_left _ _),
hN₁ N (le_max_right _ _)]
end
#exit
-- If (a n) is convergent then its bounded
lemma converge_is_bdd_abv (b : ℕ → ℝ) : is_convergent b → seq_bounded_above b :=
begin
rintro ⟨l, hl⟩,
cases (hl 1 _) with N hN,
swap, linarith,
let U := finset.image b (finset.range (N + 1)) ∪ {l + 1},
have : b 0 ∈ U := by simp,
cases finset.max_of_mem this with R hR,
use R, intro m,
cases le_or_lt m N,
{have : b m ∈ U :=
by{simp, left, use m, from ⟨(nat_le_imp_lt_succ N m).mp h, rfl⟩},
from finset.le_max_of_mem this hR
},
{have : l + 1 ∈ U := by {simp},
replace this : l + 1 ≤ R :=
by {from finset.le_max_of_mem this hR},
apply le_trans _ this,
replace this : abs (b m - l) < 1 := hN m (le_of_lt h),
rw abs_lt at this,
from le_of_lt (sub_lt_iff_lt_add'.mp this.right)
}
end
lemma converge_is_bdd_blw (b : ℕ → ℝ) : is_convergent b → seq_bounded_below b :=
begin
rintro ⟨l, hl⟩,
cases (hl 1 _) with N hN,
swap, linarith,
let U := finset.image b (finset.range (N + 1)) ∪ {l + -1},
have : b 0 ∈ U := by simp,
cases finset.min_of_mem this with R hR,
use R, intro m,
cases le_or_lt m N,
{have : b m ∈ U :=
by{simp, left, use m, from ⟨(nat_le_imp_lt_succ N m).mp h, rfl⟩},
from finset.min_le_of_mem this hR
},
{have : l + -1 ∈ U := by {simp},
replace this : R ≤ l + -1 :=
by {from finset.min_le_of_mem this hR},
apply le_trans this,
replace this : abs (b m - l) < 1 := hN m (le_of_lt h),
rw abs_lt at this,
from le_of_lt (lt_sub_iff_add_lt'.mp this.left)
}
end
theorem converge_is_bdd (b : ℕ → ℝ) : is_convergent b → seq_bounded b := λ h, ⟨converge_is_bdd_abv b h, converge_is_bdd_blw b h⟩
-- Defining addition for sequences
def seq_add_seq (a : ℕ → ℝ) (b : ℕ → ℝ) := λ n : ℕ, a n + b n
notation a ` + ` b := seq_add_seq a b
def seq_add_real (a : ℕ → ℝ) (b : ℝ) := λ n : ℕ, a n + b
notation a ` + ` b := seq_add_real a b
-- Algebra of limits
theorem add_lim_conv (a b : ℕ → ℝ) (l m : ℝ) : a ⇒ l ∧ b ⇒ m → (a + b) ⇒ (l + m) :=
begin
rintros ⟨ha, hb⟩ ε hε,
have : ε / 2 > 0 := half_pos hε,
cases ha (ε / 2) this with N₁ hN₁,
cases hb (ε / 2) this with N₂ hN₂,
let N : ℕ := max N₁ N₂,
use N,
intros n hn,
have hrw : a n + b n - (l + m) = (a n - l) + (b n - m) := by {linarith},
unfold seq_add_seq,
rw hrw,
have hmax : N ≥ N₁ ∧ N ≥ N₂ :=
by {split,
all_goals {rwa [ge_iff_le, le_max_iff], tauto}},
suffices h : abs (a n - l) + abs (b n - m) < ε,
from lt_of_le_of_lt (abs_add (a n - l) (b n - m)) h,
have h : abs (a n - l) + abs (b n - m) < ε / 2 + ε / 2 :=
by {from add_lt_add (hN₁ n (ge_trans hn hmax.left)) (hN₂ n (ge_trans hn hmax.right))},
rwa add_halves' ε at h
end
lemma diff_seq_is_zero (a b : ℕ → ℝ) (l : ℝ) (h : a ⇒ l) : a = b + l → b ⇒ 0 :=
begin
unfold seq_add_real, unfold converges_to,
unfold converges_to at h,
intro ha,
rw ha at h, simp at h,
suffices : ∀ (ε : ℝ), 0 < ε → (∃ (N : ℕ), ∀ (n : ℕ), N ≤ n → abs (b n) < ε),
simpa,
assumption
end
-- Defining multiplication of sequences
def seq_mul_seq (a : ℕ → ℝ) (b : ℕ → ℝ) := λ n : ℕ, a n * b n
notation a ` × ` b := seq_mul_seq a b
def seq_mul_real (a : ℕ → ℝ) (b : ℝ) := λ n : ℕ, a n * b
notation a ` × ` b := seq_mul_real a b
theorem mul_lim_conv (a b : ℕ → ℝ) (l m : ℝ) (ha : a ⇒ l) (hb : b ⇒ m) : (a × b) ⇒ l * m :=
begin
sorry
end
-- Defining division of sequences
noncomputable def seq_div_seq (a : ℕ → ℝ) (b : ℕ → ℝ) := λ n : ℕ, (a n) / (b n)
noncomputable instance : has_div (ℕ → ℝ) := ⟨seq_div_seq⟩
theorem div_lim_conv (a b : ℕ → ℝ) (l m : ℝ) (ha : a ⇒ l) (hb : b ⇒ m) (hc : m ≠ 0) : (a / b) ⇒ l / m :=
begin
sorry
end
-- Defining monotone increasing and decreasing sequences
def mono_increasing (a : ℕ → ℝ) := ∀ n : ℕ, a n ≤ a (n + 1)
notation a ` ↑ ` := mono_increasing a
def mono_increasing_conv (a : ℕ → ℝ) (l : ℝ) := mono_increasing a ∧ a ⇒ l
notation a ` ↑ ` l := mono_increasing a l
def mono_decreasing (a : ℕ → ℝ) := ∀ n : ℕ, a (n + 1) ≤ a n
notation a ` ↓ ` := mono_decreasing a
def mono_decreasing_conv (a : ℕ → ℝ) (l : ℝ) := mono_decreasing a ∧ a ⇒ l
notation a ` ↓ ` l := mono_decreasing a l
lemma le_chain (N : ℕ) (b : ℕ → ℝ) (h : mono_increasing b) : ∀ n : ℕ, N ≤ n → b N ≤ b n :=
begin
intros n hn,
have ha : ∀ k : ℕ, b N ≤ b (N + k) :=
by {intro k,
induction k with k hk,
{refl},
{from le_trans hk (h (N + k))}
},
have : ∃ k : ℕ, N + k = n := nat.le.dest hn,
cases this with k hk,
rw ←hk,
from ha k
end
lemma ge_chain (N : ℕ) (b : ℕ → ℝ) (h : mono_decreasing b) : ∀ n : ℕ, N ≤ n → b n ≤ b N :=
begin
intros n hn,
have ha : ∀ k : ℕ, b (N + k) ≤ b N :=
by {intro k,
induction k with k hk,
{refl},
{from le_trans (h (N + k)) hk}
},
have : ∃ k : ℕ, N + k = n := nat.le.dest hn,
cases this with k hk,
rw ←hk,
from ha k
end
-- Monotone increasing and bounded means convergent (to the supremum)
lemma mono_increasing_means_conv_sup (b : ℕ → ℝ) (M : ℝ) (h₁ : mono_increasing b) (h₂ : seq_bounded b) (h₃ : sup {t : ℝ | ∃ n : ℕ, t = b n} M) : b ⇒ M :=
begin
rcases h₂ with ⟨⟨N, habv⟩, hblw⟩,
intros ε hε,
clear habv N,
have : ∃ N : ℕ, M - ε < b N :=
by {cases h₃ with hubd hnubd,
unfold upper_bound at hnubd,
push_neg at hnubd,
have : M - ε < M :=
by {rw gt_iff_lt at hε,
from sub_lt_self M hε},
rcases hnubd (M - ε) this with ⟨s, ⟨hs₁, hs₂⟩⟩,
rw set.mem_set_of_eq at hs₁,
cases hs₁ with n hn,
use n, rwa ←hn
},
cases this with N hN,
use N, intros n hn,
rw abs_of_nonpos,
{have : ∀ n : ℕ, N ≤ n → b N ≤ b n := le_chain N b h₁,
suffices : M - ε < b n,
simp, from sub_lt.mp this,
from lt_of_lt_of_le hN (this n (iff.rfl.mp hn))
},
cases h₃,
have : b n ≤ M := by {apply h₃_left, rwa set.mem_set_of_eq, use n},
from sub_nonpos_of_le this
end
theorem mono_increasing_means_conv (b : ℕ → ℝ) (h₁ : mono_increasing b) (h₂ : seq_bounded b) : is_convergent b :=
begin
let α : set ℝ := {t : ℝ | ∃ n : ℕ, t = b n},
have : ∃ M : ℝ, sup α M :=
by {rcases h₂ with ⟨⟨R, habv⟩, hblw⟩,
apply completeness α,
{use R, rintros s ⟨n, hs⟩,
suffices : b n ≤ R, rwa ←hs at this,
from habv n
},
{suffices : b 0 ∈ α,
apply set.not_eq_empty_iff_exists.mpr,
use b 0, assumption,
rw set.mem_set_of_eq,
use 0
}
},
cases this with M hM,
use M,
from mono_increasing_means_conv_sup b M h₁ h₂ hM
end
-- Monotone decreasing and bounded means convergent (to the infimum)
lemma mono_decreasing_means_conv_inf (b : ℕ → ℝ) (M : ℝ) (h₁ : mono_decreasing b) (h₂ : seq_bounded b) (h₃ : inf {t : ℝ | ∃ n : ℕ, t = b n} M) : b ⇒ M :=
begin
intros ε hε,
have : ∃ N : ℕ, b N < M + ε :=
by {cases h₃ with hlbd hnlbd,
unfold lower_bound at hnlbd,
push_neg at hnlbd,
have : M < M + ε := by {linarith},
rcases hnlbd (M + ε) this with ⟨s, ⟨hs₁, hs₂⟩⟩,
rw set.mem_set_of_eq at hs₁,
cases hs₁ with n hn,
use n, rwa ←hn
},
cases this with N hN,
use N, intros n hn,
rw abs_lt, split,
{suffices : M - ε < b n, linarith,
have : M ≤ b n := by {apply h₃.left (b n), rw set.mem_set_of_eq, use n},
have hα : M - ε < M := by {linarith},
from lt_of_lt_of_le hα this
},
{suffices : b n < M + ε, linarith,
from lt_of_le_of_lt (ge_chain N b h₁ n (iff.rfl.mp hn)) hN
}
end
theorem mono_decreasing_means_conv (b : ℕ → ℝ) (h₁ : mono_decreasing b) (h₂ : seq_bounded b) : is_convergent b :=
begin
let α : set ℝ := {t : ℝ | ∃ n : ℕ, t = b n},
have : ∃ M : ℝ, inf α M :=
by {rcases h₂ with ⟨habv, ⟨R, hblw⟩⟩,
apply completeness_below α,
{use R, rintros s ⟨n, hs⟩,
rw hs,
from hblw n
},
{suffices : b 0 ∈ α,
apply set.not_eq_empty_iff_exists.mpr,
use b 0, assumption,
rw set.mem_set_of_eq,
use 0
}
},
cases this with M hM,
use M,
from mono_decreasing_means_conv_inf b M h₁ h₂ hM
end
-- Defining order on sequences (is this necessary?)
def le_seq (a b : ℕ → ℝ) := ∀ n : ℕ, a n ≤ b n
notation a ` ≤* ` b := le_seq a b
def lt_seq (a b : ℕ → ℝ) := ∀ n : ℕ, a n < b n
notation a ` <* ` b := lt_seq a b
def ge_seq (a b : ℕ → ℝ) := ∀ n : ℕ, a n ≥ b n
notation a ` ≥* ` b := ge_seq a b
def gt_seq (a b : ℕ → ℝ) := ∀ n : ℕ, a n > b n
notation a ` >* ` b := gt_seq a b
-- Comparison of sequences
theorem le_lim (a b : ℕ → ℝ) (l m : ℝ) (ha : a ⇒ l) (hb : b ⇒ m) : (a ≤* b) → l ≤ m :=
begin
rw ←not_lt,
intros h hlt,
have hδ : (l - m) / 2 > 0 := half_pos (sub_pos.mpr hlt),
cases ha ((l - m) / 2) hδ with N₁ hN₁,
cases hb ((l - m) / 2) hδ with N₂ hN₂,
let N := max N₁ N₂,
have hmax : N ≥ N₁ ∧ N ≥ N₂ :=
by {split,
all_goals {rwa [ge_iff_le, le_max_iff], tauto}},
replace hN₁ : abs (a N - l) < (l - m) / 2 := hN₁ N hmax.left,
replace hN₂ : abs (b N - m) < (l - m) / 2 := hN₂ N hmax.right,
have hα : (l + m) / 2 < a N :=
by {rw abs_lt at hN₁,
cases hN₁ with hl hr,
linarith
},
have hβ : b N < (l + m) / 2 :=
by {rw abs_lt at hN₂,
cases hN₂ with hl hr,
linarith
},
have : b N < a N := lt_trans hβ hα,
rw ←not_le at this,
from this (h N)
end
-- Sandwich Theorem. Suppose that an ≤ bn ≤ cn ∀n and that an → a and cn → a, Then bn → a.
theorem sandwich {a b c : ℕ → ℝ} {l : ℝ} (h₀ : a ⇒ l) (h₁ : c ⇒ l) : (a ≤* b) ∧ (b ≤* c) → b ⇒ l :=
begin
rintro ⟨ha, hb⟩,
intros ε hε,
cases (h₀ ε hε) with N₀ hN₀,
cases (h₁ ε hε) with N₁ hN₁,
let N := max N₀ N₁,
have hN : N₀ ≤ N ∧ N₁ ≤ N := by {finish},
use N,
intros n hn,
cases lt_or_ge (b n) l with hlt hge,
{rw [abs_sub, abs_of_pos (sub_pos.mpr hlt)],
apply lt_of_le_of_lt _ (hN₀ n (le_trans hN.left hn)),
apply le_trans ((sub_le_sub_iff_left l).mpr (ha n)) _,
rw abs_sub,
from le_abs_self (l - a n)
},
{rw abs_of_nonneg (sub_nonneg.mpr hge),
apply lt_of_le_of_lt _ (hN₁ n (le_trans hN.right hn)),
apply le_trans (add_le_add_right' (hb n)) _,
from le_abs_self (c n - l)
}
end
-- Cauchy Sequences
def cauchy (a : ℕ → ℝ) := ∀ ε > 0, ∃ N : ℕ, ∀ n m : ℕ, N ≤ n ∧ N ≤ m → abs (a n - a m) < ε
-- Convergent implies Cauchy
lemma conv_to_cauchy (a : ℕ → ℝ) (h : is_convergent a) : cauchy a :=
begin
cases h with l hl,
intros ε hε,
cases hl (ε / 2) (half_pos hε) with N hN,
use N, intros n m hnm,
suffices : abs (a n - l) + abs (a m - l) < ε,
{rw abs_sub (a m) l at this,
have h : abs (a n - l + (l - a m)) < ε :=
lt_of_le_of_lt (abs_add_le_abs_add_abs (a n - l) (l - a m)) this,
rwa sub_add_sub_cancel (a n) l (a m) at h
},
have h : abs (a n - l) + abs (a m - l) < ε / 2 + ε / 2 :=
add_lt_add (hN n hnm.left) (hN m hnm.right),
linarith
end
-- We will prove that Cauchy implies bounded after subsequences!
-- Subsequences
def is_subseq (a b : ℕ → ℝ) := ∃ n : ℕ → ℕ, (strict_mono n ∧ ∀ i : ℕ, b i = a (n i))
-- b n = 1 is a subsequence of a n = (-1)^ n
example (a b : ℕ → ℝ) (h₁ : a = λ i, (- 1)^ i) (h₂ : b = λ i, 1) : is_subseq a b :=
begin
let n := λ i, 2 * i,
unfold is_subseq,
use n, split,
{intros a b, finish},
{intro i,
have : n = λ (i : ℕ), 2 * i, refl,
rwa [h₁, h₂, this], simp,
rw pow_mul,
finish
}
end
-- Every sequence has atleast one subsequence
theorem has_subseq (a : ℕ → ℝ) : ∃ b : ℕ → ℝ, is_subseq a b :=
begin
use a,
unfold is_subseq,
let n : ℕ → ℕ := λ i, i,
have : n = λ i, i := rfl,
use n, split,
{intros a b hab,
rw this, simpa
},
{intro i,
rwa this,
}
end
-- n(i) ≥ i ∀ i ∈ ℕ
lemma subseq_ge_id {n : ℕ → ℕ} (h : strict_mono n) : ∀ i : ℕ, i ≤ n i :=
begin
intro i,
induction i with i hi,
{from zero_le (n 0)},
{have : (n i) + 1 ≤ n (nat.succ i) :=
by {rw nat.succ_le_iff,
from h (lt_add_one i)
},
from le_trans (nat.pred_le_iff.mp hi) this
}
end
-- Bolzano-Weierstrass : Every bounded sequence has a convergent subsequence
theorem bolzano_weierstrass {a : ℕ → ℝ} (h₁ : seq_bounded a) : ∃ b : ℕ → ℝ, is_subseq a b ∧ is_convergent b :=
begin
sorry
end
-- a → l iff. all subsequences of a also converges to l
theorem conv_subseq {a : ℕ → ℝ} {l : ℝ} : a ⇒ l ↔ (∀ b : ℕ → ℝ, is_subseq a b → b ⇒ l) :=
begin
split,
{rintros h b ⟨n, ⟨hn₁, hn₂⟩⟩ ε hε,
cases (h ε hε) with N hN,
use N, intros i hi,
rw hn₂ i,
have : n i ≥ N := ge_trans (subseq_ge_id hn₁ i) hi,
from hN (n i) this
},
{intro h,
let n : ℕ → ℕ := λ i, i,
let b : ℕ → ℝ := a,
have : is_subseq a b :=
by {use n, split,
have : n = λ i, i := rfl,
{intros a b hab,
rw this, simpa},
{simp},
},
have ha : a = b := rfl,
rw ha, from h b this
}
end
-- Cauchy implies bounded
lemma cauchy_bounded_abv (b : ℕ → ℝ) : cauchy b → seq_bounded_above b :=
begin
intro hb,
cases (hb 1 _) with N hN,
swap, linarith,
let U := finset.image b (finset.range (N + 1)) ∪ {b N + 1},
have : b 0 ∈ U := by simp,
cases finset.max_of_mem this with R hR,
use R, intro m,
cases le_or_lt m N,
{have : b m ∈ U :=
by{simp, left, use m, from ⟨(nat_le_imp_lt_succ N m).mp h, rfl⟩},
from finset.le_max_of_mem this hR
},
{have : b N + 1 ∈ U := by {simp},
replace this : b N + 1 ≤ R :=
by {from finset.le_max_of_mem this hR},
apply le_trans _ this,
replace this : abs (b m - b N) < 1 := hN m N ⟨le_of_lt h, le_refl N⟩,
rw abs_lt at this,
from le_of_lt (sub_lt_iff_lt_add'.mp this.right)
}
end
lemma cauchy_bounded_blw (b : ℕ → ℝ) : cauchy b → seq_bounded_below b :=
begin
intro hb,
cases (hb 1 _) with N hN,
swap, linarith,
let U := finset.image b (finset.range (N + 1)) ∪ {b N + -1},
have : b 0 ∈ U := by simp,
cases finset.min_of_mem this with R hR,
use R, intro m,
cases le_or_lt m N,
{have : b m ∈ U :=
by{simp, left, use m, from ⟨(nat_le_imp_lt_succ N m).mp h, rfl⟩},
from finset.min_le_of_mem this hR
},
{have : b N + -1 ∈ U := by {simp},
replace this : R ≤ b N + -1 :=
by {from finset.min_le_of_mem this hR},
apply le_trans this,
replace this : abs (b m - b N) < 1 := hN m N ⟨le_of_lt h, le_refl N⟩,
rw abs_lt at this,
from le_of_lt (lt_sub_iff_add_lt'.mp this.left)
}
end
lemma cauchy_bounded (a : ℕ → ℝ) : cauchy a → seq_bounded a := λ h, ⟨cauchy_bounded_abv a h, cauchy_bounded_blw a h⟩
-- Cauchy implies convergent
lemma cauchy_to_conv (a : ℕ → ℝ) (h : cauchy a) : is_convergent a :=
begin
rcases bolzano_weierstrass (cauchy_bounded a h) with ⟨b, ⟨⟨n, ⟨hb₁, hb₂⟩⟩, ⟨l, hl⟩⟩⟩,
use l, intros ε hε,
cases h (ε / 2) (half_pos hε) with N₁ hN₁,
cases hl (ε / 2) (half_pos hε) with N₂ hN₂,
let N := n (max N₁ N₂),
use N, intros i hi,
suffices : abs (a i - a N) + abs (a N - l) < ε,
apply lt_of_le_of_lt _ this,
have hβ: a i - a N + (a N - l) = a i - l := by {linarith},
rw ←hβ,
from abs_add (a i - a N) (a N - l),
have hα : abs (a i - a N) + abs (a N - l) < ε / 2 + ε / 2 :=
by {have : N = n (max N₁ N₂) := rfl,
apply add_lt_add,
{have hβ : N₁ ≤ N :=
by {rw this, from le_trans (le_max_left N₁ N₂) (subseq_ge_id hb₁ (max N₁ N₂))},
have hγ : N₁ ≤ i := by {from le_trans hβ hi},
from hN₁ i N ⟨hγ, hβ⟩
},
{have hβ : N₂ ≤ N :=
by {rw this, from le_trans (le_max_right N₁ N₂) (subseq_ge_id hb₁ (max N₁ N₂))},
apply lt_of_le_of_lt _ (hN₂ (max N₁ N₂) (le_max_right N₁ N₂)),
rwa hb₂ (max N₁ N₂)
}
},
linarith
end
-- Cauchy iff. convergent
theorem cauchy_iff_conv {a : ℕ → ℝ} : cauchy a ↔ is_convergent a :=
begin
split,
{intro h, from cauchy_to_conv a h},
{intro h, from conv_to_cauchy a h}
end
end sequences |
330b1ff151811596da399ac7ed12f7c499839166 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/meta/expr.lean | 27f101ba4d9fb4cc9b815e99c92212942536c618 | [
"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 | 39,183 | lean | /-
Copyright (c) 2019 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis
-/
import data.string.defs
import tactic.derive_inhabited
/-!
# Additional operations on expr and related types
This file defines basic operations on the types expr, name, declaration, level, environment.
This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`.
## Tags
expr, name, declaration, level, environment, meta, metaprogramming, tactic
-/
attribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind
@[priority 100] meta instance has_reflect.has_to_pexpr {α} [has_reflect α] : has_to_pexpr α :=
⟨λ b, pexpr.of_expr (reflect b)⟩
namespace binder_info
/-! ### Declarations about `binder_info` -/
instance : inhabited binder_info := ⟨ binder_info.default ⟩
/-- The brackets corresponding to a given binder_info. -/
def brackets : binder_info → string × string
| binder_info.implicit := ("{", "}")
| binder_info.strict_implicit := ("{{", "}}")
| binder_info.inst_implicit := ("[", "]")
| _ := ("(", ")")
end binder_info
namespace name
/-! ### Declarations about `name` -/
/-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix
with the value of `f n`. -/
def map_prefix (f : name → option name) : name → name
| anonymous := anonymous
| (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n')
| (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n')
/-- If `nm` is a simple name (having only one string component) starting with `_`, then
`deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/
meta def deinternalize_field : name → name
| (mk_string s name.anonymous) :=
let i := s.mk_iterator in
if i.curr = '_' then i.next.next_to_string else s
| n := n
/-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/
meta def get_nth_prefix : name → ℕ → name
| nm 0 := nm
| nm (n + 1) := get_nth_prefix nm.get_prefix n
/-- Auxilliary definition for `pop_nth_prefix` -/
private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ
| anonymous n := (anonymous, 1)
| nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in
if height ≤ n then (anonymous, height + 1)
else (nm.update_prefix pfx, height + 1)
/-- Pops the top `n` prefixes from the given name. -/
meta def pop_nth_prefix (nm : name) (n : ℕ) : name :=
prod.fst $ pop_nth_prefix_aux nm n
/-- Pop the prefix of a name -/
meta def pop_prefix (n : name) : name :=
pop_nth_prefix n 1
/-- Auxilliary definition for `from_components` -/
private def from_components_aux : name → list string → name
| n [] := n
| n (s :: rest) := from_components_aux (name.mk_string s n) rest
/-- Build a name from components. For example `from_components ["foo","bar"]` becomes
``` `foo.bar``` -/
def from_components : list string → name :=
from_components_aux name.anonymous
/-- `name`s can contain numeral pieces, which are not legal names
when typed/passed directly to the parser. We turn an arbitrary
name into a legal identifier name by turning the numbers to strings. -/
meta def sanitize_name : name → name
| name.anonymous := name.anonymous
| (name.mk_string s p) := name.mk_string s $ sanitize_name p
| (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p
/-- Append a string to the last component of a name -/
def append_suffix : name → string → name
| (mk_string s n) s' := mk_string (s ++ s') n
| n _ := n
/-- The first component of a name, turning a number to a string -/
meta def head : name → string
| (mk_string s anonymous) := s
| (mk_string s p) := head p
| (mk_numeral n p) := head p
| anonymous := "[anonymous]"
/-- Tests whether the first component of a name is `"_private"` -/
meta def is_private (n : name) : bool :=
n.head = "_private"
/-- Get the last component of a name, and convert it to a string. -/
meta def last : name → string
| (mk_string s _) := s
| (mk_numeral n _) := repr n
| anonymous := "[anonymous]"
/-- Returns the number of characters used to print all the string components of a name,
including periods between name segments. Ignores numerical parts of a name. -/
meta def length : name → ℕ
| (mk_string s anonymous) := s.length
| (mk_string s p) := s.length + 1 + p.length
| (mk_numeral n p) := p.length
| anonymous := "[anonymous]".length
/-- Checks whether `nm` has a prefix (including itself) such that P is true -/
def has_prefix (P : name → bool) : name → bool
| anonymous := ff
| (mk_string s nm) := P (mk_string s nm) ∨ has_prefix nm
| (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm
/-- Appends `'` to the end of a name. -/
meta def add_prime : name → name
| (name.mk_string s p) := name.mk_string (s ++ "'") p
| n := (name.mk_string "x'" n)
/-- `last_string n` returns the rightmost component of `n`, ignoring numeral components.
For example, ``last_string `a.b.c.33`` will return `` `c ``. -/
def last_string : name → string
| anonymous := "[anonymous]"
| (mk_string s _) := s
| (mk_numeral _ n) := last_string n
/--
Constructs a (non-simple) name from a string.
Example: ``name.from_string "foo.bar" = `foo.bar``
-/
meta def from_string (s : string) : name :=
from_components $ s.split (= '.')
/--
In surface Lean, we can write anonymous Π binders (i.e. binders where the
argument is not named) using the function arrow notation:
```lean
inductive test : Type :=
| intro : unit → test
```
After elaboration, however, every binder must have a name, so Lean generates
one. In the example, the binder in the type of `intro` is anonymous, so Lean
gives it the name `a`:
```lean
test.intro : ∀ (a : unit), test
```
When there are multiple anonymous binders, they are named `a_1`, `a_2` etc.
Thus, when we want to know whether the user named a binder, we can check whether
the name follows this scheme. Note, however, that this is not reliable. When the
user writes (for whatever reason)
```lean
inductive test : Type :=
| intro : ∀ (a : unit), test
```
we cannot tell that the binder was, in fact, named.
The function `name.is_likely_generated_binder_name` checks if
a name is of the form `a`, `a_1`, etc.
-/
library_note "likely generated binder names"
/--
Check whether a simple name was likely generated by Lean to name an anonymous
binder. Such names are either `a` or `a_n` for some natural `n`. See
note [likely generated binder names].
-/
meta def is_likely_generated_binder_simple_name : string → bool
| "a" := tt
| n :=
match n.get_rest "a_" with
| none := ff
| some suffix := suffix.is_nat
end
/--
Check whether a name was likely generated by Lean to name an anonymous binder.
Such names are either `a` or `a_n` for some natural `n`. See
note [likely generated binder names].
-/
meta def is_likely_generated_binder_name (n : name) : bool :=
match n with
| mk_string s anonymous := is_likely_generated_binder_simple_name s
| _ := ff
end
end name
namespace level
/-! ### Declarations about `level` -/
/-- Tests whether a universe level is non-zero for all assignments of its variables -/
meta def nonzero : level → bool
| (succ _) := tt
| (max l₁ l₂) := l₁.nonzero || l₂.nonzero
| (imax _ l₂) := l₂.nonzero
| _ := ff
/--
`l.fold_mvar f` folds a function `f : name → α → α`
over each `n : name` appearing in a `level.mvar n` in `l`.
-/
meta def fold_mvar {α} : level → (name → α → α) → α → α
| zero f := id
| (succ a) f := fold_mvar a f
| (param a) f := id
| (mvar a) f := f a
| (max a b) f := fold_mvar a f ∘ fold_mvar b f
| (imax a b) f := fold_mvar a f ∘ fold_mvar b f
end level
/-! ### Declarations about `binder` -/
/-- The type of binders containing a name, the binding info and the binding type -/
@[derive decidable_eq, derive inhabited]
meta structure binder :=
(name : name)
(info : binder_info)
(type : expr)
namespace binder
/-- Turn a binder into a string. Uses expr.to_string for the type. -/
protected meta def to_string (b : binder) : string :=
let (l, r) := b.info.brackets in
l ++ b.name.to_string ++ " : " ++ b.type.to_string ++ r
open tactic
meta instance : has_to_string binder := ⟨ binder.to_string ⟩
meta instance : has_to_format binder := ⟨ λ b, b.to_string ⟩
meta instance : has_to_tactic_format binder :=
⟨ λ b, let (l, r) := b.info.brackets in
(λ e, l ++ b.name.to_string ++ " : " ++ e ++ r) <$> pp b.type ⟩
end binder
/-!
### Converting between expressions and numerals
There are a number of ways to convert between expressions and numerals, depending on the input and
output types and whether you want to infer the necessary type classes.
See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`.
-/
/--
`nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +.
`type`: an expression representing the target type. This must live in Type 0.
`has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc.
-/
meta def nat.mk_numeral (type has_zero has_one has_add : expr) : ℕ → expr :=
let z : expr := `(@has_zero.zero.{0} %%type %%has_zero),
o : expr := `(@has_one.one.{0} %%type %%has_one) in
nat.binary_rec z
(λ b n e, if n = 0 then o else
if b then `(@bit1.{0} %%type %%has_one %%has_add %%e)
else `(@bit0.{0} %%type %%has_add %%e))
/--
`int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -.
`type`: an expression representing the target type. This must live in Type 0.
`has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc.
-/
meta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : ℤ → expr
| (int.of_nat n) := n.mk_numeral type has_zero has_one has_add
| -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in
`(@has_neg.neg.{0} %%type %%has_neg %%ne)
/--
`nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`.
The `pexpr` does not hold any typing information:
`to_expr ``((%%(nat.to_pexpr 5) : ℤ))` will create a native integer numeral `(5 : ℤ)`.
-/
meta def nat.to_pexpr : ℕ → pexpr
| 0 := ``(0)
| 1 := ``(1)
| n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2)))
namespace expr
/--
Turns an expression into a natural number, assuming it is only built up from
`has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`.
-/
protected meta def to_nat : expr → option ℕ
| `(has_zero.zero) := some 0
| `(has_one.one) := some 1
| `(bit0 %%e) := bit0 <$> e.to_nat
| `(bit1 %%e) := bit1 <$> e.to_nat
| `(nat.succ %%e) := (+1) <$> e.to_nat
| `(nat.zero) := some 0
| _ := none
/--
Turns an expression into a integer, assuming it is only built up from
`has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head.
-/
protected meta def to_int : expr → option ℤ
| `(has_neg.neg %%e) := do n ← e.to_nat, some (-n)
| e := coe <$> e.to_nat
/--
`is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure,
ignoring differences in type and type class arguments.
-/
meta def is_num_eq : expr → expr → bool
| `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt
| `(@has_one.one _ _) `(@has_one.one _ _) := tt
| `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b
| `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b
| `(-%%a) `(-%%b) := a.is_num_eq b
| `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b
| _ _ := ff
end expr
/-! ### Declarations about `expr` -/
namespace expr
open tactic
/-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/
meta def clean_ids : list name :=
[``id, ``id_rhs, ``id_delta, ``hidden]
/-- Clean an expression by removing `id`s listed in `clean_ids`. -/
meta def clean (e : expr) : expr :=
e.replace (λ e n,
match e with
| (app (app (const n _) _) e') :=
if n ∈ clean_ids then some e' else none
| (app (lam _ _ _ (var 0)) e') := some e'
| _ := none
end)
/-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/
meta def replace_with (e : expr) (s : expr) (s' : expr) : expr :=
e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none
/-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/
protected meta def apply_replacement_fun (f : name → name) (e : expr) : expr :=
e.replace $ λ e d,
match e with
| expr.const n ls := some $ expr.const (f n) ls
| _ := none
end
/-- Match a variable. -/
meta def match_var {elab} : expr elab → option ℕ
| (var n) := some n
| _ := none
/-- Match a sort. -/
meta def match_sort {elab} : expr elab → option level
| (sort u) := some u
| _ := none
/-- Match a constant. -/
meta def match_const {elab} : expr elab → option (name × list level)
| (const n lvls) := some (n, lvls)
| _ := none
/-- Match a metavariable. -/
meta def match_mvar {elab} : expr elab →
option (name × name × expr elab)
| (mvar unique pretty type) := some (unique, pretty, type)
| _ := none
/-- Match a local constant. -/
meta def match_local_const {elab} : expr elab →
option (name × name × binder_info × expr elab)
| (local_const unique pretty bi type) := some (unique, pretty, bi, type)
| _ := none
/-- Match an application. -/
meta def match_app {elab} : expr elab → option (expr elab × expr elab)
| (app t u) := some (t, u)
| _ := none
/-- Match an abstraction. -/
meta def match_lam {elab} : expr elab →
option (name × binder_info × expr elab × expr elab)
| (lam var_name bi type body) := some (var_name, bi, type, body)
| _ := none
/-- Match a Π type. -/
meta def match_pi {elab} : expr elab →
option (name × binder_info × expr elab × expr elab)
| (pi var_name bi type body) := some (var_name, bi, type, body)
| _ := none
/-- Match a let. -/
meta def match_elet {elab} : expr elab →
option (name × expr elab × expr elab × expr elab)
| (elet var_name type assignment body) := some (var_name, type, assignment, body)
| _ := none
/-- Match a macro. -/
meta def match_macro {elab} : expr elab →
option (macro_def × list (expr elab))
| (macro df args) := some (df, args)
| _ := none
/-- Tests whether an expression is a meta-variable. -/
meta def is_mvar : expr → bool
| (mvar _ _ _) := tt
| _ := ff
/-- Tests whether an expression is a sort. -/
meta def is_sort : expr → bool
| (sort _) := tt
| e := ff
/-- Get the universe levels of a `const` expression -/
meta def univ_levels : expr → list level
| (const n ls) := ls
| _ := []
/--
Replace any metavariables in the expression with underscores, in preparation for printing
`refine ...` statements.
-/
meta def replace_mvars (e : expr) : expr :=
e.replace (λ e' _, if e'.is_mvar then some (unchecked_cast pexpr.mk_placeholder) else none)
/-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to
`implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/
meta def to_implicit_local_const : expr → expr
| (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t
| e := e
/-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder
info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/
meta def to_implicit_binder : expr → expr
| (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d
| (lam n _ d b) := lam n binder_info.implicit d b
| (pi n _ d b) := pi n binder_info.implicit d b
| e := e
/-- Returns a list of all local constants in an expression (without duplicates). -/
meta def list_local_consts (e : expr) : list expr :=
e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es)
/-- Returns a name_set of all constants in an expression. -/
meta def list_constant (e : expr) : name_set :=
e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es)
/-- Returns a list of all meta-variables in an expression (without duplicates). -/
meta def list_meta_vars (e : expr) : list expr :=
e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es)
/-- Returns a list of all universe meta-variables in an expression (without duplicates). -/
meta def list_univ_meta_vars (e : expr) : list name :=
native.rb_set.to_list $ e.fold native.mk_rb_set $ λ e' i s,
match e' with
| (sort u) := u.fold_mvar (flip native.rb_set.insert) s
| (const _ ls) := ls.foldl (λ s' l, l.fold_mvar (flip native.rb_set.insert) s') s
| _ := s
end
/--
Test `t` contains the specified subexpression `e`, or a metavariable.
This represents the notion that `e` "may occur" in `t`,
possibly after subsequent unification.
-/
meta def contains_expr_or_mvar (t : expr) (e : expr) : bool :=
-- We can't use `t.has_meta_var` here, as that detects universe metavariables, too.
¬ t.list_meta_vars.empty ∨ e.occurs t
/-- Returns a name_set of all constants in an expression starting with a certain prefix. -/
meta def list_names_with_prefix (pre : name) (e : expr) : name_set :=
e.fold mk_name_set $ λ e' _ l,
match e' with
| expr.const n _ := if n.get_prefix = pre then l.insert n else l
| _ := l
end
/-- Returns true if `e` contains a name `n` where `p n` is true.
Returns `true` if `p name.anonymous` is true. -/
meta def contains_constant (e : expr) (p : name → Prop) [decidable_pred p] : bool :=
e.fold ff (λ e' _ b, if p (e'.const_name) then tt else b)
/--
Returns true if `e` contains a `sorry`.
-/
meta def contains_sorry (e : expr) : bool :=
e.fold ff (λ e' _ b, if (is_sorry e').is_some then tt else b)
/--
`app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`.
-/
meta def app_symbol_in (e : expr) (l : list name) : bool :=
match e.get_app_fn with
| (expr.const n _) := n ∈ l
| _ := ff
end
/-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/
meta def get_simp_args (e : expr) : tactic (list expr) :=
-- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app
if ¬ e.is_app then pure [] else do
cgr ← mk_specialized_congr_lemma_simp e,
pure $ do
(arg_kind, arg) ← cgr.arg_kinds.zip e.get_app_args,
guard $ arg_kind = congr_arg_kind.eq,
pure arg
/-- Simplifies the expression `t` with the specified options.
The result is `(new_e, pr)` with the new expression `new_e` and a proof
`pr : e = new_e`. -/
meta def simp (t : expr)
(cfg : simp_config := {}) (discharger : tactic unit := failed)
(no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) :
tactic (expr × expr) :=
do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs,
simplify s to_unfold t cfg `eq discharger
/-- Definitionally simplifies the expression `t` with the specified options.
The result is the simplified expression. -/
meta def dsimp (t : expr)
(cfg : dsimp_config := {})
(no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) :
tactic expr :=
do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs,
s.dsimplify to_unfold t cfg
/-- Get the names of the bound variables by a sequence of pis or lambdas. -/
meta def binding_names : expr → list name
| (pi n _ _ e) := n :: e.binding_names
| (lam n _ _ e) := n :: e.binding_names
| e := []
/-- head-reduce a single let expression -/
meta def reduce_let : expr → expr
| (elet _ _ v b) := b.instantiate_var v
| e := e
/-- head-reduce all let expressions -/
meta def reduce_lets : expr → expr
| (elet _ _ v b) := reduce_lets $ b.instantiate_var v
| e := e
/-- Instantiate lambdas in the second argument by expressions from the first. -/
meta def instantiate_lambdas : list expr → expr → expr
| (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e')
| _ e := e
/-- Repeatedly apply `expr.subst`. -/
meta def substs : expr → list expr → expr | e es := es.foldl expr.subst e
/-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`.
If the length of `es` is larger than the number of lambdas in `e`,
then the term is applied to the remaining terms.
Also reduces head let-expressions in `e`, including those after instantiating all lambdas.
This is very similar to `expr.substs`, but this also reduces head let-expressions. -/
meta def instantiate_lambdas_or_apps : list expr → expr → expr
| (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v
| es (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v
| es e := mk_app e es
/--
Some declarations work with open expressions, i.e. an expr that has free variables.
Terms will free variables are not well-typed, and one should not use them in tactics like
`infer_type` or `unify`. You can still do syntactic analysis/manipulation on them.
The reason for working with open types is for performance: instantiating variables requires
iterating through the expression. In one performance test `pi_binders` was more than 6x
quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x).
-/
library_note "open expressions"
/-- Get the codomain/target of a pi-type.
This definition doesn't instantiate bound variables, and therefore produces a term that is open.
See note [open expressions]. -/
meta def pi_codomain : expr → expr
| (pi n bi d b) := pi_codomain b
| e := e
/-- Get the body/value of a lambda-expression.
This definition doesn't instantiate bound variables, and therefore produces a term that is open.
See note [open expressions]. -/
meta def lambda_body : expr → expr
| (lam n bi d b) := lambda_body b
| e := e
/-- Auxilliary defintion for `pi_binders`.
See note [open expressions]. -/
meta def pi_binders_aux : list binder → expr → list binder × expr
| es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b
| es e := (es, e)
/-- Get the binders and codomain of a pi-type.
This definition doesn't instantiate bound variables, and therefore produces a term that is open.
The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the
free variables.
See note [open expressions]. -/
meta def pi_binders (e : expr) : list binder × expr :=
let (es, e) := pi_binders_aux [] e in (es.reverse, e)
/-- Auxilliary defintion for `get_app_fn_args`. -/
meta def get_app_fn_args_aux : list expr → expr → expr × list expr
| r (app f a) := get_app_fn_args_aux (a::r) f
| r e := (e, r)
/-- A combination of `get_app_fn` and `get_app_args`: lists both the
function and its arguments of an application -/
meta def get_app_fn_args : expr → expr × list expr :=
get_app_fn_args_aux []
/-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/
meta def drop_pis : list expr → expr → tactic expr
| (list.cons v vs) (pi n bi d b) := do
t ← infer_type v,
guard (t =ₐ d),
drop_pis vs (b.instantiate_var v)
| [] e := return e
| _ _ := failed
/-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`.
Returns `empty` if the list is empty. -/
meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr
| [] := empty
| [e] := e
| (e :: es) := op e $ mk_op_lst es
/-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/
meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true)
/-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/
meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false)
/-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant.
Otherwise returns `binder_info.default`. -/
meta def local_binding_info : expr → binder_info
| (expr.local_const _ _ bi _) := bi
| _ := binder_info.default
/-- `is_default_local e` tests whether `e` is a local constant with binder info
`binder_info.default` -/
meta def is_default_local : expr → bool
| (expr.local_const _ _ binder_info.default _) := tt
| _ := ff
/-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/
meta def has_local_constant (e l : expr) : bool :=
e.has_local_in $ mk_name_set.insert l.local_uniq_name
/-- Turns a local constant into a binder -/
meta def to_binder : expr → binder
| (local_const _ nm bi t) := ⟨nm, bi, t⟩
| _ := default binder
/-- Strip-away the context-dependent unique id for the given local const and return: its friendly
`name`, its `binder_info`, and its `type : expr`. -/
meta def get_local_const_kind : expr → name × binder_info × expr
| (expr.local_const _ n bi e) := (n, bi, e)
| _ := (name.anonymous, binder_info.default, expr.const name.anonymous [])
/-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/
meta def local_const_set_type {elab : bool} : expr elab → expr elab → expr elab
| (expr.local_const x n bi t) new_t := expr.local_const x n bi new_t
| e new_t := e
/-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to
access core `expr` manipulation functions for `pexpr`-based use, but which are restricted to
`expr tt` at the site of definition unnecessarily.
DANGER: Unless you know exactly what you are doing, this is probably not the function you are
looking for. For `pexpr → expr` see `tactic.to_expr`. For `expr → pexpr` see `to_pexpr`. -/
meta def unsafe_cast {elab₁ elab₂ : bool} : expr elab₁ → expr elab₂ := unchecked_cast
/-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr × expr)` as
a collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says "whenever
`f` is encountered in `e` verbatim, replace it with `t`". -/
meta def replace_subexprs {elab : bool} (e : expr elab) (mappings : list (expr × expr)) : expr elab :=
unsafe_cast $ e.unsafe_cast.replace $ λ e n,
(mappings.filter $ λ ent : expr × expr, ent.1 = e).head'.map prod.snd
/-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of
other `expr.local_const`s. It determines whether `e` should be considered "available in context"
as a variable by virtue of the fact that the variables `vs` have been deemed such.
For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that
the typeclass instance `prime n` should be included, but `ih : even n` should not.
DANGER: It is possible that for `f : expr` another `expr.local_const`, we have
`is_implicitly_included_variable f vs = ff` but
`is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to
iteratively add a list of local constants (usually, the `variables` declared in the local scope)
which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables
were added in a particular iteration. The function `all_implicitly_included_variables` below
implements this behaviour.
Note that if `e ∈ vs` then `is_implicitly_included_variable e vs = tt`. -/
meta def is_implicitly_included_variable (e : expr) (vs : list expr) : bool :=
if ¬(e.local_pp_name.to_string.starts_with "_") then
e ∈ vs
else e.local_type.fold tt $ λ se _ b,
if ¬b then ff
else if ¬se.is_local_constant then tt
else se ∈ vs
/-- Private work function for `all_implicitly_included_variables`, performing the actual series of
iterations, tracking with a boolean whether any updates occured this iteration. -/
private meta def all_implicitly_included_variables_aux
: list expr → list expr → list expr → bool → list expr
| [] vs rs tt := all_implicitly_included_variables_aux rs vs [] ff
| [] vs rs ff := vs
| (e :: rest) vs rs b :=
let (vs, rs, b) := if e.is_implicitly_included_variable vs then (e :: vs, rs, tt) else (vs, e :: rs, b) in
all_implicitly_included_variables_aux rest vs rs b
/-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`,
another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion
of the variables in `vs` into the local context implies that `e` should also be included. See
`is_implicitly_included_variable e vs` for the details.
In particular, those elements of `vs` are included automatically. -/
meta def all_implicitly_included_variables (es vs : list expr) : list expr :=
all_implicitly_included_variables_aux es vs [] ff
end expr
/-! ### Declarations about `environment` -/
namespace environment
/-- Tests whether `n` is a structure. -/
meta def is_structure (env : environment) (n : name) : bool :=
(env.structure_fields n).is_some
/-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a
structure. -/
meta def structure_fields_full (env : environment) (n : name) : option (list name) :=
(env.structure_fields n).map (list.map $ λ n', n ++ n')
/-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type.
Note that `is_ginductive` returns `tt` even on regular inductive types.
This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive
type. -/
meta def is_ginductive' (e : environment) (nm : name) : bool :=
e.is_ginductive nm ∧ ¬ e.is_inductive nm
/-- For all declarations `d` where `f d = some x` this adds `x` to the returned list. -/
meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α :=
e.fold [] $ λ d l, match f d with
| some r := r :: l
| none := l
end
/-- Maps `f` to all declarations in the environment. -/
meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α :=
e.decl_filter_map $ λ d, some (f d)
/-- Lists all declarations in the environment -/
meta def get_decls (e : environment) : list declaration :=
e.decl_map id
/-- Lists all trusted (non-meta) declarations in the environment -/
meta def get_trusted_decls (e : environment) : list declaration :=
e.decl_filter_map (λ d, if d.is_trusted then some d else none)
/-- Lists the name of all declarations in the environment -/
meta def get_decl_names (e : environment) : list name :=
e.decl_map declaration.to_name
/-- Fold a monad over all declarations in the environment. -/
meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α)
(fn : declaration → α → m α) : m α :=
e.fold (return x) (λ d t, t >>= fn d)
/-- Filters all declarations in the environment. -/
meta def filter (e : environment) (test : declaration → bool) : list declaration :=
e.fold [] $ λ d ds, if test d then d::ds else ds
/-- Filters all declarations in the environment. -/
meta def mfilter (e : environment) (test : declaration → tactic bool) : tactic (list declaration) :=
e.mfold [] $ λ d ds, do b ← test d, return $ if b then d::ds else ds
/-- Checks whether `s` is a prefix of the file where `n` is declared.
This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/
meta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool :=
s.is_prefix_of $ (e.decl_olean n).get_or_else ""
end environment
/-!
### `is_eta_expansion`
In this section we define the tactic `is_eta_expansion` which checks whether an expression
is an eta-expansion of a structure. (not to be confused with eta-expanion for `λ`).
-/
namespace expr
open tactic
/-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have
`pr = nm.{univs} args`.
Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we
want to eta-reduce. -/
meta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name × expr)) :
bool :=
l.all $ λ⟨proj, val⟩, val = (const proj univs).mk_app args
/-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all
elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`.
Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we
want to eta-reduce. -/
meta def is_eta_expansion_test : list (name × expr) → option expr
| [] := none
| (⟨proj, val⟩::l) :=
match val.get_app_fn with
| (const nm univs : expr) :=
if nm = proj then
let args := val.get_app_args in
let e := args.ilast in
if is_eta_expansion_of args univs l then some e else none
else
none
| _ := none
end
/-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`.
Here `l` is intended to consists of the projections and the fields of `val`.
This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and
afterward checks whether the resulting expression `e` unifies with `val`.
This last check is necessary, because `val` and `e` might have different types. -/
meta def is_eta_expansion_aux (val : expr) (l : list (name × expr)) : tactic (option expr) :=
do l' ← l.mfilter (λ⟨proj, val⟩, bnot <$> is_proof val),
match is_eta_expansion_test l' with
| some e := option.map (λ _, e) <$> try_core (unify e val)
| none := return none
end
/-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the
eta-expansion of `e`.
With eta-expansion we here mean the eta-expansion of a structure, not of a function.
For example, the eta-expansion of `x : α × β` is `⟨x.1, x.2⟩`.
This assumes that `val` is a fully-applied application of the constructor of a structure.
This is useful to reduce expressions generated by the notation
`{ field_1 := _, ..other_structure }`
If `other_structure` is itself a field of the structure, then the elaborator will insert an
eta-expanded version of `other_structure`. -/
meta def is_eta_expansion (val : expr) : tactic (option expr) := do
e ← get_env,
type ← infer_type val,
projs ← e.structure_fields_full type.get_app_fn.const_name,
let args := (val.get_app_args).drop type.get_app_args.length,
is_eta_expansion_aux val (projs.zip args)
end expr
/-! ### Declarations about `declaration` -/
namespace declaration
open tactic
/--
`declaration.update_with_fun f tgt decl`
sets the name of the given `decl : declaration` to `tgt`, and applies `f` to the names
of all `expr.const`s which appear in the value or type of `decl`.
-/
protected meta def update_with_fun (f : name → name) (tgt : name) (decl : declaration) :
declaration :=
let decl := decl.update_name $ tgt in
let decl := decl.update_type $ decl.type.apply_replacement_fun f in
decl.update_value $ decl.value.apply_replacement_fun f
/-- Checks whether the declaration is declared in the current file.
This is a simple wrapper around `environment.in_current_file`
Use `environment.in_current_file` instead if performance matters. -/
meta def in_current_file (d : declaration) : tactic bool :=
do e ← get_env, return $ e.in_current_file d.to_name
/-- Checks whether a declaration is a theorem -/
meta def is_theorem : declaration → bool
| (thm _ _ _ _) := tt
| _ := ff
/-- Checks whether a declaration is a constant -/
meta def is_constant : declaration → bool
| (cnst _ _ _ _) := tt
| _ := ff
/-- Checks whether a declaration is a axiom -/
meta def is_axiom : declaration → bool
| (ax _ _ _) := tt
| _ := ff
/-- Checks whether a declaration is automatically generated in the environment.
There is no cheap way to check whether a declaration in the namespace of a generalized
inductive type is automatically generated, so for now we say that all of them are automatically
generated. -/
meta def is_auto_generated (e : environment) (d : declaration) : bool :=
e.is_constructor d.to_name ∨
(e.is_projection d.to_name).is_some ∨
(e.is_constructor d.to_name.get_prefix ∧
d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨
(e.is_inductive d.to_name.get_prefix ∧
d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec",
"rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨
d.to_name.has_prefix (λ nm, e.is_ginductive' nm)
/--
Returns true iff `d` is an automatically-generated or internal declaration.
-/
meta def is_auto_or_internal (env : environment) (d : declaration) : bool :=
d.to_name.is_internal || d.is_auto_generated env
/-- Returns the list of universe levels of a declaration. -/
meta def univ_levels (d : declaration) : list level :=
d.univ_params.map level.param
/-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/
protected meta def reducibility_hints : declaration → reducibility_hints
| (declaration.defn _ _ _ _ red _) := red
| _ := _root_.reducibility_hints.opaque
/-- formats the arguments of a `declaration.thm` -/
private meta def print_thm (nm : name) (tp : expr) (body : task expr) : tactic format :=
do tp ← pp tp, body ← pp body.get,
return $ "<theorem " ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">"
/-- formats the arguments of a `declaration.defn` -/
private meta def print_defn (nm : name) (tp : expr) (body : expr) (is_trusted : bool) :
tactic format :=
do tp ← pp tp, body ← pp body,
return $ "<" ++ (if is_trusted then "def " else "meta def ") ++ to_fmt nm ++ " : " ++ tp ++ " := "
++ body ++ ">"
/-- formats the arguments of a `declaration.cnst` -/
private meta def print_cnst (nm : name) (tp : expr) (is_trusted : bool) : tactic format :=
do tp ← pp tp,
return $ "<" ++ (if is_trusted then "constant " else "meta constant ") ++ to_fmt nm ++ " : "
++ tp ++ ">"
/-- formats the arguments of a `declaration.ax` -/
private meta def print_ax (nm : name) (tp : expr) : tactic format :=
do tp ← pp tp,
return $ "<axiom " ++ to_fmt nm ++ " : " ++ tp ++ ">"
/-- pretty-prints a `declaration` object. -/
meta def to_tactic_format : declaration → tactic format
| (declaration.thm nm _ tp bd) := print_thm nm tp bd
| (declaration.defn nm _ tp bd _ is_trusted) := print_defn nm tp bd is_trusted
| (declaration.cnst nm _ tp is_trusted) := print_cnst nm tp is_trusted
| (declaration.ax nm _ tp) := print_ax nm tp
meta instance : has_to_tactic_format declaration :=
⟨to_tactic_format⟩
end declaration
meta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) :=
unchecked_cast
expr.has_decidable_eq
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.