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
788d33a1a9dbc2e9d8126022261408fb66d100f7
e9dbaaae490bc072444e3021634bf73664003760
/src/Problems/2008/IMO_2008_P1.lean
25092b15d9d1e9908380f7b1146242d90a73f8a7
[ "Apache-2.0" ]
permissive
liaofei1128/geometry
566d8bfe095ce0c0113d36df90635306c60e975b
3dd128e4eec8008764bb94e18b932f9ffd66e6b3
refs/heads/master
1,678,996,510,399
1,581,454,543,000
1,583,337,839,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
494
lean
import Geo.Geo.Core namespace Geo open Triangle def IMO_2008_P1 : Prop := ∀ (A B C : Point), acute ⟨A, B, C⟩ → let H := orthocenter ⟨A, B, C⟩; ∀ (A₁ A₂ B₁ B₂ C₁ C₂ : Point), intersectAt₂ (Circle.buildOP (Seg.mk B C).midp H) (Line.mk B C) A₁ A₂ → intersectAt₂ (Circle.buildOP (Seg.mk C A).midp H) (Line.mk C A) B₁ B₂ → intersectAt₂ (Circle.buildOP (Seg.mk A B).midp H) (Line.mk A B) C₁ C₂ → cycl [A₁, A₂, B₁, B₂, C₁, C₂] end Geo
7098d508ef17b55e8c824b392c57697100cb94cf
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/bounded_variation.lean
3deb1eb619731a5f4f6ff74ff37372e095bcf40a
[ "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
34,131
lean
/- Copyright (c) 2022 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 measure_theory.measure.lebesgue import analysis.calculus.monotone /-! # Functions of bounded variation We study functions of bounded variation. In particular, we show that a bounded variation function is a difference of monotone functions, and differentiable almost everywhere. This implies that Lipschitz functions from the real line into finite-dimensional vector space are also differentiable almost everywhere. ## Main definitions and results * `evariation_on f s` is the total variation of the function `f` on the set `s`, in `ℝ≥0∞`. * `has_bounded_variation_on f s` registers that the variation of `f` on `s` is finite. * `has_locally_bounded_variation f s` registers that `f` has finite variation on any compact subinterval of `s`. * `evariation_on.Icc_add_Icc` states that the variation of `f` on `[a, c]` is the sum of its variations on `[a, b]` and `[b, c]`. * `has_locally_bounded_variation_on.exists_monotone_on_sub_monotone_on` proves that a function with locally bounded variation is the difference of two monotone functions. * `lipschitz_with.has_locally_bounded_variation_on` shows that a Lipschitz function has locally bounded variation. * `has_locally_bounded_variation_on.ae_differentiable_within_at` shows that a bounded variation function into a finite dimensional real vector space is differentiable almost everywhere. * `lipschitz_on_with.ae_differentiable_within_at` is the same result for Lipschitz functions. We also give several variations around these results. ## Implementation We define the variation as an extended nonnegative real, to allow for infinite variation. This makes it possible to use the complete linear order structure of `ℝ≥0∞`. The proofs would be much more tedious with an `ℝ`-valued or `ℝ≥0`-valued variation, since one would always need to check that the sets one uses are nonempty and bounded above as these are only conditionally complete. -/ open_locale big_operators nnreal ennreal open set measure_theory variables {α : Type*} [linear_order α] {E F : Type*} [pseudo_emetric_space E] [pseudo_emetric_space F] {V : Type*} [normed_add_comm_group V] [normed_space ℝ V] [finite_dimensional ℝ V] /-- The (extended real valued) variation of a function `f` on a set `s` inside a linear order is the supremum of the sum of `edist (f (u (i+1))) (f (u i))` over all finite increasing sequences `u` in `s`. -/ noncomputable def evariation_on (f : α → E) (s : set α) : ℝ≥0∞ := ⨆ (p : ℕ × {u : ℕ → α // monotone u ∧ ∀ i, u i ∈ s}), ∑ i in finset.range p.1, edist (f ((p.2 : ℕ → α) (i+1))) (f ((p.2 : ℕ → α) i)) /-- A function has bounded variation on a set `s` if its total variation there is finite. -/ def has_bounded_variation_on (f : α → E) (s : set α) := evariation_on f s ≠ ∞ /-- A function has locally bounded variation on a set `s` if, given any interval `[a, b]` with endpoints in `s`, then the function has finite variation on `s ∩ [a, b]`. -/ def has_locally_bounded_variation_on (f : α → E) (s : set α) := ∀ a b, a ∈ s → b ∈ s → has_bounded_variation_on f (s ∩ Icc a b) /-! ## Basic computations of variation -/ namespace evariation_on lemma nonempty_monotone_mem {s : set α} (hs : s.nonempty) : nonempty {u // monotone u ∧ ∀ (i : ℕ), u i ∈ s} := begin obtain ⟨x, hx⟩ := hs, exact ⟨⟨λ i, x, λ i j hij, le_rfl, λ i, hx⟩⟩, end lemma sum_le (f : α → E) {s : set α} (n : ℕ) {u : ℕ → α} (hu : monotone u) (us : ∀ i, u i ∈ s) : ∑ i in finset.range n, edist (f (u (i+1))) (f (u i)) ≤ evariation_on f s := begin let p : ℕ × {u : ℕ → α // monotone u ∧ ∀ i, u i ∈ s} := (n, ⟨u, hu, us⟩), change ∑ i in finset.range p.1, edist (f ((p.2 : ℕ → α) (i+1))) (f ((p.2 : ℕ → α) i)) ≤ evariation_on f s, exact le_supr (λ (p : ℕ × {u : ℕ → α // monotone u ∧ ∀ i, u i ∈ s}), ∑ i in finset.range p.1, edist (f ((p.2 : ℕ → α) (i+1))) (f ((p.2 : ℕ → α) i))) _, end lemma sum_le_of_monotone_on_Iic (f : α → E) {s : set α} {n : ℕ} {u : ℕ → α} (hu : monotone_on u (Iic n)) (us : ∀ i ≤ n, u i ∈ s) : ∑ i in finset.range n, edist (f (u (i+1))) (f (u i)) ≤ evariation_on f s := begin let v := λ i, if i ≤ n then u i else u n, have vs : ∀ i, v i ∈ s, { assume i, simp only [v], split_ifs, { exact us i h }, { exact us n le_rfl } }, have hv : monotone v, { apply monotone_nat_of_le_succ (λ i, _), simp only [v], rcases lt_trichotomy i n with hi|rfl|hi, { have : i + 1 ≤ n, by linarith, simp only [hi.le, this, if_true], exact hu hi.le this (nat.le_succ i) }, { simp only [le_refl, if_true, add_le_iff_nonpos_right, le_zero_iff, nat.one_ne_zero, if_false] }, { have A : ¬(i ≤ n), by linarith, have B : ¬(i + 1 ≤ n), by linarith, simp [A, B] } }, convert sum_le f n hv vs using 1, apply finset.sum_congr rfl (λ i hi, _), simp only [finset.mem_range] at hi, have : i + 1 ≤ n, by linarith, simp only [v], simp [this, hi.le], end lemma sum_le_of_monotone_on_Icc (f : α → E) {s : set α} {m n : ℕ} {u : ℕ → α} (hu : monotone_on u (Icc m n)) (us : ∀ i ∈ Icc m n, u i ∈ s) : ∑ i in finset.Ico m n, edist (f (u (i+1))) (f (u i)) ≤ evariation_on f s := begin rcases le_or_lt n m with hnm|hmn, { simp only [finset.Ico_eq_empty_of_le hnm, finset.sum_empty, zero_le'] }, let v := λ i, u (m + i), have hv : monotone_on v (Iic (n - m)), { assume a ha b hb hab, simp only [le_tsub_iff_left hmn.le, mem_Iic] at ha hb, exact hu ⟨le_add_right le_rfl, ha⟩ ⟨le_add_right le_rfl, hb⟩ (add_le_add le_rfl hab) }, have vs : ∀ i ∈ Iic (n - m), v i ∈ s, { assume i hi, simp only [le_tsub_iff_left hmn.le, mem_Iic] at hi, exact us _ ⟨le_add_right le_rfl, hi⟩ }, calc ∑ i in finset.Ico m n, edist (f (u (i + 1))) (f (u i)) = ∑ i in finset.range (n - m), edist (f (u (m + i + 1))) (f (u (m + i))) : begin rw [finset.range_eq_Ico], convert (finset.sum_Ico_add (λ i, edist (f (u (i + 1))) (f (u i))) 0 (n - m) m).symm, { rw [zero_add] }, { rw tsub_add_cancel_of_le hmn.le } end ... = ∑ i in finset.range (n - m), edist (f (v (i + 1))) (f (v i)) : begin apply finset.sum_congr rfl (λ i hi, _), simp only [v, add_assoc], end ... ≤ evariation_on f s : sum_le_of_monotone_on_Iic f hv vs, end lemma mono (f : α → E) {s t : set α} (hst : t ⊆ s) : evariation_on f t ≤ evariation_on f s := begin apply supr_le _, rintros ⟨n, ⟨u, hu, ut⟩⟩, exact sum_le f n hu (λ i, hst (ut i)), end lemma _root_.has_bounded_variation_on.mono {f : α → E} {s : set α} (h : has_bounded_variation_on f s) {t : set α} (ht : t ⊆ s) : has_bounded_variation_on f t := (lt_of_le_of_lt (evariation_on.mono f ht) (lt_top_iff_ne_top.2 h)).ne lemma _root_.has_bounded_variation_on.has_locally_bounded_variation_on {f : α → E} {s : set α} (h : has_bounded_variation_on f s) : has_locally_bounded_variation_on f s := λ x y hx hy, h.mono (inter_subset_left _ _) @[simp] protected lemma subsingleton (f : α → E) {s : set α} (hs : s.subsingleton) : evariation_on f s = 0 := begin apply le_antisymm _ (zero_le _), apply supr_le _, rintros ⟨n, ⟨u, hu, ut⟩⟩, have : ∀ i, u i = u 0, from λ i, hs (ut _) (ut _), simp [subtype.coe_mk, le_zero_iff, finset.sum_eq_zero_iff, finset.mem_range, this], end lemma edist_le (f : α → E) {s : set α} {x y : α} (hx : x ∈ s) (hy : y ∈ s) : edist (f x) (f y) ≤ evariation_on f s := begin wlog hxy : x ≤ y := le_total x y using [x y, y x] tactic.skip, swap, { assume hx hy, rw edist_comm, exact this hy hx }, let u : ℕ → α := λ n, if n = 0 then x else y, have hu : monotone u, { assume m n hmn, dsimp only [u], split_ifs, exacts [le_rfl, hxy, by linarith [pos_iff_ne_zero.2 h], le_rfl] }, have us : ∀ i, u i ∈ s, { assume i, dsimp only [u], split_ifs, exacts [hx, hy] }, convert sum_le f 1 hu us, simp [u, edist_comm], end lemma _root_.has_bounded_variation_on.dist_le {E : Type*} [pseudo_metric_space E] {f : α → E} {s : set α} (h : has_bounded_variation_on f s) {x y : α} (hx : x ∈ s) (hy : y ∈ s) : dist (f x) (f y) ≤ (evariation_on f s).to_real := begin rw [← ennreal.of_real_le_of_real_iff ennreal.to_real_nonneg, ennreal.of_real_to_real h, ← edist_dist], exact edist_le f hx hy end lemma _root_.has_bounded_variation_on.sub_le {f : α → ℝ} {s : set α} (h : has_bounded_variation_on f s) {x y : α} (hx : x ∈ s) (hy : y ∈ s) : f x - f y ≤ (evariation_on f s).to_real := begin apply (le_abs_self _).trans, rw ← real.dist_eq, exact h.dist_le hx hy end /-- Consider a monotone function `u` parameterizing some points of a set `s`. Given `x ∈ s`, then one can find another monotone function `v` parameterizing the same points as `u`, with `x` added. In particular, the variation of a function along `u` is bounded by its variation along `v`. -/ lemma add_point (f : α → E) {s : set α} {x : α} (hx : x ∈ s) (u : ℕ → α) (hu : monotone u) (us : ∀ i, u i ∈ s) (n : ℕ) : ∃ (v : ℕ → α) (m : ℕ), monotone v ∧ (∀ i, v i ∈ s) ∧ x ∈ v '' (Iio m) ∧ ∑ i in finset.range n, edist (f (u (i+1))) (f (u i)) ≤ ∑ j in finset.range m, edist (f (v (j+1))) (f (v j)) := begin rcases le_or_lt (u n) x with h|h, { let v := λ i, if i ≤ n then u i else x, have vs : ∀ i, v i ∈ s, { assume i, simp only [v], split_ifs, { exact us i }, { exact hx } }, have hv : monotone v, { apply monotone_nat_of_le_succ (λ i, _), simp only [v], rcases lt_trichotomy i n with hi|rfl|hi, { have : i + 1 ≤ n, by linarith, simp only [hi.le, this, if_true], exact hu (nat.le_succ i) }, { simp only [le_refl, if_true, add_le_iff_nonpos_right, le_zero_iff, nat.one_ne_zero, if_false, h], }, { have A : ¬(i ≤ n), by linarith, have B : ¬(i + 1 ≤ n), by linarith, simp only [A, B, if_false]} }, refine ⟨v, n+2, hv, vs, (mem_image _ _ _).2 ⟨n+1, _, _⟩, _⟩, { rw mem_Iio, exact nat.lt_succ_self (n+1) }, { have : ¬(n + 1 ≤ n), by linarith, simp only [this, ite_eq_right_iff, is_empty.forall_iff] }, { calc ∑ i in finset.range n, edist (f (u (i+1))) (f (u i)) = ∑ i in finset.range n, edist (f (v (i+1))) (f (v i)) : begin apply finset.sum_congr rfl (λ i hi, _), simp only [finset.mem_range] at hi, have : i + 1 ≤ n, by linarith, dsimp only [v], simp only [hi.le, this, if_true], end ... ≤ ∑ j in finset.range (n + 2), edist (f (v (j+1))) (f (v j)) : finset.sum_le_sum_of_subset (finset.range_mono (by linarith)) } }, have exists_N : ∃ N, N ≤ n ∧ x < u N, from ⟨n, le_rfl, h⟩, let N := nat.find exists_N, have hN : N ≤ n ∧ x < u N := nat.find_spec exists_N, let w : ℕ → α := λ i, if i < N then u i else if i = N then x else u (i - 1), have ws : ∀ i, w i ∈ s, { dsimp only [w], assume i, split_ifs, exacts [us _, hx, us _] }, have hw : monotone w, { apply monotone_nat_of_le_succ (λ i, _), dsimp only [w], rcases lt_trichotomy (i + 1) N with hi|hi|hi, { have : i < N, by linarith, simp only [hi, this, if_true], exact hu (nat.le_succ _) }, { have A : i < N, by linarith, have B : ¬(i + 1 < N), by linarith, rw [if_pos A, if_neg B, if_pos hi], have T := nat.find_min exists_N A, push_neg at T, exact T (A.le.trans hN.1) }, { have A : ¬(i < N), by linarith, have B : ¬(i + 1 < N), by linarith, have C : ¬(i + 1 = N), by linarith, have D : i + 1 - 1 = i := nat.pred_succ i, rw [if_neg A, if_neg B, if_neg C, D], split_ifs, { exact hN.2.le.trans (hu (by linarith)) }, { exact hu (nat.pred_le _) } } }, refine ⟨w, n+1, hw, ws, (mem_image _ _ _).2 ⟨N, hN.1.trans_lt (nat.lt_succ_self n), _⟩, _⟩, { dsimp only [w], rw [if_neg (lt_irrefl N), if_pos rfl] }, rcases eq_or_lt_of_le (zero_le N) with Npos|Npos, { calc ∑ i in finset.range n, edist (f (u (i + 1))) (f (u i)) = ∑ i in finset.range n, edist (f (w (1 + i + 1))) (f (w (1 + i))) : begin apply finset.sum_congr rfl (λ i hi, _), dsimp only [w], simp only [← Npos, nat.not_lt_zero, nat.add_succ_sub_one, add_zero, if_false, add_eq_zero_iff, nat.one_ne_zero, false_and, nat.succ_add_sub_one, zero_add], rw add_comm 1 i, end ... = ∑ i in finset.Ico 1 (n + 1), edist (f (w (i + 1))) (f (w i)) : begin rw finset.range_eq_Ico, exact finset.sum_Ico_add (λ i, edist (f (w (i + 1))) (f (w i))) 0 n 1, end ... ≤ ∑ j in finset.range (n + 1), edist (f (w (j + 1))) (f (w j)) : begin apply finset.sum_le_sum_of_subset _, rw finset.range_eq_Ico, exact finset.Ico_subset_Ico zero_le_one le_rfl, end }, { calc ∑ i in finset.range n, edist (f (u (i + 1))) (f (u i)) = ∑ i in finset.Ico 0 (N-1), edist (f (u (i + 1))) (f (u i)) + ∑ i in finset.Ico (N-1) N, edist (f (u (i + 1))) (f (u i)) + ∑ i in finset.Ico N n, edist (f (u (i + 1))) (f (u i)) : begin rw [finset.sum_Ico_consecutive, finset.sum_Ico_consecutive, finset.range_eq_Ico], { exact zero_le _ }, { exact hN.1 }, { exact zero_le _}, { exact nat.pred_le _ } end ... = ∑ i in finset.Ico 0 (N-1), edist (f (w (i + 1))) (f (w i)) + edist (f (u N)) (f (u (N - 1))) + ∑ i in finset.Ico N n, edist (f (w (1 + i + 1))) (f (w (1 + i))) : begin congr' 1, congr' 1, { apply finset.sum_congr rfl (λ i hi, _), simp only [finset.mem_Ico, zero_le', true_and] at hi, dsimp only [w], have A : i + 1 < N, from nat.lt_pred_iff.1 hi, have B : i < N, by linarith, rw [if_pos A, if_pos B] }, { have A : N - 1 + 1 = N, from nat.succ_pred_eq_of_pos Npos, have : finset.Ico (N - 1) N = {N - 1}, by rw [← nat.Ico_succ_singleton, A], simp only [this, A, finset.sum_singleton] }, { apply finset.sum_congr rfl (λ i hi, _), simp only [finset.mem_Ico] at hi, dsimp only [w], have A : ¬(1 + i + 1 < N), by linarith, have B : ¬(1 + i + 1 = N), by linarith, have C : ¬(1 + i < N), by linarith, have D : ¬(1 + i = N), by linarith, rw [if_neg A, if_neg B, if_neg C, if_neg D], congr' 3; { rw eq_tsub_iff_add_eq_of_le, { abel }, { linarith } } } end ... = ∑ i in finset.Ico 0 (N-1), edist (f (w (i + 1))) (f (w i)) + edist (f (w (N + 1))) (f (w (N - 1))) + ∑ i in finset.Ico (N + 1) (n + 1), edist (f (w (i + 1))) (f (w (i))) : begin congr' 1, congr' 1, { dsimp only [w], have A : ¬(N + 1 < N), by linarith, have B : N - 1 < N := nat.pred_lt Npos.ne', simp only [A, not_and, not_lt, nat.succ_ne_self, nat.add_succ_sub_one, add_zero, if_false, B, if_true] }, { exact finset.sum_Ico_add (λ i, edist (f (w (i + 1))) (f (w i))) N n 1 } end ... ≤ ∑ i in finset.Ico 0 (N - 1), edist (f (w (i + 1))) (f (w i)) + ∑ i in finset.Ico (N - 1) (N + 1), edist (f (w (i + 1))) (f (w i)) + ∑ i in finset.Ico (N + 1) (n + 1), edist (f (w (i + 1))) (f (w i)) : begin refine add_le_add (add_le_add le_rfl _) le_rfl, have A : N - 1 + 1 = N, from nat.succ_pred_eq_of_pos Npos, have B : N - 1 + 1 < N + 1, by linarith, have C : N - 1 < N + 1, by linarith, rw [finset.sum_eq_sum_Ico_succ_bot C, finset.sum_eq_sum_Ico_succ_bot B, A, finset.Ico_self, finset.sum_empty, add_zero, add_comm (edist _ _)], exact edist_triangle _ _ _, end ... = ∑ j in finset.range (n + 1), edist (f (w (j + 1))) (f (w j)) : begin rw [finset.sum_Ico_consecutive, finset.sum_Ico_consecutive, finset.range_eq_Ico], { exact zero_le _ }, { linarith }, { exact zero_le _ }, { linarith } end } end /-- The variation of a function on the union of two sets `s` and `t`, with `s` to the left of `t`, bounds the sum of the variations along `s` and `t`. -/ lemma add_le_union (f : α → E) {s t : set α} (h : ∀ x ∈ s, ∀ y ∈ t, x ≤ y) : evariation_on f s + evariation_on f t ≤ evariation_on f (s ∪ t) := begin by_cases hs : s = ∅, { simp [hs] }, haveI : nonempty {u // monotone u ∧ ∀ (i : ℕ), u i ∈ s}, from nonempty_monotone_mem (ne_empty_iff_nonempty.1 hs), by_cases ht : t = ∅, { simp [ht] }, haveI : nonempty {u // monotone u ∧ ∀ (i : ℕ), u i ∈ t}, from nonempty_monotone_mem (ne_empty_iff_nonempty.1 ht), refine ennreal.supr_add_supr_le _, /- We start from two sequences `u` and `v` along `s` and `t` respectively, and we build a new sequence `w` along `s ∪ t` by juxtaposing them. Its variation is larger than the sum of the variations. -/ rintros ⟨n, ⟨u, hu, us⟩⟩ ⟨m, ⟨v, hv, vt⟩⟩, let w := λ i, if i ≤ n then u i else v (i - (n+1)), have wst : ∀ i, w i ∈ s ∪ t, { assume i, by_cases hi : i ≤ n, { simp [w, hi, us] }, { simp [w, hi, vt] } }, have hw : monotone w, { assume i j hij, dsimp only [w], split_ifs, { exact hu hij }, { apply h _ (us _) _ (vt _) }, { linarith }, { apply hv (tsub_le_tsub hij le_rfl) } }, calc ∑ i in finset.range n, edist (f (u (i + 1))) (f (u i)) + ∑ (i : ℕ) in finset.range m, edist (f (v (i + 1))) (f (v i)) = ∑ i in finset.range n, edist (f (w (i + 1))) (f (w i)) + ∑ (i : ℕ) in finset.range m, edist (f (w ((n+1) + i + 1))) (f (w ((n+1) + i))) : begin dsimp only [w], congr' 1, { apply finset.sum_congr rfl (λ i hi, _), simp only [finset.mem_range] at hi, have : i + 1 ≤ n, by linarith, simp [hi.le, this] }, { apply finset.sum_congr rfl (λ i hi, _), simp only [finset.mem_range] at hi, have A : ¬(n + 1 + i + 1 ≤ n), by linarith, have B : ¬(n + 1 + i ≤ n), by linarith, have C : n + 1 + i - n = i + 1, { rw tsub_eq_iff_eq_add_of_le, { abel }, { linarith } }, simp only [A, B, C, nat.succ_sub_succ_eq_sub, if_false, add_tsub_cancel_left] } end ... = ∑ i in finset.range n, edist (f (w (i + 1))) (f (w i)) + ∑ (i : ℕ) in finset.Ico (n+1) ((n+1)+m), edist (f (w (i + 1))) (f (w i)) : begin congr' 1, rw finset.range_eq_Ico, convert finset.sum_Ico_add (λ (i : ℕ), edist (f (w (i + 1))) (f (w i))) 0 m (n+1) using 3; abel, end ... ≤ ∑ i in finset.range ((n+1) + m), edist (f (w (i + 1))) (f (w i)) : begin rw ← finset.sum_union, { apply finset.sum_le_sum_of_subset _, rintros i hi, simp only [finset.mem_union, finset.mem_range, finset.mem_Ico] at hi ⊢, cases hi, { linarith }, { exact hi.2 } }, { apply finset.disjoint_left.2 (λ i hi h'i, _), simp only [finset.mem_Ico, finset.mem_range] at hi h'i, linarith [h'i.1] } end ... ≤ evariation_on f (s ∪ t) : sum_le f _ hw wst end /-- If a set `s` is to the left of a set `t`, and both contain the boundary point `x`, then the variation of `f` along `s ∪ t` is the sum of the variations. -/ lemma union (f : α → E) {s t : set α} {x : α} (hs : is_greatest s x) (ht : is_least t x) : evariation_on f (s ∪ t) = evariation_on f s + evariation_on f t := begin classical, apply le_antisymm _ (evariation_on.add_le_union f (λ a ha b hb, le_trans (hs.2 ha) (ht.2 hb))), apply supr_le _, rintros ⟨n, ⟨u, hu, ust⟩⟩, obtain ⟨v, m, hv, vst, xv, huv⟩ : ∃ (v : ℕ → α) (m : ℕ), monotone v ∧ (∀ i, v i ∈ s ∪ t) ∧ x ∈ v '' (Iio m) ∧ ∑ i in finset.range n, edist (f (u (i+1))) (f (u i)) ≤ ∑ j in finset.range m, edist (f (v (j+1))) (f (v j)), from evariation_on.add_point f (mem_union_left t hs.1) u hu ust n, obtain ⟨N, hN, Nx⟩ : ∃ N, N < m ∧ v N = x, from xv, calc ∑ j in finset.range n, edist (f (u (j + 1))) (f (u j)) ≤ ∑ j in finset.range m, edist (f (v (j + 1))) (f (v j)) : huv ... = ∑ j in finset.Ico 0 N , edist (f (v (j + 1))) (f (v j)) + ∑ j in finset.Ico N m , edist (f (v (j + 1))) (f (v j)) : by rw [finset.range_eq_Ico, finset.sum_Ico_consecutive _ (zero_le _) hN.le] ... ≤ evariation_on f s + evariation_on f t : begin refine add_le_add _ _, { apply sum_le_of_monotone_on_Icc _ (hv.monotone_on _) (λ i hi, _), rcases vst i with h|h, { exact h }, have : v i = x, { apply le_antisymm, { rw ← Nx, exact hv hi.2 }, { exact ht.2 h } }, rw this, exact hs.1 }, { apply sum_le_of_monotone_on_Icc _ (hv.monotone_on _) (λ i hi, _), rcases vst i with h|h, swap, { exact h }, have : v i = x, { apply le_antisymm, { exact hs.2 h }, { rw ← Nx, exact hv hi.1 } }, rw this, exact ht.1 } end end lemma Icc_add_Icc (f : α → E) {s : set α} {a b c : α} (hab : a ≤ b) (hbc : b ≤ c) (hb : b ∈ s) : evariation_on f (s ∩ Icc a b) + evariation_on f (s ∩ Icc b c) = evariation_on f (s ∩ Icc a c) := begin have A : is_greatest (s ∩ Icc a b) b := ⟨⟨hb, hab, le_rfl⟩, (inter_subset_right _ _).trans (Icc_subset_Iic_self)⟩, have B : is_least (s ∩ Icc b c) b := ⟨⟨hb, le_rfl, hbc⟩, (inter_subset_right _ _).trans (Icc_subset_Ici_self)⟩, rw [← evariation_on.union f A B, ← inter_union_distrib_left, Icc_union_Icc_eq_Icc hab hbc], end end evariation_on /-! ## Monotone functions and bounded variation -/ lemma monotone_on.evariation_on_le {f : α → ℝ} {s : set α} (hf : monotone_on f s) {a b : α} (as : a ∈ s) (bs : b ∈ s) : evariation_on f (s ∩ Icc a b) ≤ ennreal.of_real (f b - f a) := begin apply supr_le _, rintros ⟨n, ⟨u, hu, us⟩⟩, calc ∑ i in finset.range n, edist (f (u (i+1))) (f (u i)) = ∑ i in finset.range n, ennreal.of_real (f (u (i + 1)) - f (u i)) : begin apply finset.sum_congr rfl (λ i hi, _), simp only [finset.mem_range] at hi, rw [edist_dist, real.dist_eq, abs_of_nonneg], exact sub_nonneg_of_le (hf (us i).1 (us (i+1)).1 (hu (nat.le_succ _))), end ... = ennreal.of_real (∑ i in finset.range n, (f (u (i + 1)) - f (u i))) : begin rw [ennreal.of_real_sum_of_nonneg], assume i hi, exact sub_nonneg_of_le (hf (us i).1 (us (i+1)).1 (hu (nat.le_succ _))) end ... = ennreal.of_real (f (u n) - f (u 0)) : by rw finset.sum_range_sub (λ i, f (u i)) ... ≤ ennreal.of_real (f b - f a) : begin apply ennreal.of_real_le_of_real, exact sub_le_sub (hf (us n).1 bs (us n).2.2) (hf as (us 0).1 (us 0).2.1), end end lemma monotone_on.has_locally_bounded_variation_on {f : α → ℝ} {s : set α} (hf : monotone_on f s) : has_locally_bounded_variation_on f s := λ a b as bs, ((hf.evariation_on_le as bs).trans_lt ennreal.of_real_lt_top).ne /-- If a real valued function has bounded variation on a set, then it is a difference of monotone functions there. -/ lemma has_locally_bounded_variation_on.exists_monotone_on_sub_monotone_on {f : α → ℝ} {s : set α} (h : has_locally_bounded_variation_on f s) : ∃ (p q : α → ℝ), monotone_on p s ∧ monotone_on q s ∧ f = p - q := begin rcases eq_empty_or_nonempty s with rfl|hs, { exact ⟨f, 0, subsingleton_empty.monotone_on _, subsingleton_empty.monotone_on _, by simp only [tsub_zero]⟩ }, rcases hs with ⟨c, cs⟩, let p := λ x, if c ≤ x then (evariation_on f (s ∩ Icc c x)).to_real else -(evariation_on f (s ∩ Icc x c)).to_real, have hp : monotone_on p s, { assume x xs y ys hxy, dsimp only [p], split_ifs with hcx hcy hcy, { have : evariation_on f (s ∩ Icc c x) + evariation_on f (s ∩ Icc x y) = evariation_on f (s ∩ Icc c y), from evariation_on.Icc_add_Icc f hcx hxy xs, rw [← this, ennreal.to_real_add (h c x cs xs) (h x y xs ys)], exact le_add_of_le_of_nonneg le_rfl ennreal.to_real_nonneg }, { exact (lt_irrefl _ ((not_le.1 hcy).trans_le (hcx.trans hxy))).elim }, { exact (neg_nonpos.2 ennreal.to_real_nonneg).trans ennreal.to_real_nonneg }, { simp only [neg_le_neg_iff], have : evariation_on f (s ∩ Icc x y) + evariation_on f (s ∩ Icc y c) = evariation_on f (s ∩ Icc x c), from evariation_on.Icc_add_Icc f hxy (not_le.1 hcy).le ys, rw [← this, ennreal.to_real_add (h x y xs ys) (h y c ys cs), add_comm], exact le_add_of_le_of_nonneg le_rfl ennreal.to_real_nonneg } }, have hq : monotone_on (λ x, p x - f x) s, { assume x xs y ys hxy, dsimp only [p], split_ifs with hcx hcy hcy, { have : evariation_on f (s ∩ Icc c x) + evariation_on f (s ∩ Icc x y) = evariation_on f (s ∩ Icc c y), from evariation_on.Icc_add_Icc f hcx hxy xs, rw [← this, ennreal.to_real_add (h c x cs xs) (h x y xs ys)], suffices : f y - f x ≤ (evariation_on f (s ∩ Icc x y)).to_real, by linarith, exact (h x y xs ys).sub_le ⟨ys, hxy, le_rfl⟩ ⟨xs, le_rfl, hxy⟩ }, { exact (lt_irrefl _ ((not_le.1 hcy).trans_le (hcx.trans hxy))).elim }, { suffices : f y - f x ≤ (evariation_on f (s ∩ Icc x c)).to_real + (evariation_on f (s ∩ Icc c y)).to_real, by linarith, rw [← ennreal.to_real_add (h x c xs cs) (h c y cs ys), evariation_on.Icc_add_Icc f (not_le.1 hcx).le hcy cs], exact (h x y xs ys).sub_le ⟨ys, hxy, le_rfl⟩ ⟨xs, le_rfl, hxy⟩ }, { have : evariation_on f (s ∩ Icc x y) + evariation_on f (s ∩ Icc y c) = evariation_on f (s ∩ Icc x c), from evariation_on.Icc_add_Icc f hxy (not_le.1 hcy).le ys, rw [← this, ennreal.to_real_add (h x y xs ys) (h y c ys cs)], suffices : f y - f x ≤ (evariation_on f (s ∩ Icc x y)).to_real, by linarith, exact (h x y xs ys).sub_le ⟨ys, hxy, le_rfl⟩ ⟨xs, le_rfl, hxy⟩ } }, refine ⟨p, λ x, p x - f x, hp, hq, _⟩, ext x, dsimp, abel, end /-! ## Lipschitz functions and bounded variation -/ lemma lipschitz_on_with.comp_evariation_on_le {f : E → F} {C : ℝ≥0} {t : set E} (h : lipschitz_on_with C f t) {g : α → E} {s : set α} (hg : maps_to g s t) : evariation_on (f ∘ g) s ≤ C * evariation_on g s := begin apply supr_le _, rintros ⟨n, ⟨u, hu, us⟩⟩, calc ∑ i in finset.range n, edist (f (g (u (i+1)))) (f (g (u i))) ≤ ∑ i in finset.range n, C * edist (g (u (i+1))) (g (u i)) : finset.sum_le_sum (λ i hi, h (hg (us _)) (hg (us _))) ... = C * ∑ i in finset.range n, edist (g (u (i+1))) (g (u i)) : by rw finset.mul_sum ... ≤ C * evariation_on g s : mul_le_mul_left' (evariation_on.sum_le _ _ hu us) _ end lemma lipschitz_on_with.comp_has_bounded_variation_on {f : E → F} {C : ℝ≥0} {t : set E} (hf : lipschitz_on_with C f t) {g : α → E} {s : set α} (hg : maps_to g s t) (h : has_bounded_variation_on g s) : has_bounded_variation_on (f ∘ g) s := begin dsimp [has_bounded_variation_on] at h, apply ne_of_lt, apply (hf.comp_evariation_on_le hg).trans_lt, simp [lt_top_iff_ne_top, h], end lemma lipschitz_on_with.comp_has_locally_bounded_variation_on {f : E → F} {C : ℝ≥0} {t : set E} (hf : lipschitz_on_with C f t) {g : α → E} {s : set α} (hg : maps_to g s t) (h : has_locally_bounded_variation_on g s) : has_locally_bounded_variation_on (f ∘ g) s := λ x y xs ys, hf.comp_has_bounded_variation_on (hg.mono_left (inter_subset_left _ _)) (h x y xs ys) lemma lipschitz_with.comp_has_bounded_variation_on {f : E → F} {C : ℝ≥0} (hf : lipschitz_with C f) {g : α → E} {s : set α} (h : has_bounded_variation_on g s) : has_bounded_variation_on (f ∘ g) s := (hf.lipschitz_on_with univ).comp_has_bounded_variation_on (maps_to_univ _ _) h lemma lipschitz_with.comp_has_locally_bounded_variation_on {f : E → F} {C : ℝ≥0} (hf : lipschitz_with C f) {g : α → E} {s : set α} (h : has_locally_bounded_variation_on g s) : has_locally_bounded_variation_on (f ∘ g) s := (hf.lipschitz_on_with univ).comp_has_locally_bounded_variation_on (maps_to_univ _ _) h lemma lipschitz_on_with.has_locally_bounded_variation_on {f : ℝ → E} {C : ℝ≥0} {s : set ℝ} (hf : lipschitz_on_with C f s) : has_locally_bounded_variation_on f s := hf.comp_has_locally_bounded_variation_on (maps_to_id _) (@monotone_on_id ℝ _ s).has_locally_bounded_variation_on lemma lipschitz_with.has_locally_bounded_variation_on {f : ℝ → E} {C : ℝ≥0} (hf : lipschitz_with C f) (s : set ℝ) : has_locally_bounded_variation_on f s := (hf.lipschitz_on_with s).has_locally_bounded_variation_on /-! ## Almost everywhere differentiability of functions with locally bounded variation -/ namespace has_locally_bounded_variation_on /-- A bounded variation function into `ℝ` is differentiable almost everywhere. Superseded by `ae_differentiable_within_at_of_mem`. -/ theorem ae_differentiable_within_at_of_mem_real {f : ℝ → ℝ} {s : set ℝ} (h : has_locally_bounded_variation_on f s) : ∀ᵐ x, x ∈ s → differentiable_within_at ℝ f s x := begin obtain ⟨p, q, hp, hq, fpq⟩ : ∃ p q, monotone_on p s ∧ monotone_on q s ∧ f = p - q, from h.exists_monotone_on_sub_monotone_on, filter_upwards [hp.ae_differentiable_within_at_of_mem, hq.ae_differentiable_within_at_of_mem] with x hxp hxq xs, have fpq : ∀ x, f x = p x - q x, by simp [fpq], refine ((hxp xs).sub (hxq xs)).congr (λ y hy, fpq y) (fpq x), end /-- A bounded variation function into a finite dimensional product vector space is differentiable almost everywhere. Superseded by `ae_differentiable_within_at_of_mem`. -/ theorem ae_differentiable_within_at_of_mem_pi {ι : Type*} [fintype ι] {f : ℝ → (ι → ℝ)} {s : set ℝ} (h : has_locally_bounded_variation_on f s) : ∀ᵐ x, x ∈ s → differentiable_within_at ℝ f s x := begin have A : ∀ (i : ι), lipschitz_with 1 (λ (x : ι → ℝ), x i) := λ i, lipschitz_with.eval i, have : ∀ (i : ι), ∀ᵐ x, x ∈ s → differentiable_within_at ℝ (λ (x : ℝ), f x i) s x, { assume i, apply ae_differentiable_within_at_of_mem_real, exact lipschitz_with.comp_has_locally_bounded_variation_on (A i) h }, filter_upwards [ae_all_iff.2 this] with x hx xs, exact differentiable_within_at_pi.2 (λ i, hx i xs), end /-- A real function into a finite dimensional real vector space with bounded variation on a set is differentiable almost everywhere in this set. -/ theorem ae_differentiable_within_at_of_mem {f : ℝ → V} {s : set ℝ} (h : has_locally_bounded_variation_on f s) : ∀ᵐ x, x ∈ s → differentiable_within_at ℝ f s x := begin let A := (basis.of_vector_space ℝ V).equiv_fun.to_continuous_linear_equiv, suffices H : ∀ᵐ x, x ∈ s → differentiable_within_at ℝ (A ∘ f) s x, { filter_upwards [H] with x hx xs, have : f = (A.symm ∘ A) ∘ f, by simp only [continuous_linear_equiv.symm_comp_self, function.comp.left_id], rw this, exact A.symm.differentiable_at.comp_differentiable_within_at x (hx xs) }, apply ae_differentiable_within_at_of_mem_pi, exact A.lipschitz.comp_has_locally_bounded_variation_on h, end /-- A real function into a finite dimensional real vector space with bounded variation on a set is differentiable almost everywhere in this set. -/ theorem ae_differentiable_within_at {f : ℝ → V} {s : set ℝ} (h : has_locally_bounded_variation_on f s) (hs : measurable_set s) : ∀ᵐ x ∂(volume.restrict s), differentiable_within_at ℝ f s x := begin rw ae_restrict_iff' hs, exact h.ae_differentiable_within_at_of_mem end /-- A real function into a finite dimensional real vector space with bounded variation is differentiable almost everywhere. -/ theorem ae_differentiable_at {f : ℝ → V} (h : has_locally_bounded_variation_on f univ) : ∀ᵐ x, differentiable_at ℝ f x := begin filter_upwards [h.ae_differentiable_within_at_of_mem] with x hx, rw differentiable_within_at_univ at hx, exact hx (mem_univ _), end end has_locally_bounded_variation_on /-- A real function into a finite dimensional real vector space which is Lipschitz on a set is differentiable almost everywhere in this set . -/ lemma lipschitz_on_with.ae_differentiable_within_at_of_mem {C : ℝ≥0} {f : ℝ → V} {s : set ℝ} (h : lipschitz_on_with C f s) : ∀ᵐ x, x ∈ s → differentiable_within_at ℝ f s x := h.has_locally_bounded_variation_on.ae_differentiable_within_at_of_mem /-- A real function into a finite dimensional real vector space which is Lipschitz on a set is differentiable almost everywhere in this set. -/ lemma lipschitz_on_with.ae_differentiable_within_at {C : ℝ≥0} {f : ℝ → V} {s : set ℝ} (h : lipschitz_on_with C f s) (hs : measurable_set s) : ∀ᵐ x ∂(volume.restrict s), differentiable_within_at ℝ f s x := h.has_locally_bounded_variation_on.ae_differentiable_within_at hs /-- A real Lipschitz function into a finite dimensional real vector space is differentiable almost everywhere. -/ lemma lipschitz_with.ae_differentiable_at {C : ℝ≥0} {f : ℝ → V} (h : lipschitz_with C f) : ∀ᵐ x, differentiable_at ℝ f x := (h.has_locally_bounded_variation_on univ).ae_differentiable_at
b8a2c835eb556cf5dec5e800d4745d425974944f
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Declaration.lean
e9f0d5272cd56f4adf53e49e67eacd1075691e7a
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,094
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Expr namespace Lean /-- Reducibility hints are used in the convertibility checker. When trying to solve a constraint such a (f ...) =?= (g ...) where f and g are definitions, the checker has to decide which one will be unfolded. If f (g) is opaque, then g (f) is unfolded if it is also not marked as opaque, Else if f (g) is abbrev, then f (g) is unfolded if g (f) is also not marked as abbrev, Else if f and g are regular, then we unfold the one with the biggest definitional height. Otherwise both are unfolded. The arguments of the `regular` Constructor are: the definitional height and the flag `selfOpt`. The definitional height is by default computed by the kernel. It only takes into account other regular definitions used in a definition. When creating declarations using meta-programming, we can specify the definitional depth manually. Remark: the hint only affects performance. None of the hints prevent the kernel from unfolding a declaration during Type checking. Remark: the ReducibilityHints are not related to the attributes: reducible/irrelevance/semireducible. These attributes are used by the Elaborator. The ReducibilityHints are used by the kernel (and Elaborator). Moreover, the ReducibilityHints cannot be changed after a declaration is added to the kernel. -/ inductive ReducibilityHints where | opaque : ReducibilityHints | «abbrev» : ReducibilityHints | regular : UInt32 → ReducibilityHints deriving Inhabited @[export lean_mk_reducibility_hints_regular] def mkReducibilityHintsRegularEx (h : UInt32) : ReducibilityHints := ReducibilityHints.regular h @[export lean_reducibility_hints_get_height] def ReducibilityHints.getHeightEx (h : ReducibilityHints) : UInt32 := match h with | ReducibilityHints.regular h => h | _ => 0 namespace ReducibilityHints def lt : ReducibilityHints → ReducibilityHints → Bool | «abbrev», «abbrev» => false | «abbrev», _ => true | regular d₁, regular d₂ => d₁ < d₂ | regular _, opaque => true | _, _ => false end ReducibilityHints /-- Base structure for `AxiomVal`, `DefinitionVal`, `TheoremVal`, `InductiveVal`, `ConstructorVal`, `RecursorVal` and `QuotVal`. -/ structure ConstantVal where name : Name levelParams : List Name type : Expr deriving Inhabited structure AxiomVal extends ConstantVal where isUnsafe : Bool deriving Inhabited @[export lean_mk_axiom_val] def mkAxiomValEx (name : Name) (levelParams : List Name) (type : Expr) (isUnsafe : Bool) : AxiomVal := { name := name, levelParams := levelParams, type := type, isUnsafe := isUnsafe } @[export lean_axiom_val_is_unsafe] def AxiomVal.isUnsafeEx (v : AxiomVal) : Bool := v.isUnsafe inductive DefinitionSafety where | «unsafe» | safe | «partial» deriving Inhabited, BEq, Repr structure DefinitionVal extends ConstantVal where value : Expr hints : ReducibilityHints safety : DefinitionSafety deriving Inhabited @[export lean_mk_definition_val] def mkDefinitionValEx (name : Name) (levelParams : List Name) (type : Expr) (val : Expr) (hints : ReducibilityHints) (safety : DefinitionSafety) : DefinitionVal := { name := name, levelParams := levelParams, type := type, value := val, hints := hints, safety := safety } @[export lean_definition_val_get_safety] def DefinitionVal.getSafetyEx (v : DefinitionVal) : DefinitionSafety := v.safety structure TheoremVal extends ConstantVal where value : Expr deriving Inhabited /- Value for an opaque constant declaration `constant x : t := e` -/ structure OpaqueVal extends ConstantVal where value : Expr isUnsafe : Bool deriving Inhabited @[export lean_mk_opaque_val] def mkOpaqueValEx (name : Name) (levelParams : List Name) (type : Expr) (val : Expr) (isUnsafe : Bool) : OpaqueVal := { name := name, levelParams := levelParams, type := type, value := val, isUnsafe := isUnsafe } @[export lean_opaque_val_is_unsafe] def OpaqueVal.isUnsafeEx (v : OpaqueVal) : Bool := v.isUnsafe structure Constructor where name : Name type : Expr deriving Inhabited structure InductiveType where name : Name type : Expr ctors : List Constructor deriving Inhabited /-- Declaration object that can be sent to the kernel. -/ inductive Declaration where | axiomDecl (val : AxiomVal) | defnDecl (val : DefinitionVal) | thmDecl (val : TheoremVal) | opaqueDecl (val : OpaqueVal) | quotDecl | mutualDefnDecl (defns : List DefinitionVal) -- All definitions must be marked as `unsafe` or `partial` | inductDecl (lparams : List Name) (nparams : Nat) (types : List InductiveType) (isUnsafe : Bool) deriving Inhabited @[export lean_mk_inductive_decl] def mkInductiveDeclEs (lparams : List Name) (nparams : Nat) (types : List InductiveType) (isUnsafe : Bool) : Declaration := Declaration.inductDecl lparams nparams types isUnsafe @[export lean_is_unsafe_inductive_decl] def Declaration.isUnsafeInductiveDeclEx : Declaration → Bool | Declaration.inductDecl _ _ _ isUnsafe => isUnsafe | _ => false @[specialize] def Declaration.foldExprM {α} {m : Type → Type} [Monad m] (d : Declaration) (f : α → Expr → m α) (a : α) : m α := match d with | Declaration.quotDecl => pure a | Declaration.axiomDecl { type := type, .. } => f a type | Declaration.defnDecl { type := type, value := value, .. } => do let a ← f a type; f a value | Declaration.opaqueDecl { type := type, value := value, .. } => do let a ← f a type; f a value | Declaration.thmDecl { type := type, value := value, .. } => do let a ← f a type; f a value | Declaration.mutualDefnDecl vals => vals.foldlM (fun a v => do let a ← f a v.type; f a v.value) a | Declaration.inductDecl _ _ inductTypes _ => inductTypes.foldlM (fun a inductType => do let a ← f a inductType.type inductType.ctors.foldlM (fun a ctor => f a ctor.type) a) a @[inline] def Declaration.forExprM {m : Type → Type} [Monad m] (d : Declaration) (f : Expr → m Unit) : m Unit := d.foldExprM (fun _ a => f a) () /-- The kernel compiles (mutual) inductive declarations (see `inductiveDecls`) into a set of - `Declaration.inductDecl` (for each inductive datatype in the mutual Declaration), - `Declaration.ctorDecl` (for each Constructor in the mutual Declaration), - `Declaration.recDecl` (automatically generated recursors). This data is used to implement iota-reduction efficiently and compile nested inductive declarations. A series of checks are performed by the kernel to check whether a `inductiveDecls` is valid or not. -/ structure InductiveVal extends ConstantVal where numParams : Nat -- Number of parameters numIndices : Nat -- Number of indices all : List Name -- List of all (including this one) inductive datatypes in the mutual declaration containing this one ctors : List Name -- List of all constructors for this inductive datatype isRec : Bool -- `true` Iff it is recursive isUnsafe : Bool isReflexive : Bool isNested : Bool deriving Inhabited @[export lean_mk_inductive_val] def mkInductiveValEx (name : Name) (levelParams : List Name) (type : Expr) (numParams numIndices : Nat) (all ctors : List Name) (isRec isUnsafe isReflexive isNested : Bool) : InductiveVal := { name := name levelParams := levelParams type := type numParams := numParams numIndices := numIndices all := all ctors := ctors isRec := isRec isUnsafe := isUnsafe isReflexive := isReflexive isNested := isNested } @[export lean_inductive_val_is_rec] def InductiveVal.isRecEx (v : InductiveVal) : Bool := v.isRec @[export lean_inductive_val_is_unsafe] def InductiveVal.isUnsafeEx (v : InductiveVal) : Bool := v.isUnsafe @[export lean_inductive_val_is_reflexive] def InductiveVal.isReflexiveEx (v : InductiveVal) : Bool := v.isReflexive @[export lean_inductive_val_is_nested] def InductiveVal.isNestedEx (v : InductiveVal) : Bool := v.isNested def InductiveVal.nctors (v : InductiveVal) : Nat := v.ctors.length structure ConstructorVal extends ConstantVal where induct : Name -- Inductive Type this Constructor is a member of cidx : Nat -- Constructor index (i.e., Position in the inductive declaration) numParams : Nat -- Number of parameters in inductive datatype `induct` numFields : Nat -- Number of fields (i.e., arity - nparams) isUnsafe : Bool deriving Inhabited @[export lean_mk_constructor_val] def mkConstructorValEx (name : Name) (levelParams : List Name) (type : Expr) (induct : Name) (cidx numParams numFields : Nat) (isUnsafe : Bool) : ConstructorVal := { name := name, levelParams := levelParams, type := type, induct := induct, cidx := cidx, numParams := numParams, numFields := numFields, isUnsafe := isUnsafe } @[export lean_constructor_val_is_unsafe] def ConstructorVal.isUnsafeEx (v : ConstructorVal) : Bool := v.isUnsafe /-- Information for reducing a recursor -/ structure RecursorRule where ctor : Name -- Reduction rule for this Constructor nfields : Nat -- Number of fields (i.e., without counting inductive datatype parameters) rhs : Expr -- Right hand side of the reduction rule deriving Inhabited structure RecursorVal extends ConstantVal where all : List Name -- List of all inductive datatypes in the mutual declaration that generated this recursor numParams : Nat -- Number of parameters numIndices : Nat -- Number of indices numMotives : Nat -- Number of motives numMinors : Nat -- Number of minor premises rules : List RecursorRule -- A reduction for each Constructor k : Bool -- It supports K-like reduction isUnsafe : Bool deriving Inhabited @[export lean_mk_recursor_val] def mkRecursorValEx (name : Name) (levelParams : List Name) (type : Expr) (all : List Name) (numParams numIndices numMotives numMinors : Nat) (rules : List RecursorRule) (k isUnsafe : Bool) : RecursorVal := { name := name, levelParams := levelParams, type := type, all := all, numParams := numParams, numIndices := numIndices, numMotives := numMotives, numMinors := numMinors, rules := rules, k := k, isUnsafe := isUnsafe } @[export lean_recursor_k] def RecursorVal.kEx (v : RecursorVal) : Bool := v.k @[export lean_recursor_is_unsafe] def RecursorVal.isUnsafeEx (v : RecursorVal) : Bool := v.isUnsafe def RecursorVal.getMajorIdx (v : RecursorVal) : Nat := v.numParams + v.numMotives + v.numMinors + v.numIndices def RecursorVal.getFirstIndexIdx (v : RecursorVal) : Nat := v.numParams + v.numMotives + v.numMinors def RecursorVal.getFirstMinorIdx (v : RecursorVal) : Nat := v.numParams + v.numMotives def RecursorVal.getInduct (v : RecursorVal) : Name := v.name.getPrefix inductive QuotKind where | type -- `Quot` | ctor -- `Quot.mk` | lift -- `Quot.lift` | ind -- `Quot.ind` deriving Inhabited structure QuotVal extends ConstantVal where kind : QuotKind deriving Inhabited @[export lean_mk_quot_val] def mkQuotValEx (name : Name) (levelParams : List Name) (type : Expr) (kind : QuotKind) : QuotVal := { name := name, levelParams := levelParams, type := type, kind := kind } @[export lean_quot_val_kind] def QuotVal.kindEx (v : QuotVal) : QuotKind := v.kind /-- Information associated with constant declarations. -/ inductive ConstantInfo where | axiomInfo (val : AxiomVal) | defnInfo (val : DefinitionVal) | thmInfo (val : TheoremVal) | opaqueInfo (val : OpaqueVal) | quotInfo (val : QuotVal) | inductInfo (val : InductiveVal) | ctorInfo (val : ConstructorVal) | recInfo (val : RecursorVal) deriving Inhabited namespace ConstantInfo def toConstantVal : ConstantInfo → ConstantVal | defnInfo {toConstantVal := d, ..} => d | axiomInfo {toConstantVal := d, ..} => d | thmInfo {toConstantVal := d, ..} => d | opaqueInfo {toConstantVal := d, ..} => d | quotInfo {toConstantVal := d, ..} => d | inductInfo {toConstantVal := d, ..} => d | ctorInfo {toConstantVal := d, ..} => d | recInfo {toConstantVal := d, ..} => d def isUnsafe : ConstantInfo → Bool | defnInfo v => v.safety == DefinitionSafety.unsafe | axiomInfo v => v.isUnsafe | thmInfo v => false | opaqueInfo v => v.isUnsafe | quotInfo v => false | inductInfo v => v.isUnsafe | ctorInfo v => v.isUnsafe | recInfo v => v.isUnsafe def name (d : ConstantInfo) : Name := d.toConstantVal.name def levelParams (d : ConstantInfo) : List Name := d.toConstantVal.levelParams def type (d : ConstantInfo) : Expr := d.toConstantVal.type def value? : ConstantInfo → Option Expr | defnInfo {value := r, ..} => some r | thmInfo {value := r, ..} => some r | _ => none def hasValue : ConstantInfo → Bool | defnInfo {value := r, ..} => true | thmInfo {value := r, ..} => true | _ => false def value! : ConstantInfo → Expr | defnInfo {value := r, ..} => r | thmInfo {value := r, ..} => r | _ => panic! "declaration with value expected" def hints : ConstantInfo → ReducibilityHints | defnInfo {hints := r, ..} => r | _ => ReducibilityHints.opaque def isCtor : ConstantInfo → Bool | ctorInfo _ => true | _ => false @[extern "lean_instantiate_type_lparams"] constant instantiateTypeLevelParams (c : @& ConstantInfo) (ls : @& List Level) : Expr @[extern "lean_instantiate_value_lparams"] constant instantiateValueLevelParams (c : @& ConstantInfo) (ls : @& List Level) : Expr end ConstantInfo def mkRecName (declName : Name) : Name := Name.mkStr declName "rec" end Lean
c1b799a834025af8084f6f039c46ed5af26a6a93
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/task_test_io.lean
f567c3308345dcb6d9bb466580c1b1ae835260d0
[ "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
912
lean
#lang lean4 #eval id (α := IO _) do let t1 ← IO.asTask $ Nat.forM 10 fun _ => IO.println "hi"; let t2 ← IO.asTask $ Nat.forM 10 fun _ => IO.println "ho"; IO.ofExcept t1.get #eval id (α := IO _) do let t1 ← IO.mapTask IO.println (Task.spawn fun _ => "ha"); pure () #eval id (α := IO _) do let t1 ← IO.bindTask (Task.spawn fun _ => "hu") fun s => IO.asTask (IO.println s); pure () #eval id (α := IO _) do let t1 ← IO.asTask do { let c ← IO.checkCanceled; IO.println (if c then "canceled!" else "done!") }; pure () #eval id (α := IO _) do let t1 ← IO.asTask do { let c ← IO.checkCanceled; IO.println (if c then "canceled! 2" else "done! 2") }; IO.cancel t1; IO.wait t1; pure () #eval IO.waitAny [ Task.spawn fun _ => dbgSleep 2 fun _ => "A", Task.spawn fun _ => dbgSleep 3 fun _ => "B", Task.spawn fun _ => dbgSleep 1 fun _ => "C" ]
2659a3f42f565aed0f2187732ce6845d99d260d7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/lint_coe_t.lean
0a809d2f6e3509731d65f2c6f9172ab07374773d
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,075
lean
import tactic.lint open tactic -- bad, because every iteration of tc search will loop, generating nested quotients section local attribute [instance] def a_to_quot {α} (R : setoid α) : has_coe α (quotient R) := ⟨quotient.mk⟩ run_cmd do d ← get_decl ``a_to_quot, some _ ← linter.has_coe_variable.test d, d ← get_decl ``coe_trans, some s ← fails_quickly 3000 d, guard $ "maximum class-instance resolution depth has been reached".is_prefix_of s end -- good, because the term gets smaller in every iteration noncomputable instance quot_to_a {α} (R : setoid α) : has_coe (quotient R) α := ⟨λ q, quot.rec_on q (λ a, classical.choice ⟨a⟩) (by cc)⟩ run_cmd do decl ← get_decl ``quot_to_a, -- linter does not complain none ← linter.has_coe_variable.test decl, skip -- bad, because it introduces a metavariable section local attribute [instance] def int_to_a {α} [inhabited α] : has_coe ℤ α := ⟨default⟩ run_cmd do decl ← get_decl ``int_to_a, -- linter does not complain some _ ← linter.has_coe_variable.test decl, skip end
39f1567e89ade9b1300455bd740a34864527153c
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/src/builtin/sum.lean
abfc2e50f58ecdf396f7c96d5ce55855bff331fe
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
7,035
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 macros subtype optional using subtype using optional -- We are encoding the (sum A B) as a subtype of (optional A) # (optional B), where -- (proj1 n = none) ≠ (proj2 n = none) definition sum_pred (A B : (Type U)) := λ p : (optional A) # (optional B), (proj1 p = none) ≠ (proj2 p = none) definition sum (A B : (Type U)) := subtype ((optional A) # (optional B)) (sum_pred A B) namespace sum theorem inl_pred {A : (Type U)} (a : A) (B : (Type U)) : sum_pred A B (pair (some a) none) := not_intro (assume N : (some a = none) = (none = (@none B)), have eq : some a = none, from (symm N) ◂ (refl (@none B)), show false, from absurd eq (distinct a)) theorem inr_pred (A : (Type U)) {B : (Type U)} (b : B) : sum_pred A B (pair none (some b)) := not_intro (assume N : (none = (@none A)) = (some b = none), have eq : some b = none, from N ◂ (refl (@none A)), show false, from absurd eq (distinct b)) theorem inhabl {A : (Type U)} (H : inhabited A) (B : (Type U)) : inhabited (sum A B) := inhabited_elim H (take w : A, subtype_inhabited (exists_intro (pair (some w) none) (inl_pred w B))) theorem inhabr (A : (Type U)) {B : (Type U)} (H : inhabited B) : inhabited (sum A B) := inhabited_elim H (take w : B, subtype_inhabited (exists_intro (pair none (some w)) (inr_pred A w))) definition inl {A : (Type U)} (a : A) (B : (Type U)) : sum A B := abst (pair (some a) none) (inhabl (inhabited_intro a) B) definition inr (A : (Type U)) {B : (Type U)} (b : B) : sum A B := abst (pair none (some b)) (inhabr A (inhabited_intro b)) theorem inl_inj {A B : (Type U)} {a1 a2 : A} : inl a1 B = inl a2 B → a1 = a2 := assume Heq : inl a1 B = inl a2 B, have eq1 : inl a1 B = abst (pair (some a1) none) (inhabl (inhabited_intro a1) B), from refl (inl a1 B), have eq2 : inl a2 B = abst (pair (some a2) none) (inhabl (inhabited_intro a1) B), from subst (refl (inl a2 B)) (proof_irrel (inhabl (inhabited_intro a2) B) (inhabl (inhabited_intro a1) B)), have rep_eq : (pair (some a1) none) = (pair (some a2) none), from abst_inj (inhabl (inhabited_intro a1) B) (inl_pred a1 B) (inl_pred a2 B) (trans (trans (symm eq1) Heq) eq2), show a1 = a2, from optional::injectivity (calc some a1 = proj1 (pair (some a1) (@none B)) : refl (some a1) ... = proj1 (pair (some a2) (@none B)) : proj1_congr rep_eq ... = some a2 : refl (some a2)) theorem inr_inj {A B : (Type U)} {b1 b2 : B} : inr A b1 = inr A b2 → b1 = b2 := assume Heq : inr A b1 = inr A b2, have eq1 : inr A b1 = abst (pair none (some b1)) (inhabr A (inhabited_intro b1)), from refl (inr A b1), have eq2 : inr A b2 = abst (pair none (some b2)) (inhabr A (inhabited_intro b1)), from subst (refl (inr A b2)) (proof_irrel (inhabr A (inhabited_intro b2)) (inhabr A (inhabited_intro b1))), have rep_eq : (pair none (some b1)) = (pair none (some b2)), from abst_inj (inhabr A (inhabited_intro b1)) (inr_pred A b1) (inr_pred A b2) (trans (trans (symm eq1) Heq) eq2), show b1 = b2, from optional::injectivity (calc some b1 = proj2 (pair (@none A) (some b1)) : refl (some b1) ... = proj2 (pair (@none A) (some b2)) : proj2_congr rep_eq ... = some b2 : refl (some b2)) theorem distinct {A B : (Type U)} (a : A) (b : B) : inl a B ≠ inr A b := not_intro (assume N : inl a B = inr A b, have eq1 : inl a B = abst (pair (some a) none) (inhabl (inhabited_intro a) B), from refl (inl a B), have eq2 : inr A b = abst (pair none (some b)) (inhabl (inhabited_intro a) B), from subst (refl (inr A b)) (proof_irrel (inhabr A (inhabited_intro b)) (inhabl (inhabited_intro a) B)), have rep_eq : (pair (some a) none) = (pair none (some b)), from abst_inj (inhabl (inhabited_intro a) B) (inl_pred a B) (inr_pred A b) (trans (trans (symm eq1) N) eq2), show false, from absurd (proj1_congr rep_eq) (optional::distinct a)) theorem dichotomy {A B : (Type U)} (n : sum A B) : (∃ a, n = inl a B) ∨ (∃ b, n = inr A b) := let pred : (proj1 (rep n) = none) ≠ (proj2 (rep n) = none) := P_rep n in or_elim (em (proj1 (rep n) = none)) (assume Heq : proj1 (rep n) = none, have neq_none : ¬ proj2 (rep n) = (@none B), from (symm (not_iff_elim (ne_symm pred))) ◂ Heq, have ex_some : ∃ b, proj2 (rep n) = some b, from resolve1 (optional::dichotomy (proj2 (rep n))) neq_none, obtain (b : B) (Hb : proj2 (rep n) = some b), from ex_some, show (∃ a, n = inl a B) ∨ (∃ b, n = inr A b), from or_intror (∃ a, n = inl a B) (have rep_eq : rep n = pair none (some b), from pairext_proj Heq Hb, have rep_inr : rep (inr A b) = pair none (some b), from rep_abst (inhabr A (inhabited_intro b)) (pair none (some b)) (inr_pred A b), have n_eq_inr : n = inr A b, from rep_inj (trans rep_eq (symm rep_inr)), show (∃ b, n = inr A b), from exists_intro b n_eq_inr)) (assume Hne : ¬ proj1 (rep n) = none, have eq_none : proj2 (rep n) = (@none B), from (not_iff_elim pred) ◂ Hne, have ex_some : ∃ a, proj1 (rep n) = some a, from resolve1 (optional::dichotomy (proj1 (rep n))) Hne, obtain (a : A) (Ha : proj1 (rep n) = some a), from ex_some, show (∃ a, n = inl a B) ∨ (∃ b, n = inr A b), from or_introl (have rep_eq : rep n = pair (some a) none, from pairext_proj Ha eq_none, have rep_inl : rep (inl a B) = pair (some a) none, from rep_abst (inhabl (inhabited_intro a) B) (pair (some a) none) (inl_pred a B), have n_eq_inl : n = inl a B, from rep_inj (trans rep_eq (symm rep_inl)), show ∃ a, n = inl a B, from exists_intro a n_eq_inl) (∃ b, n = inr A b)) theorem induction {A B : (Type U)} {P : sum A B → Bool} (H1 : ∀ a, P (inl a B)) (H2 : ∀ b, P (inr A b)) : ∀ n, P n := take n, or_elim (sum::dichotomy n) (assume Hex : ∃ a, n = inl a B, obtain (a : A) (Ha : n = inl a B), from Hex, show P n, from subst (H1 a) (symm Ha)) (assume Hex : ∃ b, n = inr A b, obtain (b : B) (Hb : n = inr A b), from Hex, show P n, from subst (H2 b) (symm Hb)) set_opaque inl true set_opaque inr true end set_opaque sum_pred true set_opaque sum true
662f5fec6c1009b5ca0c774ded18c15488803058
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/dynamics/circle/rotation_number/translation_number.lean
578ccef2af38496ccd8c20d663d31c351b66d7b5
[ "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
39,650
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import algebra.iterate_hom import analysis.specific_limits import topology.algebra.ordered.monotone_continuity import order.iterate import order.semiconj_Sup /-! # Translation number of a monotone real map that commutes with `x ↦ x + 1` Let `f : ℝ → ℝ` be a monotone map such that `f (x + 1) = f x + 1` for all `x`. Then the limit $$ \tau(f)=\lim_{n\to\infty}{f^n(x)-x}{n} $$ exists and does not depend on `x`. This number is called the *translation number* of `f`. Different authors use different notation for this number: `τ`, `ρ`, `rot`, etc In this file we define a structure `circle_deg1_lift` for bundled maps with these properties, define translation number of `f : circle_deg1_lift`, prove some estimates relating `f^n(x)-x` to `τ(f)`. In case of a continuous map `f` we also prove that `f` admits a point `x` such that `f^n(x)=x+m` if and only if `τ(f)=m/n`. Maps of this type naturally appear as lifts of orientation preserving circle homeomorphisms. More precisely, let `f` be an orientation preserving homeomorphism of the circle $S^1=ℝ/ℤ$, and consider a real number `a` such that `⟦a⟧ = f 0`, where `⟦⟧` means the natural projection `ℝ → ℝ/ℤ`. Then there exists a unique continuous function `F : ℝ → ℝ` such that `F 0 = a` and `⟦F x⟧ = f ⟦x⟧` for all `x` (this fact is not formalized yet). This function is strictly monotone, continuous, and satisfies `F (x + 1) = F x + 1`. The number `⟦τ F⟧ : ℝ / ℤ` is called the *rotation number* of `f`. It does not depend on the choice of `a`. ## Main definitions * `circle_deg1_lift`: a monotone map `f : ℝ → ℝ` such that `f (x + 1) = f x + 1` for all `x`; the type `circle_deg1_lift` is equipped with `lattice` and `monoid` structures; the multiplication is given by composition: `(f * g) x = f (g x)`. * `circle_deg1_lift.translation_number`: translation number of `f : circle_deg1_lift`. ## Main statements We prove the following properties of `circle_deg1_lift.translation_number`. * `circle_deg1_lift.translation_number_eq_of_dist_bounded`: if the distance between `(f^n) 0` and `(g^n) 0` is bounded from above uniformly in `n : ℕ`, then `f` and `g` have equal translation numbers. * `circle_deg1_lift.translation_number_eq_of_semiconj_by`: if two `circle_deg1_lift` maps `f`, `g` are semiconjugate by a `circle_deg1_lift` map, then `τ f = τ g`. * `circle_deg1_lift.translation_number_units_inv`: if `f` is an invertible `circle_deg1_lift` map (equivalently, `f` is a lift of an orientation-preserving circle homeomorphism), then the translation number of `f⁻¹` is the negative of the translation number of `f`. * `circle_deg1_lift.translation_number_mul_of_commute`: if `f` and `g` commute, then `τ (f * g) = τ f + τ g`. * `circle_deg1_lift.translation_number_eq_rat_iff`: the translation number of `f` is equal to a rational number `m / n` if and only if `(f^n) x = x + m` for some `x`. * `circle_deg1_lift.semiconj_of_bijective_of_translation_number_eq`: if `f` and `g` are two bijective `circle_deg1_lift` maps and their translation numbers are equal, then these maps are semiconjugate to each other. * `circle_deg1_lift.semiconj_of_group_action_of_forall_translation_number_eq`: let `f₁` and `f₂` be two actions of a group `G` on the circle by degree 1 maps (formally, `f₁` and `f₂` are two homomorphisms from `G →* circle_deg1_lift`). If the translation numbers of `f₁ g` and `f₂ g` are equal to each other for all `g : G`, then these two actions are semiconjugate by some `F : circle_deg1_lift`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. ## Notation We use a local notation `τ` for the translation number of `f : circle_deg1_lift`. ## Implementation notes We define the translation number of `f : circle_deg1_lift` to be the limit of the sequence `(f ^ (2 ^ n)) 0 / (2 ^ n)`, then prove that `((f ^ n) x - x) / n` tends to this number for any `x`. This way it is much easier to prove that the limit exists and basic properties of the limit. We define translation number for a wider class of maps `f : ℝ → ℝ` instead of lifts of orientation preserving circle homeomorphisms for two reasons: * non-strictly monotone circle self-maps with discontinuities naturally appear as Poincaré maps for some flows on the two-torus (e.g., one can take a constant flow and glue in a few Cherry cells); * definition and some basic properties still work for this class. ## References * [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes] ## TODO Here are some short-term goals. * Introduce a structure or a typeclass for lifts of circle homeomorphisms. We use `units circle_deg1_lift` for now, but it's better to have a dedicated type (or a typeclass?). * Prove that the `semiconj_by` relation on circle homeomorphisms is an equivalence relation. * Introduce `conditionally_complete_lattice` structure, use it in the proof of `circle_deg1_lift.semiconj_of_group_action_of_forall_translation_number_eq`. * Prove that the orbits of the irrational rotation are dense in the circle. Deduce that a homeomorphism with an irrational rotation is semiconjugate to the corresponding irrational translation by a continuous `circle_deg1_lift`. ## Tags circle homeomorphism, rotation number -/ open filter set function (hiding commute) int open_locale topological_space classical /-! ### Definition and monoid structure -/ /-- A lift of a monotone degree one map `S¹ → S¹`. -/ structure circle_deg1_lift : Type := (to_fun : ℝ → ℝ) (monotone' : monotone to_fun) (map_add_one' : ∀ x, to_fun (x + 1) = to_fun x + 1) namespace circle_deg1_lift instance : has_coe_to_fun circle_deg1_lift (λ _, ℝ → ℝ) := ⟨circle_deg1_lift.to_fun⟩ @[simp] lemma coe_mk (f h₁ h₂) : ⇑(mk f h₁ h₂) = f := rfl variables (f g : circle_deg1_lift) protected lemma monotone : monotone f := f.monotone' @[mono] lemma mono {x y} (h : x ≤ y) : f x ≤ f y := f.monotone h lemma strict_mono_iff_injective : strict_mono f ↔ injective f := f.monotone.strict_mono_iff_injective @[simp] lemma map_add_one : ∀ x, f (x + 1) = f x + 1 := f.map_add_one' @[simp] lemma map_one_add (x : ℝ) : f (1 + x) = 1 + f x := by rw [add_comm, map_add_one, add_comm] theorem coe_inj : ∀ ⦃f g : circle_deg1_lift ⦄, (f : ℝ → ℝ) = g → f = g := assume ⟨f, fm, fd⟩ ⟨g, gm, gd⟩ h, by congr; exact h @[ext] theorem ext ⦃f g : circle_deg1_lift ⦄ (h : ∀ x, f x = g x) : f = g := coe_inj $ funext h theorem ext_iff {f g : circle_deg1_lift} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ instance : monoid circle_deg1_lift := { mul := λ f g, { to_fun := f ∘ g, monotone' := f.monotone.comp g.monotone, map_add_one' := λ x, by simp [map_add_one] }, one := ⟨id, monotone_id, λ _, rfl⟩, mul_one := λ f, coe_inj $ function.comp.right_id f, one_mul := λ f, coe_inj $ function.comp.left_id f, mul_assoc := λ f₁ f₂ f₃, coe_inj rfl } instance : inhabited circle_deg1_lift := ⟨1⟩ @[simp] lemma coe_mul : ⇑(f * g) = f ∘ g := rfl lemma mul_apply (x) : (f * g) x = f (g x) := rfl @[simp] lemma coe_one : ⇑(1 : circle_deg1_lift) = id := rfl instance units_has_coe_to_fun : has_coe_to_fun (units circle_deg1_lift) (λ _, ℝ → ℝ) := ⟨λ f, ⇑(f : circle_deg1_lift)⟩ @[simp, norm_cast] lemma units_coe (f : units circle_deg1_lift) : ⇑(f : circle_deg1_lift) = f := rfl @[simp] lemma units_inv_apply_apply (f : units circle_deg1_lift) (x : ℝ) : (f⁻¹ : units circle_deg1_lift) (f x) = x := by simp only [← units_coe, ← mul_apply, f.inv_mul, coe_one, id] @[simp] lemma units_apply_inv_apply (f : units circle_deg1_lift) (x : ℝ) : f ((f⁻¹ : units circle_deg1_lift) x) = x := by simp only [← units_coe, ← mul_apply, f.mul_inv, coe_one, id] /-- If a lift of a circle map is bijective, then it is an order automorphism of the line. -/ def to_order_iso : units circle_deg1_lift →* ℝ ≃o ℝ := { to_fun := λ f, { to_fun := f, inv_fun := ⇑(f⁻¹), left_inv := units_inv_apply_apply f, right_inv := units_apply_inv_apply f, map_rel_iff' := λ x y, ⟨λ h, by simpa using mono ↑(f⁻¹) h, mono f⟩ }, map_one' := rfl, map_mul' := λ f g, rfl } @[simp] lemma coe_to_order_iso (f : units circle_deg1_lift) : ⇑(to_order_iso f) = f := rfl @[simp] lemma coe_to_order_iso_symm (f : units circle_deg1_lift) : ⇑(to_order_iso f).symm = (f⁻¹ : units circle_deg1_lift) := rfl @[simp] lemma coe_to_order_iso_inv (f : units circle_deg1_lift) : ⇑(to_order_iso f)⁻¹ = (f⁻¹ : units circle_deg1_lift) := rfl lemma is_unit_iff_bijective {f : circle_deg1_lift} : is_unit f ↔ bijective f := ⟨λ ⟨u, h⟩, h ▸ (to_order_iso u).bijective, λ h, units.is_unit { val := f, inv := { to_fun := (equiv.of_bijective f h).symm, monotone' := λ x y hxy, (f.strict_mono_iff_injective.2 h.1).le_iff_le.1 (by simp only [equiv.of_bijective_apply_symm_apply f h, hxy]), map_add_one' := λ x, h.1 $ by simp only [equiv.of_bijective_apply_symm_apply f, f.map_add_one] }, val_inv := ext $ equiv.of_bijective_apply_symm_apply f h, inv_val := ext $ equiv.of_bijective_symm_apply_apply f h }⟩ lemma coe_pow : ∀ n : ℕ, ⇑(f^n) = (f^[n]) | 0 := rfl | (n+1) := by {ext x, simp [coe_pow n, pow_succ'] } lemma semiconj_by_iff_semiconj {f g₁ g₂ : circle_deg1_lift} : semiconj_by f g₁ g₂ ↔ semiconj f g₁ g₂ := ext_iff lemma commute_iff_commute {f g : circle_deg1_lift} : commute f g ↔ function.commute f g := ext_iff /-! ### Translate by a constant -/ /-- The map `y ↦ x + y` as a `circle_deg1_lift`. More precisely, we define a homomorphism from `multiplicative ℝ` to `units circle_deg1_lift`, so the translation by `x` is `translation (multiplicative.of_add x)`. -/ def translate : multiplicative ℝ →* units circle_deg1_lift := by refine (units.map _).comp to_units.to_monoid_hom; exact { to_fun := λ x, ⟨λ y, x.to_add + y, λ y₁ y₂ h, add_le_add_left h _, λ y, (add_assoc _ _ _).symm⟩, map_one' := ext $ zero_add, map_mul' := λ x y, ext $ add_assoc _ _ } @[simp] lemma translate_apply (x y : ℝ) : translate (multiplicative.of_add x) y = x + y := rfl @[simp] lemma translate_inv_apply (x y : ℝ) : (translate $ multiplicative.of_add x)⁻¹ y = -x + y := rfl @[simp] lemma translate_gpow (x : ℝ) (n : ℤ) : (translate (multiplicative.of_add x))^n = translate (multiplicative.of_add $ ↑n * x) := by simp only [← gsmul_eq_mul, of_add_gsmul, monoid_hom.map_gpow] @[simp] lemma translate_pow (x : ℝ) (n : ℕ) : (translate (multiplicative.of_add x))^n = translate (multiplicative.of_add $ ↑n * x) := translate_gpow x n @[simp] lemma translate_iterate (x : ℝ) (n : ℕ) : (translate (multiplicative.of_add x))^[n] = translate (multiplicative.of_add $ ↑n * x) := by rw [← units_coe, ← coe_pow, ← units.coe_pow, translate_pow, units_coe] /-! ### Commutativity with integer translations In this section we prove that `f` commutes with translations by an integer number. First we formulate these statements (for a natural or an integer number, addition on the left or on the right, addition or subtraction) using `function.commute`, then reformulate as `simp` lemmas `map_int_add` etc. -/ lemma commute_nat_add (n : ℕ) : function.commute f ((+) n) := by simpa only [nsmul_one, add_left_iterate] using function.commute.iterate_right f.map_one_add n lemma commute_add_nat (n : ℕ) : function.commute f (λ x, x + n) := by simp only [add_comm _ (n:ℝ), f.commute_nat_add n] lemma commute_sub_nat (n : ℕ) : function.commute f (λ x, x - n) := by simpa only [sub_eq_add_neg] using (f.commute_add_nat n).inverses_right (equiv.add_right _).right_inv (equiv.add_right _).left_inv lemma commute_add_int : ∀ n : ℤ, function.commute f (λ x, x + n) | (n:ℕ) := f.commute_add_nat n | -[1+n] := by simpa only [sub_eq_add_neg] using f.commute_sub_nat (n + 1) lemma commute_int_add (n : ℤ) : function.commute f ((+) n) := by simpa only [add_comm _ (n:ℝ)] using f.commute_add_int n lemma commute_sub_int (n : ℤ) : function.commute f (λ x, x - n) := by simpa only [sub_eq_add_neg] using (f.commute_add_int n).inverses_right (equiv.add_right _).right_inv (equiv.add_right _).left_inv @[simp] lemma map_int_add (m : ℤ) (x : ℝ) : f (m + x) = m + f x := f.commute_int_add m x @[simp] lemma map_add_int (x : ℝ) (m : ℤ) : f (x + m) = f x + m := f.commute_add_int m x @[simp] lemma map_sub_int (x : ℝ) (n : ℤ) : f (x - n) = f x - n := f.commute_sub_int n x @[simp] lemma map_add_nat (x : ℝ) (n : ℕ) : f (x + n) = f x + n := f.map_add_int x n @[simp] lemma map_nat_add (n : ℕ) (x : ℝ) : f (n + x) = n + f x := f.map_int_add n x @[simp] lemma map_sub_nat (x : ℝ) (n : ℕ) : f (x - n) = f x - n := f.map_sub_int x n lemma map_int_of_map_zero (n : ℤ) : f n = f 0 + n := by rw [← f.map_add_int, zero_add] @[simp] lemma map_fract_sub_fract_eq (x : ℝ) : f (fract x) - fract x = f x - x := by rw [int.fract, f.map_sub_int, sub_sub_sub_cancel_right] /-! ### Pointwise order on circle maps -/ /-- Monotone circle maps form a lattice with respect to the pointwise order -/ noncomputable instance : lattice circle_deg1_lift := { sup := λ f g, { to_fun := λ x, max (f x) (g x), monotone' := λ x y h, max_le_max (f.mono h) (g.mono h), -- TODO: generalize to `monotone.max` map_add_one' := λ x, by simp [max_add_add_right] }, le := λ f g, ∀ x, f x ≤ g x, le_refl := λ f x, le_refl (f x), le_trans := λ f₁ f₂ f₃ h₁₂ h₂₃ x, le_trans (h₁₂ x) (h₂₃ x), le_antisymm := λ f₁ f₂ h₁₂ h₂₁, ext $ λ x, le_antisymm (h₁₂ x) (h₂₁ x), le_sup_left := λ f g x, le_max_left (f x) (g x), le_sup_right := λ f g x, le_max_right (f x) (g x), sup_le := λ f₁ f₂ f₃ h₁ h₂ x, max_le (h₁ x) (h₂ x), inf := λ f g, { to_fun := λ x, min (f x) (g x), monotone' := λ x y h, min_le_min (f.mono h) (g.mono h), map_add_one' := λ x, by simp [min_add_add_right] }, inf_le_left := λ f g x, min_le_left (f x) (g x), inf_le_right := λ f g x, min_le_right (f x) (g x), le_inf := λ f₁ f₂ f₃ h₂ h₃ x, le_min (h₂ x) (h₃ x) } @[simp] lemma sup_apply (x : ℝ) : (f ⊔ g) x = max (f x) (g x) := rfl @[simp] lemma inf_apply (x : ℝ) : (f ⊓ g) x = min (f x) (g x) := rfl lemma iterate_monotone (n : ℕ) : monotone (λ f : circle_deg1_lift, f^[n]) := λ f g h, f.monotone.iterate_le_of_le h _ lemma iterate_mono {f g : circle_deg1_lift} (h : f ≤ g) (n : ℕ) : f^[n] ≤ (g^[n]) := iterate_monotone n h lemma pow_mono {f g : circle_deg1_lift} (h : f ≤ g) (n : ℕ) : f^n ≤ g^n := λ x, by simp only [coe_pow, iterate_mono h n x] lemma pow_monotone (n : ℕ) : monotone (λ f : circle_deg1_lift, f^n) := λ f g h, pow_mono h n /-! ### Estimates on `(f * g) 0` We prove the estimates `f 0 + ⌊g 0⌋ ≤ f (g 0) ≤ f 0 + ⌈g 0⌉` and some corollaries with added/removed floors and ceils. We also prove that for two semiconjugate maps `g₁`, `g₂`, the distance between `g₁ 0` and `g₂ 0` is less than two. -/ lemma map_le_of_map_zero (x : ℝ) : f x ≤ f 0 + ⌈x⌉ := calc f x ≤ f ⌈x⌉ : f.monotone $ le_ceil _ ... = f 0 + ⌈x⌉ : f.map_int_of_map_zero _ lemma map_map_zero_le : f (g 0) ≤ f 0 + ⌈g 0⌉ := f.map_le_of_map_zero (g 0) lemma floor_map_map_zero_le : ⌊f (g 0)⌋ ≤ ⌊f 0⌋ + ⌈g 0⌉ := calc ⌊f (g 0)⌋ ≤ ⌊f 0 + ⌈g 0⌉⌋ : floor_mono $ f.map_map_zero_le g ... = ⌊f 0⌋ + ⌈g 0⌉ : floor_add_int _ _ lemma ceil_map_map_zero_le : ⌈f (g 0)⌉ ≤ ⌈f 0⌉ + ⌈g 0⌉ := calc ⌈f (g 0)⌉ ≤ ⌈f 0 + ⌈g 0⌉⌉ : ceil_mono $ f.map_map_zero_le g ... = ⌈f 0⌉ + ⌈g 0⌉ : ceil_add_int _ _ lemma map_map_zero_lt : f (g 0) < f 0 + g 0 + 1 := calc f (g 0) ≤ f 0 + ⌈g 0⌉ : f.map_map_zero_le g ... < f 0 + (g 0 + 1) : add_lt_add_left (ceil_lt_add_one _) _ ... = f 0 + g 0 + 1 : (add_assoc _ _ _).symm lemma le_map_of_map_zero (x : ℝ) : f 0 + ⌊x⌋ ≤ f x := calc f 0 + ⌊x⌋ = f ⌊x⌋ : (f.map_int_of_map_zero _).symm ... ≤ f x : f.monotone $ floor_le _ lemma le_map_map_zero : f 0 + ⌊g 0⌋ ≤ f (g 0) := f.le_map_of_map_zero (g 0) lemma le_floor_map_map_zero : ⌊f 0⌋ + ⌊g 0⌋ ≤ ⌊f (g 0)⌋ := calc ⌊f 0⌋ + ⌊g 0⌋ = ⌊f 0 + ⌊g 0⌋⌋ : (floor_add_int _ _).symm ... ≤ ⌊f (g 0)⌋ : floor_mono $ f.le_map_map_zero g lemma le_ceil_map_map_zero : ⌈f 0⌉ + ⌊g 0⌋ ≤ ⌈(f * g) 0⌉ := calc ⌈f 0⌉ + ⌊g 0⌋ = ⌈f 0 + ⌊g 0⌋⌉ : (ceil_add_int _ _).symm ... ≤ ⌈f (g 0)⌉ : ceil_mono $ f.le_map_map_zero g lemma lt_map_map_zero : f 0 + g 0 - 1 < f (g 0) := calc f 0 + g 0 - 1 = f 0 + (g 0 - 1) : add_sub_assoc _ _ _ ... < f 0 + ⌊g 0⌋ : add_lt_add_left (sub_one_lt_floor _) _ ... ≤ f (g 0) : f.le_map_map_zero g lemma dist_map_map_zero_lt : dist (f 0 + g 0) (f (g 0)) < 1 := begin rw [dist_comm, real.dist_eq, abs_lt, lt_sub_iff_add_lt', sub_lt_iff_lt_add', ← sub_eq_add_neg], exact ⟨f.lt_map_map_zero g, f.map_map_zero_lt g⟩ end lemma dist_map_zero_lt_of_semiconj {f g₁ g₂ : circle_deg1_lift} (h : function.semiconj f g₁ g₂) : dist (g₁ 0) (g₂ 0) < 2 := calc dist (g₁ 0) (g₂ 0) ≤ dist (g₁ 0) (f (g₁ 0) - f 0) + dist _ (g₂ 0) : dist_triangle _ _ _ ... = dist (f 0 + g₁ 0) (f (g₁ 0)) + dist (g₂ 0 + f 0) (g₂ (f 0)) : by simp only [h.eq, real.dist_eq, sub_sub, add_comm (f 0), sub_sub_assoc_swap, abs_sub_comm (g₂ (f 0))] ... < 2 : add_lt_add (f.dist_map_map_zero_lt g₁) (g₂.dist_map_map_zero_lt f) lemma dist_map_zero_lt_of_semiconj_by {f g₁ g₂ : circle_deg1_lift} (h : semiconj_by f g₁ g₂) : dist (g₁ 0) (g₂ 0) < 2 := dist_map_zero_lt_of_semiconj $ semiconj_by_iff_semiconj.1 h /-! ### Limits at infinities and continuity -/ protected lemma tendsto_at_bot : tendsto f at_bot at_bot := tendsto_at_bot_mono f.map_le_of_map_zero $ tendsto_at_bot_add_const_left _ _ $ tendsto_at_bot_mono (λ x, (ceil_lt_add_one x).le) $ tendsto_at_bot_add_const_right _ _ tendsto_id protected lemma tendsto_at_top : tendsto f at_top at_top := tendsto_at_top_mono f.le_map_of_map_zero $ tendsto_at_top_add_const_left _ _ $ tendsto_at_top_mono (λ x, (sub_one_lt_floor x).le) $ by simpa [sub_eq_add_neg] using tendsto_at_top_add_const_right _ _ tendsto_id lemma continuous_iff_surjective : continuous f ↔ function.surjective f := ⟨λ h, h.surjective f.tendsto_at_top f.tendsto_at_bot, f.monotone.continuous_of_surjective⟩ /-! ### Estimates on `(f^n) x` If we know that `f x` is `≤`/`<`/`≥`/`>`/`=` to `x + m`, then we have a similar estimate on `f^[n] x` and `x + n * m`. For `≤`, `≥`, and `=` we formulate both `of` (implication) and `iff` versions because implications work for `n = 0`. For `<` and `>` we formulate only `iff` versions. -/ lemma iterate_le_of_map_le_add_int {x : ℝ} {m : ℤ} (h : f x ≤ x + m) (n : ℕ) : f^[n] x ≤ x + n * m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_le_of_map_le f.monotone (monotone_id.add_const m) h n lemma le_iterate_of_add_int_le_map {x : ℝ} {m : ℤ} (h : x + m ≤ f x) (n : ℕ) : x + n * m ≤ (f^[n]) x := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).symm.iterate_le_of_map_le (monotone_id.add_const m) f.monotone h n lemma iterate_eq_of_map_eq_add_int {x : ℝ} {m : ℤ} (h : f x = x + m) (n : ℕ) : f^[n] x = x + n * m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_eq_of_map_eq n h lemma iterate_pos_le_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x ≤ x + n * m ↔ f x ≤ x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_le_iff_map_le f.monotone (strict_mono_id.add_const m) hn lemma iterate_pos_lt_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x < x + n * m ↔ f x < x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_lt_iff_map_lt f.monotone (strict_mono_id.add_const m) hn lemma iterate_pos_eq_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x = x + n * m ↔ f x = x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_eq_iff_map_eq f.monotone (strict_mono_id.add_const m) hn lemma le_iterate_pos_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : x + n * m ≤ (f^[n]) x ↔ x + m ≤ f x := by simpa only [not_lt] using not_congr (f.iterate_pos_lt_iff hn) lemma lt_iterate_pos_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : x + n * m < (f^[n]) x ↔ x + m < f x := by simpa only [not_le] using not_congr (f.iterate_pos_le_iff hn) lemma mul_floor_map_zero_le_floor_iterate_zero (n : ℕ) : ↑n * ⌊f 0⌋ ≤ ⌊(f^[n] 0)⌋ := begin rw [le_floor, int.cast_mul, int.cast_coe_nat, ← zero_add ((n : ℝ) * _)], apply le_iterate_of_add_int_le_map, simp [floor_le] end /-! ### Definition of translation number -/ noncomputable theory /-- An auxiliary sequence used to define the translation number. -/ def transnum_aux_seq (n : ℕ) : ℝ := (f^(2^n)) 0 / 2^n /-- The translation number of a `circle_deg1_lift`, $τ(f)=\lim_{n→∞}\frac{f^n(x)-x}{n}$. We use an auxiliary sequence `\frac{f^{2^n}(0)}{2^n}` to define `τ(f)` because some proofs are simpler this way. -/ def translation_number : ℝ := lim at_top f.transnum_aux_seq -- TODO: choose two different symbols for `circle_deg1_lift.translation_number` and the future -- `circle_mono_homeo.rotation_number`, then make them `localized notation`s local notation `τ` := translation_number lemma transnum_aux_seq_def : f.transnum_aux_seq = λ n : ℕ, (f^(2^n)) 0 / 2^n := rfl lemma translation_number_eq_of_tendsto_aux {τ' : ℝ} (h : tendsto f.transnum_aux_seq at_top (𝓝 τ')) : τ f = τ' := h.lim_eq lemma translation_number_eq_of_tendsto₀ {τ' : ℝ} (h : tendsto (λ n:ℕ, f^[n] 0 / n) at_top (𝓝 τ')) : τ f = τ' := f.translation_number_eq_of_tendsto_aux $ by simpa [(∘), transnum_aux_seq_def, coe_pow] using h.comp (nat.tendsto_pow_at_top_at_top_of_one_lt one_lt_two) lemma translation_number_eq_of_tendsto₀' {τ' : ℝ} (h : tendsto (λ n:ℕ, f^[n + 1] 0 / (n + 1)) at_top (𝓝 τ')) : τ f = τ' := f.translation_number_eq_of_tendsto₀ $ (tendsto_add_at_top_iff_nat 1).1 h lemma transnum_aux_seq_zero : f.transnum_aux_seq 0 = f 0 := by simp [transnum_aux_seq] lemma transnum_aux_seq_dist_lt (n : ℕ) : dist (f.transnum_aux_seq n) (f.transnum_aux_seq (n+1)) < (1 / 2) / (2^n) := begin have : 0 < (2^(n+1):ℝ) := pow_pos zero_lt_two _, rw [div_div_eq_div_mul, ← pow_succ, ← abs_of_pos this], replace := abs_pos.2 (ne_of_gt this), convert (div_lt_div_right this).2 ((f^(2^n)).dist_map_map_zero_lt (f^(2^n))), simp_rw [transnum_aux_seq, real.dist_eq], rw [← abs_div, sub_div, pow_succ', pow_succ, ← two_mul, mul_div_mul_left _ _ (@two_ne_zero ℝ _ _), pow_mul, sq, mul_apply] end lemma tendsto_translation_number_aux : tendsto f.transnum_aux_seq at_top (𝓝 $ τ f) := (cauchy_seq_of_le_geometric_two 1 (λ n, le_of_lt $ f.transnum_aux_seq_dist_lt n)).tendsto_lim lemma dist_map_zero_translation_number_le : dist (f 0) (τ f) ≤ 1 := f.transnum_aux_seq_zero ▸ dist_le_of_le_geometric_two_of_tendsto₀ 1 (λ n, le_of_lt $ f.transnum_aux_seq_dist_lt n) f.tendsto_translation_number_aux lemma tendsto_translation_number_of_dist_bounded_aux (x : ℕ → ℝ) (C : ℝ) (H : ∀ n : ℕ, dist ((f^n) 0) (x n) ≤ C) : tendsto (λ n : ℕ, x (2^n) / (2^n)) at_top (𝓝 $ τ f) := begin refine f.tendsto_translation_number_aux.congr_dist (squeeze_zero (λ _, dist_nonneg) _ _), { exact λ n, C / 2^n }, { intro n, have : 0 < (2^n:ℝ) := pow_pos zero_lt_two _, convert (div_le_div_right this).2 (H (2^n)), rw [transnum_aux_seq, real.dist_eq, ← sub_div, abs_div, abs_of_pos this, real.dist_eq] }, { exact mul_zero C ▸ tendsto_const_nhds.mul (tendsto_inv_at_top_zero.comp $ tendsto_pow_at_top_at_top_of_one_lt one_lt_two) } end lemma translation_number_eq_of_dist_bounded {f g : circle_deg1_lift} (C : ℝ) (H : ∀ n : ℕ, dist ((f^n) 0) ((g^n) 0) ≤ C) : τ f = τ g := eq.symm $ g.translation_number_eq_of_tendsto_aux $ f.tendsto_translation_number_of_dist_bounded_aux _ C H @[simp] lemma translation_number_one : τ 1 = 0 := translation_number_eq_of_tendsto₀ _ $ by simp [tendsto_const_nhds] lemma translation_number_eq_of_semiconj_by {f g₁ g₂ : circle_deg1_lift} (H : semiconj_by f g₁ g₂) : τ g₁ = τ g₂ := translation_number_eq_of_dist_bounded 2 $ λ n, le_of_lt $ dist_map_zero_lt_of_semiconj_by $ H.pow_right n lemma translation_number_eq_of_semiconj {f g₁ g₂ : circle_deg1_lift} (H : function.semiconj f g₁ g₂) : τ g₁ = τ g₂ := translation_number_eq_of_semiconj_by $ semiconj_by_iff_semiconj.2 H lemma translation_number_mul_of_commute {f g : circle_deg1_lift} (h : commute f g) : τ (f * g) = τ f + τ g := begin have : tendsto (λ n : ℕ, ((λ k, (f^k) 0 + (g^k) 0) (2^n)) / (2^n)) at_top (𝓝 $ τ f + τ g) := ((f.tendsto_translation_number_aux.add g.tendsto_translation_number_aux).congr $ λ n, (add_div ((f^(2^n)) 0) ((g^(2^n)) 0) ((2:ℝ)^n)).symm), refine tendsto_nhds_unique ((f * g).tendsto_translation_number_of_dist_bounded_aux _ 1 (λ n, _)) this, rw [h.mul_pow, dist_comm], exact le_of_lt ((f^n).dist_map_map_zero_lt (g^n)) end @[simp] lemma translation_number_units_inv (f : units circle_deg1_lift) : τ ↑(f⁻¹) = -τ f := eq_neg_iff_add_eq_zero.2 $ by simp [← translation_number_mul_of_commute (commute.refl _).units_inv_left] @[simp] lemma translation_number_pow : ∀ n : ℕ, τ (f^n) = n * τ f | 0 := by simp | (n+1) := by rw [pow_succ', translation_number_mul_of_commute (commute.pow_self f n), translation_number_pow n, nat.cast_add_one, add_mul, one_mul] @[simp] lemma translation_number_gpow (f : units circle_deg1_lift) : ∀ n : ℤ, τ (f ^ n : units _) = n * τ f | (n : ℕ) := by simp [translation_number_pow f n] | -[1+n] := by { simp, ring } @[simp] lemma translation_number_conj_eq (f : units circle_deg1_lift) (g : circle_deg1_lift) : τ (↑f * g * ↑(f⁻¹)) = τ g := (translation_number_eq_of_semiconj_by (f.mk_semiconj_by g)).symm @[simp] lemma translation_number_conj_eq' (f : units circle_deg1_lift) (g : circle_deg1_lift) : τ (↑(f⁻¹) * g * f) = τ g := translation_number_conj_eq f⁻¹ g lemma dist_pow_map_zero_mul_translation_number_le (n:ℕ) : dist ((f^n) 0) (n * f.translation_number) ≤ 1 := f.translation_number_pow n ▸ (f^n).dist_map_zero_translation_number_le lemma tendsto_translation_number₀' : tendsto (λ n:ℕ, (f^(n+1)) 0 / (n+1)) at_top (𝓝 $ τ f) := begin refine (tendsto_iff_dist_tendsto_zero.2 $ squeeze_zero (λ _, dist_nonneg) (λ n, _) ((tendsto_const_div_at_top_nhds_0_nat 1).comp (tendsto_add_at_top_nat 1))), dsimp, have : (0:ℝ) < n + 1 := n.cast_add_one_pos, rw [real.dist_eq, div_sub' _ _ _ (ne_of_gt this), abs_div, ← real.dist_eq, abs_of_pos this, div_le_div_right this, ← nat.cast_add_one], apply dist_pow_map_zero_mul_translation_number_le end lemma tendsto_translation_number₀ : tendsto (λ n:ℕ, ((f^n) 0) / n) at_top (𝓝 $ τ f) := (tendsto_add_at_top_iff_nat 1).1 f.tendsto_translation_number₀' /-- For any `x : ℝ` the sequence $\frac{f^n(x)-x}{n}$ tends to the translation number of `f`. In particular, this limit does not depend on `x`. -/ lemma tendsto_translation_number (x : ℝ) : tendsto (λ n:ℕ, ((f^n) x - x) / n) at_top (𝓝 $ τ f) := begin rw [← translation_number_conj_eq' (translate $ multiplicative.of_add x)], convert tendsto_translation_number₀ _, ext n, simp [sub_eq_neg_add, units.conj_pow'] end lemma tendsto_translation_number' (x : ℝ) : tendsto (λ n:ℕ, ((f^(n+1)) x - x) / (n+1)) at_top (𝓝 $ τ f) := (tendsto_add_at_top_iff_nat 1).2 (f.tendsto_translation_number x) lemma translation_number_mono : monotone τ := λ f g h, le_of_tendsto_of_tendsto' f.tendsto_translation_number₀ g.tendsto_translation_number₀ $ λ n, div_le_div_of_le_of_nonneg (pow_mono h n 0) n.cast_nonneg lemma translation_number_translate (x : ℝ) : τ (translate $ multiplicative.of_add x) = x := translation_number_eq_of_tendsto₀' _ $ by simp [nat.cast_add_one_ne_zero, mul_div_cancel_left, tendsto_const_nhds] lemma translation_number_le_of_le_add {z : ℝ} (hz : ∀ x, f x ≤ x + z) : τ f ≤ z := translation_number_translate z ▸ translation_number_mono (λ x, trans_rel_left _ (hz x) (add_comm _ _)) lemma le_translation_number_of_add_le {z : ℝ} (hz : ∀ x, x + z ≤ f x) : z ≤ τ f := translation_number_translate z ▸ translation_number_mono (λ x, trans_rel_right _ (add_comm _ _) (hz x)) lemma translation_number_le_of_le_add_int {x : ℝ} {m : ℤ} (h : f x ≤ x + m) : τ f ≤ m := le_of_tendsto' (f.tendsto_translation_number' x) $ λ n, (div_le_iff' (n.cast_add_one_pos : (0 : ℝ) < _)).mpr $ sub_le_iff_le_add'.2 $ (coe_pow f (n + 1)).symm ▸ f.iterate_le_of_map_le_add_int h (n + 1) lemma translation_number_le_of_le_add_nat {x : ℝ} {m : ℕ} (h : f x ≤ x + m) : τ f ≤ m := @translation_number_le_of_le_add_int f x m h lemma le_translation_number_of_add_int_le {x : ℝ} {m : ℤ} (h : x + m ≤ f x) : ↑m ≤ τ f := ge_of_tendsto' (f.tendsto_translation_number' x) $ λ n, (le_div_iff (n.cast_add_one_pos : (0 : ℝ) < _)).mpr $ le_sub_iff_add_le'.2 $ by simp only [coe_pow, mul_comm (m:ℝ), ← nat.cast_add_one, f.le_iterate_of_add_int_le_map h] lemma le_translation_number_of_add_nat_le {x : ℝ} {m : ℕ} (h : x + m ≤ f x) : ↑m ≤ τ f := @le_translation_number_of_add_int_le f x m h /-- If `f x - x` is an integer number `m` for some point `x`, then `τ f = m`. On the circle this means that a map with a fixed point has rotation number zero. -/ lemma translation_number_of_eq_add_int {x : ℝ} {m : ℤ} (h : f x = x + m) : τ f = m := le_antisymm (translation_number_le_of_le_add_int f $ le_of_eq h) (le_translation_number_of_add_int_le f $ le_of_eq h.symm) lemma floor_sub_le_translation_number (x : ℝ) : ↑⌊f x - x⌋ ≤ τ f := le_translation_number_of_add_int_le f $ le_sub_iff_add_le'.1 (floor_le $ f x - x) lemma translation_number_le_ceil_sub (x : ℝ) : τ f ≤ ⌈f x - x⌉ := translation_number_le_of_le_add_int f $ sub_le_iff_le_add'.1 (le_ceil $ f x - x) lemma map_lt_of_translation_number_lt_int {n : ℤ} (h : τ f < n) (x : ℝ) : f x < x + n := not_le.1 $ mt f.le_translation_number_of_add_int_le $ not_le.2 h lemma map_lt_of_translation_number_lt_nat {n : ℕ} (h : τ f < n) (x : ℝ) : f x < x + n := @map_lt_of_translation_number_lt_int f n h x lemma map_lt_add_floor_translation_number_add_one (x : ℝ) : f x < x + ⌊τ f⌋ + 1 := begin rw [add_assoc], norm_cast, refine map_lt_of_translation_number_lt_int _ _ _, push_cast, exact lt_floor_add_one _ end lemma map_lt_add_translation_number_add_one (x : ℝ) : f x < x + τ f + 1 := calc f x < x + ⌊τ f⌋ + 1 : f.map_lt_add_floor_translation_number_add_one x ... ≤ x + τ f + 1 : by { mono*, exact floor_le (τ f) } lemma lt_map_of_int_lt_translation_number {n : ℤ} (h : ↑n < τ f) (x : ℝ) : x + n < f x := not_le.1 $ mt f.translation_number_le_of_le_add_int $ not_le.2 h lemma lt_map_of_nat_lt_translation_number {n : ℕ} (h : ↑n < τ f) (x : ℝ) : x + n < f x := @lt_map_of_int_lt_translation_number f n h x /-- If `f^n x - x`, `n > 0`, is an integer number `m` for some point `x`, then `τ f = m / n`. On the circle this means that a map with a periodic orbit has a rational rotation number. -/ lemma translation_number_of_map_pow_eq_add_int {x : ℝ} {n : ℕ} {m : ℤ} (h : (f^n) x = x + m) (hn : 0 < n) : τ f = m / n := begin have := (f^n).translation_number_of_eq_add_int h, rwa [translation_number_pow, mul_comm, ← eq_div_iff] at this, exact nat.cast_ne_zero.2 (ne_of_gt hn) end /-- If a predicate depends only on `f x - x` and holds for all `0 ≤ x ≤ 1`, then it holds for all `x`. -/ lemma forall_map_sub_of_Icc (P : ℝ → Prop) (h : ∀ x ∈ Icc (0:ℝ) 1, P (f x - x)) (x : ℝ) : P (f x - x) := f.map_fract_sub_fract_eq x ▸ h _ ⟨fract_nonneg _, le_of_lt (fract_lt_one _)⟩ lemma translation_number_lt_of_forall_lt_add (hf : continuous f) {z : ℝ} (hz : ∀ x, f x < x + z) : τ f < z := begin obtain ⟨x, xmem, hx⟩ : ∃ x ∈ Icc (0:ℝ) 1, ∀ y ∈ Icc (0:ℝ) 1, f y - y ≤ f x - x, from is_compact_Icc.exists_forall_ge (nonempty_Icc.2 zero_le_one) (hf.sub continuous_id).continuous_on, refine lt_of_le_of_lt _ (sub_lt_iff_lt_add'.2 $ hz x), apply translation_number_le_of_le_add, simp only [← sub_le_iff_le_add'], exact f.forall_map_sub_of_Icc (λ a, a ≤ f x - x) hx end lemma lt_translation_number_of_forall_add_lt (hf : continuous f) {z : ℝ} (hz : ∀ x, x + z < f x) : z < τ f := begin obtain ⟨x, xmem, hx⟩ : ∃ x ∈ Icc (0:ℝ) 1, ∀ y ∈ Icc (0:ℝ) 1, f x - x ≤ f y - y, from is_compact_Icc.exists_forall_le (nonempty_Icc.2 zero_le_one) (hf.sub continuous_id).continuous_on, refine lt_of_lt_of_le (lt_sub_iff_add_lt'.2 $ hz x) _, apply le_translation_number_of_add_le, simp only [← le_sub_iff_add_le'], exact f.forall_map_sub_of_Icc _ hx end /-- If `f` is a continuous monotone map `ℝ → ℝ`, `f (x + 1) = f x + 1`, then there exists `x` such that `f x = x + τ f`. -/ lemma exists_eq_add_translation_number (hf : continuous f) : ∃ x, f x = x + τ f := begin obtain ⟨a, ha⟩ : ∃ x, f x ≤ x + f.translation_number, { by_contradiction H, push_neg at H, exact lt_irrefl _ (f.lt_translation_number_of_forall_add_lt hf H) }, obtain ⟨b, hb⟩ : ∃ x, x + τ f ≤ f x, { by_contradiction H, push_neg at H, exact lt_irrefl _ (f.translation_number_lt_of_forall_lt_add hf H) }, exact intermediate_value_univ₂ hf (continuous_id.add continuous_const) ha hb end lemma translation_number_eq_int_iff (hf : continuous f) {m : ℤ} : τ f = m ↔ ∃ x, f x = x + m := begin refine ⟨λ h, h ▸ f.exists_eq_add_translation_number hf, _⟩, rintros ⟨x, hx⟩, exact f.translation_number_of_eq_add_int hx end lemma continuous_pow (hf : continuous f) (n : ℕ) : continuous ⇑(f^n : circle_deg1_lift) := by { rw coe_pow, exact hf.iterate n } lemma translation_number_eq_rat_iff (hf : continuous f) {m : ℤ} {n : ℕ} (hn : 0 < n) : τ f = m / n ↔ ∃ x, (f^n) x = x + m := begin rw [eq_div_iff, mul_comm, ← translation_number_pow]; [skip, exact ne_of_gt (nat.cast_pos.2 hn)], exact (f^n).translation_number_eq_int_iff (f.continuous_pow hf n) end /-- Consider two actions `f₁ f₂ : G →* circle_deg1_lift` of a group on the real line by lifts of orientation preserving circle homeomorphisms. Suppose that for each `g : G` the homeomorphisms `f₁ g` and `f₂ g` have equal rotation numbers. Then there exists `F : circle_deg1_lift` such that `F * f₁ g = f₂ g * F` for all `g : G`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. -/ lemma semiconj_of_group_action_of_forall_translation_number_eq {G : Type*} [group G] (f₁ f₂ : G →* circle_deg1_lift) (h : ∀ g, τ (f₁ g) = τ (f₂ g)) : ∃ F : circle_deg1_lift, ∀ g, semiconj F (f₁ g) (f₂ g) := begin -- Equality of translation number guarantees that for each `x` -- the set `{f₂ g⁻¹ (f₁ g x) | g : G}` is bounded above. have : ∀ x, bdd_above (range $ λ g, f₂ g⁻¹ (f₁ g x)), { refine λ x, ⟨x + 2, _⟩, rintro _ ⟨g, rfl⟩, have : τ (f₂ g⁻¹) = -τ (f₂ g), by rw [← monoid_hom.coe_to_hom_units, monoid_hom.map_inv, translation_number_units_inv, monoid_hom.coe_to_hom_units], calc f₂ g⁻¹ (f₁ g x) ≤ f₂ g⁻¹ (x + τ (f₁ g) + 1) : mono _ (map_lt_add_translation_number_add_one _ _).le ... = f₂ g⁻¹ (x + τ (f₂ g)) + 1 : by rw [h, map_add_one] ... ≤ x + τ (f₂ g) + τ (f₂ g⁻¹) + 1 + 1 : by { mono, exact (map_lt_add_translation_number_add_one _ _).le } ... = x + 2 : by simp [this, bit0, add_assoc] }, -- We have a theorem about actions by `order_iso`, so we introduce auxiliary maps -- to `ℝ ≃o ℝ`. set F₁ := to_order_iso.comp f₁.to_hom_units, set F₂ := to_order_iso.comp f₂.to_hom_units, have hF₁ : ∀ g, ⇑(F₁ g) = f₁ g := λ _, rfl, have hF₂ : ∀ g, ⇑(F₂ g) = f₂ g := λ _, rfl, simp only [← hF₁, ← hF₂], -- Now we apply `cSup_div_semiconj` and go back to `f₁` and `f₂`. refine ⟨⟨_, λ x y hxy, _, λ x, _⟩, cSup_div_semiconj F₂ F₁ (λ x, _)⟩; simp only [hF₁, hF₂, ← monoid_hom.map_inv, coe_mk], { refine csupr_le_csupr (this y) (λ g, _), exact mono _ (mono _ hxy) }, { simp only [map_add_one], exact (map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) (monotone_id.add_const (1 : ℝ)) (this x)).symm }, { exact this x } end /-- If two lifts of circle homeomorphisms have the same translation number, then they are semiconjugate by a `circle_deg1_lift`. This version uses arguments `f₁ f₂ : units circle_deg1_lift` to assume that `f₁` and `f₂` are homeomorphisms. -/ lemma units_semiconj_of_translation_number_eq {f₁ f₂ : units circle_deg1_lift} (h : τ f₁ = τ f₂) : ∃ F : circle_deg1_lift, semiconj F f₁ f₂ := begin have : ∀ n : multiplicative ℤ, τ ((units.coe_hom _).comp (gpowers_hom _ f₁) n) = τ ((units.coe_hom _).comp (gpowers_hom _ f₂) n), { intro n, simp [h] }, exact (semiconj_of_group_action_of_forall_translation_number_eq _ _ this).imp (λ F hF, hF (multiplicative.of_add 1)) end /-- If two lifts of circle homeomorphisms have the same translation number, then they are semiconjugate by a `circle_deg1_lift`. This version uses assumptions `is_unit f₁` and `is_unit f₂` to assume that `f₁` and `f₂` are homeomorphisms. -/ lemma semiconj_of_is_unit_of_translation_number_eq {f₁ f₂ : circle_deg1_lift} (h₁ : is_unit f₁) (h₂ : is_unit f₂) (h : τ f₁ = τ f₂) : ∃ F : circle_deg1_lift, semiconj F f₁ f₂ := by { rcases ⟨h₁, h₂⟩ with ⟨⟨f₁, rfl⟩, ⟨f₂, rfl⟩⟩, exact units_semiconj_of_translation_number_eq h } /-- If two lifts of circle homeomorphisms have the same translation number, then they are semiconjugate by a `circle_deg1_lift`. This version uses assumptions `bijective f₁` and `bijective f₂` to assume that `f₁` and `f₂` are homeomorphisms. -/ lemma semiconj_of_bijective_of_translation_number_eq {f₁ f₂ : circle_deg1_lift} (h₁ : bijective f₁) (h₂ : bijective f₂) (h : τ f₁ = τ f₂) : ∃ F : circle_deg1_lift, semiconj F f₁ f₂ := semiconj_of_is_unit_of_translation_number_eq (is_unit_iff_bijective.2 h₁) (is_unit_iff_bijective.2 h₂) h end circle_deg1_lift
fbb3e5e3efa683ff1639d5321f99e1dfd4aec1cb
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Tactic/Calc.lean
a62cb28c3fac0fa38e308bdcba2ead3b8976c469
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,369
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Calc import Lean.Elab.Tactic.ElabTerm namespace Lean.Elab.Tactic open Meta /-- Elaborator for the `calc` tactic mode variant. -/ @[builtin_tactic calcTactic] def evalCalc : Tactic := fun stx => withMainContext do let steps : TSyntax ``calcSteps := ⟨stx[1]⟩ let (val, mvarIds) ← withCollectingNewGoalsFrom (tagSuffix := `calc) do let target ← getMainTarget let tag ← getMainTag runTermElab do let mut val ← Term.elabCalcSteps steps let mut valType ← inferType val unless (← isDefEq valType target) do let rec throwFailed := throwError "'calc' tactic failed, has type{indentExpr valType}\nbut it is expected to have type{indentExpr target}" let some (_, _, rhs) ← Term.getCalcRelation? valType | throwFailed let some (r, _, rhs') ← Term.getCalcRelation? target | throwFailed let lastStep := mkApp2 r rhs rhs' let lastStepGoal ← mkFreshExprSyntheticOpaqueMVar lastStep (tag := tag ++ `calc.step) (val, valType) ← Term.mkCalcTrans val valType lastStepGoal lastStep unless (← isDefEq valType target) do throwFailed return val (← getMainGoal).assign val replaceMainGoal mvarIds
5b15463f62e33461af87109dc2eeb0dd52744537
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/whnfProj.lean
24699be17a4e0ac4a4f5f648062a375dea029064
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
527
lean
import Lean def h (x : Nat) := x def f (x : Nat) := x + 1 def g (x : Nat) := (x, x+1).fst open Lean open Lean.Meta def tst (declName : Name) : MetaM Unit := do let c ← getConstInfo declName lambdaTelescope c.value! fun _ b => do trace[Meta.debug]! "1. {b}" trace[Meta.debug]! "2. {← withReducible <| whnf b}" trace[Meta.debug]! "3. {← withReducibleAndInstances <| whnf b}" trace[Meta.debug]! "4. {← withDefault <| whnf b}" pure () set_option trace.Meta.debug true #eval tst `f #eval tst `g
f6f391602dc428fe71ca455e45f0d579336a4ade
4727251e0cd73359b15b664c3170e5d754078599
/src/geometry/manifold/whitney_embedding.lean
fe0a799e38d9f6c3b6cb63c1c8b451337488ea78
[ "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
6,327
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import geometry.manifold.diffeomorph import geometry.manifold.instances.real import geometry.manifold.partition_of_unity /-! # Whitney embedding theorem In this file we prove a version of the Whitney embedding theorem: for any compact real manifold `M`, for sufficiently large `n` there exists a smooth embedding `M → ℝ^n`. ## TODO * Prove the weak Whitney embedding theorem: any `σ`-compact smooth `m`-dimensional manifold can be embedded into `ℝ^(2m+1)`. This requires a version of Sard's theorem: for a locally Lipschitz continuous map `f : ℝ^m → ℝ^n`, `m < n`, the range has Hausdorff dimension at most `m`, hence it has measure zero. ## Tags partition of unity, smooth bump function, whitney theorem -/ universes uι uE uH uM variables {ι : Type uι} {E : Type uE} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {H : Type uH} [topological_space H] {I : model_with_corners ℝ E H} {M : Type uM} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] open function filter finite_dimensional set open_locale topological_space manifold classical filter big_operators noncomputable theory namespace smooth_bump_covering /-! ### Whitney embedding theorem In this section we prove a version of the Whitney embedding theorem: for any compact real manifold `M`, for sufficiently large `n` there exists a smooth embedding `M → ℝ^n`. -/ variables [t2_space M] [fintype ι] {s : set M} (f : smooth_bump_covering ι I M s) /-- Smooth embedding of `M` into `(E × ℝ) ^ ι`. -/ def embedding_pi_tangent : C^∞⟮I, M; 𝓘(ℝ, ι → (E × ℝ)), ι → (E × ℝ)⟯ := { to_fun := λ x i, (f i x • ext_chart_at I (f.c i) x, f i x), cont_mdiff_to_fun := cont_mdiff_pi_space.2 $ λ i, ((f i).smooth_smul cont_mdiff_on_ext_chart_at).prod_mk_space ((f i).smooth) } local attribute [simp] lemma embedding_pi_tangent_coe : ⇑f.embedding_pi_tangent = λ x i, (f i x • ext_chart_at I (f.c i) x, f i x) := rfl lemma embedding_pi_tangent_inj_on : inj_on f.embedding_pi_tangent s := begin intros x hx y hy h, simp only [embedding_pi_tangent_coe, funext_iff] at h, obtain ⟨h₁, h₂⟩ := prod.mk.inj_iff.1 (h (f.ind x hx)), rw [f.apply_ind x hx] at h₂, rw [← h₂, f.apply_ind x hx, one_smul, one_smul] at h₁, have := f.mem_ext_chart_at_source_of_eq_one h₂.symm, exact (ext_chart_at I (f.c _)).inj_on (f.mem_ext_chart_at_ind_source x hx) this h₁ end lemma embedding_pi_tangent_injective (f : smooth_bump_covering ι I M) : injective f.embedding_pi_tangent := injective_iff_inj_on_univ.2 f.embedding_pi_tangent_inj_on lemma comp_embedding_pi_tangent_mfderiv (x : M) (hx : x ∈ s) : ((continuous_linear_map.fst ℝ E ℝ).comp (@continuous_linear_map.proj ℝ _ ι (λ _, E × ℝ) _ _ (λ _, infer_instance) (f.ind x hx))).comp (mfderiv I 𝓘(ℝ, ι → (E × ℝ)) f.embedding_pi_tangent x) = mfderiv I I (chart_at H (f.c (f.ind x hx))) x := begin set L := ((continuous_linear_map.fst ℝ E ℝ).comp (@continuous_linear_map.proj ℝ _ ι (λ _, E × ℝ) _ _ (λ _, infer_instance) (f.ind x hx))), have := L.has_mfderiv_at.comp x f.embedding_pi_tangent.mdifferentiable_at.has_mfderiv_at, convert has_mfderiv_at_unique this _, refine (has_mfderiv_at_ext_chart_at I (f.mem_chart_at_ind_source x hx)).congr_of_eventually_eq _, refine (f.eventually_eq_one x hx).mono (λ y hy, _), simp only [embedding_pi_tangent_coe, continuous_linear_map.coe_comp', (∘), continuous_linear_map.coe_fst', continuous_linear_map.proj_apply], rw [hy, pi.one_apply, one_smul] end lemma embedding_pi_tangent_ker_mfderiv (x : M) (hx : x ∈ s) : (mfderiv I 𝓘(ℝ, ι → (E × ℝ)) f.embedding_pi_tangent x).ker = ⊥ := begin apply bot_unique, rw [← (mdifferentiable_chart I (f.c (f.ind x hx))).ker_mfderiv_eq_bot (f.mem_chart_at_ind_source x hx), ← comp_embedding_pi_tangent_mfderiv], exact linear_map.ker_le_ker_comp _ _ end lemma embedding_pi_tangent_injective_mfderiv (x : M) (hx : x ∈ s) : injective (mfderiv I 𝓘(ℝ, ι → (E × ℝ)) f.embedding_pi_tangent x) := linear_map.ker_eq_bot.1 (f.embedding_pi_tangent_ker_mfderiv x hx) /-- Baby version of the Whitney weak embedding theorem: if `M` admits a finite covering by supports of bump functions, then for some `n` it can be immersed into the `n`-dimensional Euclidean space. -/ lemma exists_immersion_euclidean (f : smooth_bump_covering ι I M) : ∃ (n : ℕ) (e : M → euclidean_space ℝ (fin n)), smooth I (𝓡 n) e ∧ injective e ∧ ∀ x : M, injective (mfderiv I (𝓡 n) e x) := begin set F := euclidean_space ℝ (fin $ finrank ℝ (ι → (E × ℝ))), letI : is_noetherian ℝ (E × ℝ) := is_noetherian.iff_fg.2 infer_instance, letI : finite_dimensional ℝ (ι → E × ℝ) := is_noetherian.iff_fg.1 infer_instance, set eEF : (ι → (E × ℝ)) ≃L[ℝ] F := continuous_linear_equiv.of_finrank_eq finrank_euclidean_space_fin.symm, refine ⟨_, eEF ∘ f.embedding_pi_tangent, eEF.to_diffeomorph.smooth.comp f.embedding_pi_tangent.smooth, eEF.injective.comp f.embedding_pi_tangent_injective, λ x, _⟩, rw [mfderiv_comp _ eEF.differentiable_at.mdifferentiable_at f.embedding_pi_tangent.mdifferentiable_at, eEF.mfderiv_eq], exact eEF.injective.comp (f.embedding_pi_tangent_injective_mfderiv _ trivial) end end smooth_bump_covering /-- Baby version of the Whitney weak embedding theorem: if `M` admits a finite covering by supports of bump functions, then for some `n` it can be embedded into the `n`-dimensional Euclidean space. -/ lemma exists_embedding_euclidean_of_compact [t2_space M] [compact_space M] : ∃ (n : ℕ) (e : M → euclidean_space ℝ (fin n)), smooth I (𝓡 n) e ∧ closed_embedding e ∧ ∀ x : M, injective (mfderiv I (𝓡 n) e x) := begin rcases smooth_bump_covering.exists_is_subordinate I is_closed_univ (λ (x : M) _, univ_mem) with ⟨ι, f, -⟩, haveI := f.fintype, rcases f.exists_immersion_euclidean with ⟨n, e, hsmooth, hinj, hinj_mfderiv⟩, exact ⟨n, e, hsmooth, hsmooth.continuous.closed_embedding hinj, hinj_mfderiv⟩ end
c2663b8c5612b50edd386368ad40f346599077d3
02fbe05a45fda5abde7583464416db4366eedfbf
/library/init/logic.lean
32d695768432a76a46bcfd062bbec7bb7a61d4ef
[ "Apache-2.0" ]
permissive
jasonrute/lean
cc12807e11f9ac6b01b8951a8bfb9c2eb35a0154
4be962c167ca442a0ec5e84472d7ff9f5302788f
refs/heads/master
1,672,036,664,637
1,601,642,826,000
1,601,642,826,000
260,777,966
0
0
Apache-2.0
1,588,454,819,000
1,588,454,818,000
null
UTF-8
Lean
false
false
38,525
lean
/- Copyright (c) 2014 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 -/ prelude import init.core universes u v w @[simp] lemma opt_param_eq (α : Sort u) (default : α) : opt_param α default = α := rfl @[inline] def id {α : Sort u} (a : α) : α := a def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := λ b a, f a b /- implication -/ def implies (a b : Prop) := a → b /-- Implication `→` is transitive. If `P → Q` and `Q → R` then `P → R`. -/ @[trans] lemma implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := assume hp, h₂ (h₁ hp) def trivial : true := ⟨⟩ /-- We can't have `a` and `¬a`, that would be absurd!-/ @[inline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : ¬a) : b := false.rec b (h₂ h₁) lemma not.intro {a : Prop} (h : a → false) : ¬ a := h /-- Modus tollens. If an implication is true, then so is its contrapositive. -/ lemma mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := assume ha : a, h₂ (h₁ ha) /- not -/ lemma not_false : ¬false := id def non_contradictory (a : Prop) : Prop := ¬¬a lemma non_contradictory_intro {a : Prop} (ha : a) : ¬¬a := assume hna : ¬a, absurd ha hna /- false -/ @[inline] def false.elim {C : Sort u} (h : false) : C := false.rec C h /- eq -/ -- proof irrelevance is built in lemma proof_irrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl @[simp] lemma id.def {α : Sort u} (a : α) : id a = a := rfl @[inline] def eq.mp {α β : Sort u} : (α = β) → α → β := eq.rec_on @[inline] def eq.mpr {α β : Sort u} : (α = β) → β → α := λ h₁ h₂, eq.rec_on (eq.symm h₁) h₂ @[elab_as_eliminator] lemma eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) : p a → p b := eq.subst (eq.symm h₁) lemma congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := eq.subst h₁ (eq.subst h₂ rfl) lemma congr_fun {α : Sort u} {β : α → Sort v} {f g : Π x, β x} (h : f = g) (a : α) : f a = g a := eq.subst h (eq.refl (f a)) lemma congr_arg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) : a₁ = a₂ → f a₁ = f a₂ := congr rfl lemma trans_rel_left {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂ ▸ h₁ lemma trans_rel_right {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c := h₁.symm ▸ h₂ lemma of_eq_true {p : Prop} (h : p = true) : p := h.symm ▸ trivial lemma not_of_eq_false {p : Prop} (h : p = false) : ¬p := assume hp, h ▸ hp @[inline] def cast {α β : Sort u} (h : α = β) (a : α) : β := eq.rec a h lemma cast_proof_irrel {α β : Sort u} (h₁ h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl lemma cast_eq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl /- ne -/ @[reducible] def ne {α : Sort u} (a b : α) := ¬(a = b) notation a ≠ b := ne a b @[simp] lemma ne.def {α : Sort u} (a b : α) : a ≠ b = ¬ (a = b) := rfl namespace ne variable {α : Sort u} variables {a b : α} lemma intro (h : a = b → false) : a ≠ b := h lemma elim (h : a ≠ b) : a = b → false := h lemma irrefl (h : a ≠ a) : false := h rfl lemma symm (h : a ≠ b) : b ≠ a := assume (h₁ : b = a), h (h₁.symm) end ne lemma false_of_ne {α : Sort u} {a : α} : a ≠ a → false := ne.irrefl section variables {p : Prop} lemma ne_false_of_self : p → p ≠ false := assume (hp : p) (heq : p = false), heq ▸ hp lemma ne_true_of_not : ¬p → p ≠ true := assume (hnp : ¬p) (heq : p = true), (heq ▸ hnp) trivial lemma true_ne_false : ¬true = false := ne_false_of_self trivial end attribute [refl] heq.refl section variables {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ} lemma heq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a == b) : p a → p b := eq.rec_on (eq_of_heq h₁) lemma heq.subst {p : ∀ T : Sort u, T → Prop} : a == b → p α a → p β b := heq.rec_on @[symm] lemma heq.symm (h : a == b) : b == a := heq.rec_on h (heq.refl a) lemma heq_of_eq (h : a = a') : a == a' := eq.subst h (heq.refl a) @[trans] lemma heq.trans (h₁ : a == b) (h₂ : b == c) : a == c := heq.subst h₂ h₁ @[trans] lemma heq_of_heq_of_eq (h₁ : a == b) (h₂ : b = b') : a == b' := heq.trans h₁ (heq_of_eq h₂) @[trans] lemma heq_of_eq_of_heq (h₁ : a = a') (h₂ : a' == b) : a == b := heq.trans (heq_of_eq h₁) h₂ def type_eq_of_heq (h : a == b) : α = β := heq.rec_on h (eq.refl α) end lemma eq_rec_heq {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} (h : a = a') (p : φ a), (eq.rec_on h p : φ a') == p | a _ rfl p := heq.refl p lemma heq_of_eq_rec_left {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a = a') (h₂ : (eq.rec_on e p₁ : φ a') = p₂), p₁ == p₂ | a _ p₁ p₂ rfl h := eq.rec_on h (heq.refl p₁) lemma heq_of_eq_rec_right {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a' = a) (h₂ : p₁ = eq.rec_on e p₂), p₁ == p₂ | a _ p₁ p₂ rfl h := have p₁ = p₂, from h, this ▸ heq.refl p₁ lemma of_heq_true {a : Prop} (h : a == true) : a := of_eq_true (eq_of_heq h) lemma eq_rec_compose : ∀ {α β φ : Sort u} (p₁ : β = φ) (p₂ : α = β) (a : α), (eq.rec_on p₁ (eq.rec_on p₂ a : β) : φ) = eq.rec_on (eq.trans p₂ p₁) a | α _ _ rfl rfl a := rfl lemma cast_heq : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a == a | α _ rfl a := heq.refl a /- and -/ notation a /\ b := and a b notation a ∧ b := and a b variables {a b c d : Prop} lemma and.elim (h₁ : a ∧ b) (h₂ : a → b → c) : c := and.rec h₂ h₁ lemma and.swap : a ∧ b → b ∧ a := assume ⟨ha, hb⟩, ⟨hb, ha⟩ def and.symm := @and.swap /- or -/ notation a \/ b := or a b notation a ∨ b := or a b namespace or lemma elim (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → c) : c := or.rec h₂ h₃ h₁ end or lemma non_contradictory_em (a : Prop) : ¬¬(a ∨ ¬a) := assume not_em : ¬(a ∨ ¬a), have neg_a : ¬a, from assume pos_a : a, absurd (or.inl pos_a) not_em, absurd (or.inr neg_a) not_em def not_not_em := non_contradictory_em lemma or.swap : a ∨ b → b ∨ a := or.rec or.inr or.inl def or.symm := @or.swap /- xor -/ def xor (a b : Prop) := (a ∧ ¬ b) ∨ (b ∧ ¬ a) /- iff -/ /-- `iff P Q`, with notation `P ↔ Q`, is the proposition asserting that `P` and `Q` are equivalent, that is, have the same truth value. -/ structure iff (a b : Prop) : Prop := intro :: (mp : a → b) (mpr : b → a) notation a <-> b := iff a b notation a ↔ b := iff a b lemma iff.elim : ((a → b) → (b → a) → c) → (a ↔ b) → c := iff.rec attribute [recursor 5] iff.elim lemma iff.elim_left : (a ↔ b) → a → b := iff.mp lemma iff.elim_right : (a ↔ b) → b → a := iff.mpr lemma iff_iff_implies_and_implies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) := iff.intro (λ h, and.intro h.mp h.mpr) (λ h, iff.intro h.left h.right) @[refl] lemma iff.refl (a : Prop) : a ↔ a := iff.intro (assume h, h) (assume h, h) lemma iff.rfl {a : Prop} : a ↔ a := iff.refl a @[trans] lemma iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := iff.intro (assume ha, iff.mp h₂ (iff.mp h₁ ha)) (assume hc, iff.mpr h₁ (iff.mpr h₂ hc)) @[symm] lemma iff.symm (h : a ↔ b) : b ↔ a := iff.intro (iff.elim_right h) (iff.elim_left h) lemma iff.comm : (a ↔ b) ↔ (b ↔ a) := iff.intro iff.symm iff.symm lemma eq.to_iff {a b : Prop} (h : a = b) : a ↔ b := eq.rec_on h iff.rfl lemma neq_of_not_iff {a b : Prop} : ¬(a ↔ b) → a ≠ b := λ h₁ h₂, have a ↔ b, from eq.subst h₂ (iff.refl a), absurd this h₁ lemma not_iff_not_of_iff (h₁ : a ↔ b) : ¬a ↔ ¬b := iff.intro (assume (hna : ¬ a) (hb : b), hna (iff.elim_right h₁ hb)) (assume (hnb : ¬ b) (ha : a), hnb (iff.elim_left h₁ ha)) lemma of_iff_true (h : a ↔ true) : a := iff.mp (iff.symm h) trivial lemma not_of_iff_false : (a ↔ false) → ¬a := iff.mp lemma iff_true_intro (h : a) : a ↔ true := iff.intro (λ hl, trivial) (λ hr, h) lemma iff_false_intro (h : ¬a) : a ↔ false := iff.intro h (false.rec a) lemma not_non_contradictory_iff_absurd (a : Prop) : ¬¬¬a ↔ ¬a := iff.intro (λ (hl : ¬¬¬a) (ha : a), hl (non_contradictory_intro ha)) absurd def not_not_not_iff := not_non_contradictory_iff_absurd lemma imp_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a → b) ↔ (c → d) := iff.intro (λ hab hc, iff.mp h₂ (hab (iff.mpr h₁ hc))) (λ hcd ha, iff.mpr h₂ (hcd (iff.mp h₁ ha))) lemma imp_congr_ctx (h₁ : a ↔ c) (h₂ : c → (b ↔ d)) : (a → b) ↔ (c → d) := iff.intro (λ hab hc, have ha : a, from iff.mpr h₁ hc, have hb : b, from hab ha, iff.mp (h₂ hc) hb) (λ hcd ha, have hc : c, from iff.mp h₁ ha, have hd : d, from hcd hc, iff.mpr (h₂ hc) hd) lemma imp_congr_right (h : a → (b ↔ c)) : (a → b) ↔ (a → c) := iff.intro (assume hab ha, iff.elim_left (h ha) (hab ha)) (assume hab ha, iff.elim_right (h ha) (hab ha)) lemma not_not_intro (ha : a) : ¬¬a := assume hna : ¬a, hna ha lemma not_of_not_not_not (h : ¬¬¬a) : ¬a := λ ha, absurd (not_not_intro ha) h @[simp] lemma not_true : (¬ true) ↔ false := iff_false_intro (not_not_intro trivial) def not_true_iff := not_true @[simp] lemma not_false_iff : (¬ false) ↔ true := iff_true_intro not_false @[congr] lemma not_congr (h : a ↔ b) : ¬a ↔ ¬b := iff.intro (λ h₁ h₂, h₁ (iff.mpr h h₂)) (λ h₁ h₂, h₁ (iff.mp h h₂)) @[simp] lemma ne_self_iff_false {α : Sort u} (a : α) : (not (a = a)) ↔ false := iff.intro false_of_ne false.elim @[simp] lemma eq_self_iff_true {α : Sort u} (a : α) : (a = a) ↔ true := iff_true_intro rfl @[simp] lemma heq_self_iff_true {α : Sort u} (a : α) : (a == a) ↔ true := iff_true_intro (heq.refl a) @[simp] lemma iff_not_self (a : Prop) : (a ↔ ¬a) ↔ false := iff_false_intro (λ h, have h' : ¬a, from (λ ha, (iff.mp h ha) ha), h' (iff.mpr h h')) @[simp] lemma not_iff_self (a : Prop) : (¬a ↔ a) ↔ false := iff_false_intro (λ h, have h' : ¬a, from (λ ha, (iff.mpr h ha) ha), h' (iff.mp h h')) @[simp] lemma true_iff_false : (true ↔ false) ↔ false := iff_false_intro (λ h, iff.mp h trivial) @[simp] lemma false_iff_true : (false ↔ true) ↔ false := iff_false_intro (λ h, iff.mpr h trivial) lemma false_of_true_iff_false : (true ↔ false) → false := assume h, iff.mp h trivial lemma false_of_true_eq_false : (true = false) → false := assume h, h ▸ trivial lemma true_eq_false_of_false : false → (true = false) := false.elim lemma eq_comm {α : Sort u} {a b : α} : a = b ↔ b = a := ⟨eq.symm, eq.symm⟩ /- and simp rules -/ lemma and.imp (hac : a → c) (hbd : b → d) : a ∧ b → c ∧ d := assume ⟨ha, hb⟩, ⟨hac ha, hbd hb⟩ def and_implies := @and.imp @[congr] lemma and_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∧ b) ↔ (c ∧ d) := iff.intro (and.imp (iff.mp h₁) (iff.mp h₂)) (and.imp (iff.mpr h₁) (iff.mpr h₂)) lemma and_congr_right (h : a → (b ↔ c)) : (a ∧ b) ↔ (a ∧ c) := iff.intro (assume ⟨ha, hb⟩, ⟨ha, iff.elim_left (h ha) hb⟩) (assume ⟨ha, hc⟩, ⟨ha, iff.elim_right (h ha) hc⟩) lemma and.comm : a ∧ b ↔ b ∧ a := iff.intro and.swap and.swap lemma and_comm (a b : Prop) : a ∧ b ↔ b ∧ a := and.comm lemma and.assoc : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := iff.intro (assume ⟨⟨ha, hb⟩, hc⟩, ⟨ha, ⟨hb, hc⟩⟩) (assume ⟨ha, ⟨hb, hc⟩⟩, ⟨⟨ha, hb⟩, hc⟩) lemma and_assoc (a b : Prop) : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := and.assoc lemma and.left_comm : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) := iff.trans (iff.symm and.assoc) (iff.trans (and_congr and.comm (iff.refl c)) and.assoc) lemma and_iff_left {a b : Prop} (hb : b) : (a ∧ b) ↔ a := iff.intro and.left (λ ha, ⟨ha, hb⟩) lemma and_iff_right {a b : Prop} (ha : a) : (a ∧ b) ↔ b := iff.intro and.right (and.intro ha) @[simp] lemma and_true (a : Prop) : a ∧ true ↔ a := and_iff_left trivial @[simp] lemma true_and (a : Prop) : true ∧ a ↔ a := and_iff_right trivial @[simp] lemma and_false (a : Prop) : a ∧ false ↔ false := iff_false_intro and.right @[simp] lemma false_and (a : Prop) : false ∧ a ↔ false := iff_false_intro and.left @[simp] lemma not_and_self (a : Prop) : (¬a ∧ a) ↔ false := iff_false_intro (λ h, and.elim h (λ h₁ h₂, absurd h₂ h₁)) @[simp] lemma and_not_self (a : Prop) : (a ∧ ¬a) ↔ false := iff_false_intro (assume ⟨h₁, h₂⟩, absurd h₁ h₂) @[simp] lemma and_self (a : Prop) : a ∧ a ↔ a := iff.intro and.left (assume h, ⟨h, h⟩) /- or simp rules -/ lemma or.imp (h₂ : a → c) (h₃ : b → d) : a ∨ b → c ∨ d := or.rec (λ h, or.inl (h₂ h)) (λ h, or.inr (h₃ h)) lemma or.imp_left (h : a → b) : a ∨ c → b ∨ c := or.imp h id lemma or.imp_right (h : a → b) : c ∨ a → c ∨ b := or.imp id h @[congr] lemma or_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∨ b) ↔ (c ∨ d) := iff.intro (or.imp (iff.mp h₁) (iff.mp h₂)) (or.imp (iff.mpr h₁) (iff.mpr h₂)) lemma or.comm : a ∨ b ↔ b ∨ a := iff.intro or.swap or.swap lemma or_comm (a b : Prop) : a ∨ b ↔ b ∨ a := or.comm lemma or.assoc : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := iff.intro (or.rec (or.imp_right or.inl) (λ h, or.inr (or.inr h))) (or.rec (λ h, or.inl (or.inl h)) (or.imp_left or.inr)) lemma or_assoc (a b : Prop) : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := or.assoc lemma or.left_comm : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) := iff.trans (iff.symm or.assoc) (iff.trans (or_congr or.comm (iff.refl c)) or.assoc) theorem or_iff_right_of_imp (ha : a → b) : (a ∨ b) ↔ b := iff.intro (or.rec ha id) or.inr theorem or_iff_left_of_imp (hb : b → a) : (a ∨ b) ↔ a := iff.intro (or.rec id hb) or.inl @[simp] lemma or_true (a : Prop) : a ∨ true ↔ true := iff_true_intro (or.inr trivial) @[simp] lemma true_or (a : Prop) : true ∨ a ↔ true := iff_true_intro (or.inl trivial) @[simp] lemma or_false (a : Prop) : a ∨ false ↔ a := iff.intro (or.rec id false.elim) or.inl @[simp] lemma false_or (a : Prop) : false ∨ a ↔ a := iff.trans or.comm (or_false a) @[simp] lemma or_self (a : Prop) : a ∨ a ↔ a := iff.intro (or.rec id id) or.inl lemma not_or {a b : Prop} : ¬ a → ¬ b → ¬ (a ∨ b) | hna hnb (or.inl ha) := absurd ha hna | hna hnb (or.inr hb) := absurd hb hnb /- or resolution rulse -/ def or.resolve_left {a b : Prop} (h : a ∨ b) (na : ¬ a) : b := or.elim h (λ ha, absurd ha na) id def or.neg_resolve_left {a b : Prop} (h : ¬ a ∨ b) (ha : a) : b := or.elim h (λ na, absurd ha na) id def or.resolve_right {a b : Prop} (h : a ∨ b) (nb : ¬ b) : a := or.elim h id (λ hb, absurd hb nb) def or.neg_resolve_right {a b : Prop} (h : a ∨ ¬ b) (hb : b) : a := or.elim h id (λ nb, absurd hb nb) /- iff simp rules -/ @[simp] lemma iff_true (a : Prop) : (a ↔ true) ↔ a := iff.intro (assume h, iff.mpr h trivial) iff_true_intro @[simp] lemma true_iff (a : Prop) : (true ↔ a) ↔ a := iff.trans iff.comm (iff_true a) @[simp] lemma iff_false (a : Prop) : (a ↔ false) ↔ ¬ a := iff.intro iff.mp iff_false_intro @[simp] lemma false_iff (a : Prop) : (false ↔ a) ↔ ¬ a := iff.trans iff.comm (iff_false a) @[simp] lemma iff_self (a : Prop) : (a ↔ a) ↔ true := iff_true_intro iff.rfl @[congr] lemma iff_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ↔ b) ↔ (c ↔ d) := (iff_iff_implies_and_implies a b).trans ((and_congr (imp_congr h₁ h₂) (imp_congr h₂ h₁)).trans (iff_iff_implies_and_implies c d).symm) /- implies simp rule -/ @[simp] lemma implies_true_iff (α : Sort u) : (α → true) ↔ true := iff.intro (λ h, trivial) (λ ha h, trivial) @[simp] lemma false_implies_iff (a : Prop) : (false → a) ↔ true := iff.intro (λ h, trivial) (λ ha h, false.elim h) @[simp] theorem true_implies_iff (α : Prop) : (true → α) ↔ α := iff.intro (λ h, h trivial) (λ h h', h) /- exists -/ inductive Exists {α : Sort u} (p : α → Prop) : Prop | intro (w : α) (h : p w) : Exists attribute [intro] Exists.intro @[pattern] def exists.intro := @Exists.intro notation `exists` binders `, ` r:(scoped P, Exists P) := r notation `∃` binders `, ` r:(scoped P, Exists P) := r lemma exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : ∃ x, p x) (h₂ : ∀ (a : α), p a → b) : b := Exists.rec h₂ h₁ /- exists unique -/ def exists_unique {α : Sort u} (p : α → Prop) := ∃ x, p x ∧ ∀ y, p y → y = x notation `∃!` binders `, ` r:(scoped P, exists_unique P) := r @[intro] lemma exists_unique.intro {α : Sort u} {p : α → Prop} (w : α) (h₁ : p w) (h₂ : ∀ y, p y → y = w) : ∃! x, p x := exists.intro w ⟨h₁, h₂⟩ attribute [recursor 4] lemma exists_unique.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₂ : ∃! x, p x) (h₁ : ∀ x, p x → (∀ y, p y → y = x) → b) : b := exists.elim h₂ (λ w hw, h₁ w (and.left hw) (and.right hw)) lemma exists_unique_of_exists_of_unique {α : Type u} {p : α → Prop} (hex : ∃ x, p x) (hunique : ∀ y₁ y₂, p y₁ → p y₂ → y₁ = y₂) : ∃! x, p x := exists.elim hex (λ x px, exists_unique.intro x px (assume y, assume : p y, hunique y x this px)) lemma exists_of_exists_unique {α : Sort u} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x := exists.elim h (λ x hx, ⟨x, and.left hx⟩) lemma unique_of_exists_unique {α : Sort u} {p : α → Prop} (h : ∃! x, p x) {y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := exists_unique.elim h (assume x, assume : p x, assume unique : ∀ y, p y → y = x, show y₁ = y₂, from eq.trans (unique _ py₁) (eq.symm (unique _ py₂))) /- exists, forall, exists unique congruences -/ @[congr] lemma forall_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a ↔ q a)) : (∀ a, p a) ↔ ∀ a, q a := iff.intro (λ p a, iff.mp (h a) (p a)) (λ q a, iff.mpr (h a) (q a)) lemma exists_imp_exists {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a → q a)) (p : ∃ a, p a) : ∃ a, q a := exists.elim p (λ a hp, ⟨a, h a hp⟩) @[congr] lemma exists_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a ↔ q a)) : (Exists p) ↔ ∃ a, q a := iff.intro (exists_imp_exists (λ a, iff.mp (h a))) (exists_imp_exists (λ a, iff.mpr (h a))) @[congr] lemma exists_unique_congr {α : Sort u} {p₁ p₂ : α → Prop} (h : ∀ x, p₁ x ↔ p₂ x) : (exists_unique p₁) ↔ (∃! x, p₂ x) := -- exists_congr (λ x, and_congr (h x) (forall_congr (λ y, imp_congr (h y) iff.rfl))) lemma forall_not_of_not_exists {α : Sort u} {p : α → Prop} : ¬(∃ x, p x) → (∀ x, ¬p x) := λ hne x hp, hne ⟨x, hp⟩ /- decidable -/ def decidable.to_bool (p : Prop) [h : decidable p] : bool := decidable.cases_on h (λ h₁, bool.ff) (λ h₂, bool.tt) export decidable (is_true is_false to_bool) @[simp] lemma to_bool_true_eq_tt (h : decidable true) : @to_bool true h = tt := decidable.cases_on h (λ h, false.elim (iff.mp not_true h)) (λ _, rfl) @[simp] lemma to_bool_false_eq_ff (h : decidable false) : @to_bool false h = ff := decidable.cases_on h (λ h, rfl) (λ h, false.elim h) instance decidable.true : decidable true := is_true trivial instance decidable.false : decidable false := is_false not_false -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[inline] def dite (c : Prop) [h : decidable c] {α : Sort u} : (c → α) → (¬ c → α) → α := λ t e, decidable.rec_on h e t /- if-then-else -/ @[inline] def ite (c : Prop) [h : decidable c] {α : Sort u} (t e : α) : α := decidable.rec_on h (λ hnc, e) (λ hc, t) namespace decidable variables {p q : Prop} def rec_on_true [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : p) (h₄ : h₁ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (λ h, false.rec _ (h h₃)) (λ h, h₄) def rec_on_false [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : ¬p) (h₄ : h₂ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (λ h, h₄) (λ h, false.rec _ (h₃ h)) def by_cases {q : Sort u} [φ : decidable p] : (p → q) → (¬p → q) → q := dite _ /-- Law of Excluded Middle. -/ lemma em (p : Prop) [decidable p] : p ∨ ¬p := by_cases or.inl or.inr lemma by_contradiction [decidable p] (h : ¬p → false) : p := if h₁ : p then h₁ else false.rec _ (h h₁) lemma of_not_not [decidable p] : ¬ ¬ p → p := λ hnn, by_contradiction (λ hn, absurd hn hnn) lemma not_not_iff (p) [decidable p] : (¬ ¬ p) ↔ p := iff.intro of_not_not not_not_intro lemma not_and_iff_or_not (p q : Prop) [d₁ : decidable p] [d₂ : decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := iff.intro (λ h, match d₁ with | is_true h₁ := match d₂ with | is_true h₂ := absurd (and.intro h₁ h₂) h | is_false h₂ := or.inr h₂ end | is_false h₁ := or.inl h₁ end) (λ h ⟨hp, hq⟩, or.elim h (λ h, h hp) (λ h, h hq)) lemma not_or_iff_and_not (p q) [d₁ : decidable p] [d₂ : decidable q] : ¬ (p ∨ q) ↔ ¬ p ∧ ¬ q := iff.intro (λ h, match d₁ with | is_true h₁ := false.elim $ h (or.inl h₁) | is_false h₁ := match d₂ with | is_true h₂ := false.elim $ h (or.inr h₂) | is_false h₂ := ⟨h₁, h₂⟩ end end) (λ ⟨np, nq⟩ h, or.elim h np nq) end decidable section variables {p q : Prop} def decidable_of_decidable_of_iff (hp : decidable p) (h : p ↔ q) : decidable q := if hp : p then is_true (iff.mp h hp) else is_false (iff.mp (not_iff_not_of_iff h) hp) def decidable_of_decidable_of_eq (hp : decidable p) (h : p = q) : decidable q := decidable_of_decidable_of_iff hp h.to_iff protected def or.by_cases [decidable p] [decidable q] {α : Sort u} (h : p ∨ q) (h₁ : p → α) (h₂ : q → α) : α := if hp : p then h₁ hp else if hq : q then h₂ hq else false.rec _ (or.elim h hp hq) end section variables {p q : Prop} instance [decidable p] [decidable q] : decidable (p ∧ q) := if hp : p then if hq : q then is_true ⟨hp, hq⟩ else is_false (assume h : p ∧ q, hq (and.right h)) else is_false (assume h : p ∧ q, hp (and.left h)) instance [decidable p] [decidable q] : decidable (p ∨ q) := if hp : p then is_true (or.inl hp) else if hq : q then is_true (or.inr hq) else is_false (or.rec hp hq) instance [decidable p] : decidable (¬p) := if hp : p then is_false (absurd hp) else is_true hp instance implies.decidable [decidable p] [decidable q] : decidable (p → q) := if hp : p then if hq : q then is_true (assume h, hq) else is_false (assume h : p → q, absurd (h hp) hq) else is_true (assume h, absurd h hp) instance [decidable p] [decidable q] : decidable (p ↔ q) := if hp : p then if hq : q then is_true ⟨λ_, hq, λ_, hp⟩ else is_false $ λh, hq (h.1 hp) else if hq : q then is_false $ λh, hp (h.2 hq) else is_true $ ⟨λh, absurd h hp, λh, absurd h hq⟩ instance [decidable p] [decidable q] : decidable (xor p q) := if hp : p then if hq : q then is_false (or.rec (λ ⟨_, h⟩, h hq : ¬(p ∧ ¬ q)) (λ ⟨_, h⟩, h hp : ¬(q ∧ ¬ p))) else is_true $ or.inl ⟨hp, hq⟩ else if hq : q then is_true $ or.inr ⟨hq, hp⟩ else is_false (or.rec (λ ⟨h, _⟩, hp h : ¬(p ∧ ¬ q)) (λ ⟨h, _⟩, hq h : ¬(q ∧ ¬ p))) instance exists_prop_decidable {p} (P : p → Prop) [Dp : decidable p] [DP : ∀ h, decidable (P h)] : decidable (∃ h, P h) := if h : p then decidable_of_decidable_of_iff (DP h) ⟨λ h2, ⟨h, h2⟩, λ⟨h', h2⟩, h2⟩ else is_false (mt (λ⟨h, _⟩, h) h) instance forall_prop_decidable {p} (P : p → Prop) [Dp : decidable p] [DP : ∀ h, decidable (P h)] : decidable (∀ h, P h) := if h : p then decidable_of_decidable_of_iff (DP h) ⟨λ h2 _, h2, λal, al h⟩ else is_true (λ h2, absurd h2 h) end instance {α : Sort u} [decidable_eq α] (a b : α) : decidable (a ≠ b) := implies.decidable lemma bool.ff_ne_tt : ff = tt → false . def is_dec_eq {α : Sort u} (p : α → α → bool) : Prop := ∀ ⦃x y : α⦄, p x y = tt → x = y def is_dec_refl {α : Sort u} (p : α → α → bool) : Prop := ∀ x, p x x = tt open decidable instance : decidable_eq bool | ff ff := is_true rfl | ff tt := is_false bool.ff_ne_tt | tt ff := is_false (ne.symm bool.ff_ne_tt) | tt tt := is_true rfl def decidable_eq_of_bool_pred {α : Sort u} {p : α → α → bool} (h₁ : is_dec_eq p) (h₂ : is_dec_refl p) : decidable_eq α := assume x y : α, if hp : p x y = tt then is_true (h₁ hp) else is_false (assume hxy : x = y, absurd (h₂ y) (@eq.rec_on _ _ (λ z, ¬p z y = tt) _ hxy hp)) lemma decidable_eq_inl_refl {α : Sort u} [h : decidable_eq α] (a : α) : h a a = is_true (eq.refl a) := match (h a a) with | (is_true e) := rfl | (is_false n) := absurd rfl n end lemma decidable_eq_inr_neg {α : Sort u} [h : decidable_eq α] {a b : α} : Π n : a ≠ b, h a b = is_false n := assume n, match (h a b) with | (is_true e) := absurd e n | (is_false n₁) := proof_irrel n n₁ ▸ eq.refl (is_false n) end /- inhabited -/ class inhabited (α : Sort u) := (default [] : α) export inhabited (default) @[inline, irreducible] def arbitrary (α : Sort u) [inhabited α] : α := default α instance prop.inhabited : inhabited Prop := ⟨true⟩ instance pi.inhabited (α : Sort u) {β : α → Sort v} [Π x, inhabited (β x)] : inhabited (Π x, β x) := ⟨λ a, default (β a)⟩ instance : inhabited bool := ⟨ff⟩ instance : inhabited true := ⟨trivial⟩ class inductive nonempty (α : Sort u) : Prop | intro (val : α) : nonempty protected def nonempty.elim {α : Sort u} {p : Prop} (h₁ : nonempty α) (h₂ : α → p) : p := nonempty.rec h₂ h₁ instance nonempty_of_inhabited {α : Sort u} [inhabited α] : nonempty α := ⟨default α⟩ lemma nonempty_of_exists {α : Sort u} {p : α → Prop} : (∃ x, p x) → nonempty α | ⟨w, h⟩ := ⟨w⟩ /- subsingleton -/ class inductive subsingleton (α : Sort u) : Prop | intro (h : ∀ a b : α, a = b) : subsingleton protected def subsingleton.elim {α : Sort u} [h : subsingleton α] : ∀ (a b : α), a = b := subsingleton.rec (λ p, p) h protected def subsingleton.helim {α β : Sort u} [h : subsingleton α] (h : α = β) : ∀ (a : α) (b : β), a == b := eq.rec_on h (λ a b : α, heq_of_eq (subsingleton.elim a b)) instance subsingleton_prop (p : Prop) : subsingleton p := ⟨λ a b, proof_irrel a b⟩ instance (p : Prop) : subsingleton (decidable p) := subsingleton.intro (λ d₁, match d₁ with | (is_true t₁) := (λ d₂, match d₂ with | (is_true t₂) := eq.rec_on (proof_irrel t₁ t₂) rfl | (is_false f₂) := absurd t₁ f₂ end) | (is_false f₁) := (λ d₂, match d₂ with | (is_true t₂) := absurd t₂ f₁ | (is_false f₂) := eq.rec_on (proof_irrel f₁ f₂) rfl end) end) protected lemma rec_subsingleton {p : Prop} [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : Π (h : p), subsingleton (h₁ h)] [h₄ : Π (h : ¬p), subsingleton (h₂ h)] : subsingleton (decidable.rec_on h h₂ h₁) := match h with | (is_true h) := h₃ h | (is_false h) := h₄ h end lemma if_pos {c : Prop} [h : decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t := match h with | (is_true hc) := rfl | (is_false hnc) := absurd hc hnc end lemma if_neg {c : Prop} [h : decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e := match h with | (is_true hc) := absurd hc hnc | (is_false hnc) := rfl end @[simp] lemma if_t_t (c : Prop) [h : decidable c] {α : Sort u} (t : α) : (ite c t t) = t := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end lemma implies_of_if_pos {c t e : Prop} [decidable c] (h : ite c t e) : c → t := assume hc, eq.rec_on (if_pos hc : ite c t e = t) h lemma implies_of_if_neg {c t e : Prop} [decidable c] (h : ite c t e) : ¬c → e := assume hnc, eq.rec_on (if_neg hnc : ite c t e = e) h lemma if_ctx_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = ite c u v := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end @[congr] lemma if_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := @if_ctx_congr α b c dec_b dec_c x y u v h_c (λ h, h_t) (λ h, h_e) @[simp] lemma if_true {α : Sort u} {h : decidable true} (t e : α) : (@ite true h α t e) = t := if_pos trivial @[simp] lemma if_false {α : Sort u} {h : decidable false} (t e : α) : (@ite false h α t e) = e := if_neg not_false lemma if_ctx_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c u v := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end @[congr] lemma if_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ ite c u v := if_ctx_congr_prop h_c (λ h, h_t) (λ h, h_e) lemma if_ctx_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) := @if_ctx_congr_prop b c x y u v dec_b (decidable_of_decidable_of_iff dec_b h_c) h_c h_t h_e @[congr] lemma if_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) := @if_ctx_simp_congr_prop b c x y u v dec_b h_c (λ h, h_t) (λ h, h_e) @[simp] lemma dif_pos {c : Prop} [h : decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : dite c t e = t hc := match h with | (is_true hc) := rfl | (is_false hnc) := absurd hc hnc end @[simp] lemma dif_neg {c : Prop} [h : decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : dite c t e = e hnc := match h with | (is_true hc) := absurd hc hnc | (is_false hnc) := rfl end @[congr] lemma dif_ctx_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite b dec_b α x y) = (@dite c dec_c α u v) := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end lemma dif_ctx_simp_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite b dec_b α x y) = (@dite c (decidable_of_decidable_of_iff dec_b h_c) α u v) := @dif_ctx_congr α b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x u y v h_c h_t h_e -- Remark: dite and ite are "defally equal" when we ignore the proofs. lemma dif_eq_if (c : Prop) [h : decidable c] {α : Sort u} (t : α) (e : α) : dite c (λ h, t) (λ h, e) = ite c t e := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end instance {c t e : Prop} [d_c : decidable c] [d_t : decidable t] [d_e : decidable e] : decidable (if c then t else e) := match d_c with | (is_true hc) := d_t | (is_false hc) := d_e end instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [d_c : decidable c] [d_t : ∀ h, decidable (t h)] [d_e : ∀ h, decidable (e h)] : decidable (if h : c then t h else e h) := match d_c with | (is_true hc) := d_t hc | (is_false hc) := d_e hc end def as_true (c : Prop) [decidable c] : Prop := if c then true else false def as_false (c : Prop) [decidable c] : Prop := if c then false else true def of_as_true {c : Prop} [h₁ : decidable c] (h₂ : as_true c) : c := match h₁, h₂ with | (is_true h_c), h₂ := h_c | (is_false h_c), h₂ := false.elim h₂ end /-- Universe lifting operation -/ structure {r s} ulift (α : Type s) : Type (max s r) := up :: (down : α) namespace ulift /- Bijection between α and ulift.{v} α -/ lemma up_down {α : Type u} : ∀ (b : ulift.{v} α), up (down b) = b | (up a) := rfl lemma down_up {α : Type u} (a : α) : down (up.{v} a) = a := rfl end ulift /-- Universe lifting operation from Sort to Type -/ structure plift (α : Sort u) : Type u := up :: (down : α) namespace plift /- Bijection between α and plift α -/ lemma up_down {α : Sort u} : ∀ (b : plift α), up (down b) = b | (up a) := rfl lemma down_up {α : Sort u} (a : α) : down (up a) = a := rfl end plift /- Equalities for rewriting let-expressions -/ lemma let_value_eq {α : Sort u} {β : Sort v} {a₁ a₂ : α} (b : α → β) : a₁ = a₂ → (let x : α := a₁ in b x) = (let x : α := a₂ in b x) := λ h, eq.rec_on h rfl lemma let_value_heq {α : Sort v} {β : α → Sort u} {a₁ a₂ : α} (b : Π x : α, β x) : a₁ = a₂ → (let x : α := a₁ in b x) == (let x : α := a₂ in b x) := λ h, eq.rec_on h (heq.refl (b a₁)) lemma let_body_eq {α : Sort v} {β : α → Sort u} (a : α) {b₁ b₂ : Π x : α, β x} : (∀ x, b₁ x = b₂ x) → (let x : α := a in b₁ x) = (let x : α := a in b₂ x) := λ h, h a lemma let_eq {α : Sort v} {β : Sort u} {a₁ a₂ : α} {b₁ b₂ : α → β} : a₁ = a₂ → (∀ x, b₁ x = b₂ x) → (let x : α := a₁ in b₁ x) = (let x : α := a₂ in b₂ x) := λ h₁ h₂, eq.rec_on h₁ (h₂ a₁) section relation variables {α : Sort u} {β : Sort v} (r : β → β → Prop) local infix `≺`:50 := r def reflexive := ∀ x, x ≺ x def symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x def transitive := ∀ ⦃x y z⦄, x ≺ y → y ≺ z → x ≺ z def equivalence := reflexive r ∧ symmetric r ∧ transitive r def total := ∀ x y, x ≺ y ∨ y ≺ x def mk_equivalence (rfl : reflexive r) (symm : symmetric r) (trans : transitive r) : equivalence r := ⟨rfl, symm, trans⟩ def irreflexive := ∀ x, ¬ x ≺ x def anti_symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x → x = y def empty_relation := λ a₁ a₂ : α, false def subrelation (q r : β → β → Prop) := ∀ ⦃x y⦄, q x y → r x y def inv_image (f : α → β) : α → α → Prop := λ a₁ a₂, f a₁ ≺ f a₂ lemma inv_image.trans (f : α → β) (h : transitive r) : transitive (inv_image r f) := λ (a₁ a₂ a₃ : α) (h₁ : inv_image r f a₁ a₂) (h₂ : inv_image r f a₂ a₃), h h₁ h₂ lemma inv_image.irreflexive (f : α → β) (h : irreflexive r) : irreflexive (inv_image r f) := λ (a : α) (h₁ : inv_image r f a a), h (f a) h₁ inductive tc {α : Sort u} (r : α → α → Prop) : α → α → Prop | base : ∀ a b, r a b → tc a b | trans : ∀ a b c, tc a b → tc b c → tc a c end relation section binary variables {α : Type u} {β : Type v} variable f : α → α → α variable inv : α → α variable one : α local notation a * b := f a b local notation a ⁻¹ := inv a variable g : α → α → α local notation a + b := g a b def commutative := ∀ a b, a * b = b * a def associative := ∀ a b c, (a * b) * c = a * (b * c) def left_identity := ∀ a, one * a = a def right_identity := ∀ a, a * one = a def right_inverse := ∀ a, a * a⁻¹ = one def left_cancelative := ∀ a b c, a * b = a * c → b = c def right_cancelative := ∀ a b c, a * b = c * b → a = c def left_distributive := ∀ a b c, a * (b + c) = a * b + a * c def right_distributive := ∀ a b c, (a + b) * c = a * c + b * c def right_commutative (h : β → α → β) := ∀ b a₁ a₂, h (h b a₁) a₂ = h (h b a₂) a₁ def left_commutative (h : α → β → β) := ∀ a₁ a₂ b, h a₁ (h a₂ b) = h a₂ (h a₁ b) lemma left_comm : commutative f → associative f → left_commutative f := assume hcomm hassoc, assume a b c, calc a*(b*c) = (a*b)*c : eq.symm (hassoc a b c) ... = (b*a)*c : hcomm a b ▸ rfl ... = b*(a*c) : hassoc b a c lemma right_comm : commutative f → associative f → right_commutative f := assume hcomm hassoc, assume a b c, calc (a*b)*c = a*(b*c) : hassoc a b c ... = a*(c*b) : hcomm b c ▸ rfl ... = (a*c)*b : eq.symm (hassoc a c b) end binary
96c2b74f484edfbf9966f5c9a80cb58db3562218
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/solve_by_elim_auto.lean
0dabf3936740bcce1fddf684e174f3f2492e7aa3
[]
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
9,497
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.core import Mathlib.PostPort namespace Mathlib /-! # solve_by_elim A depth-first search backwards reasoner. `solve_by_elim` takes a list of lemmas, and repeating tries to `apply` these against the goals, recursively acting on any generated subgoals. It accepts a variety of configuration options described below, enabling * backtracking across multiple goals, * pruning the search tree, and * invoking other tactics before or after trying to apply lemmas. At present it has no "premise selection", and simply tries the supplied lemmas in order at each step of the search. -/ namespace tactic namespace solve_by_elim /-- `mk_assumption_set` builds a collection of lemmas for use in the backtracking search in `solve_by_elim`. * By default, it includes all local hypotheses, along with `rfl`, `trivial`, `congr_fun` and `congr_arg`. * The flag `no_dflt` removes these. * The argument `hs` is a list of `simp_arg_type`s, and can be used to add, or remove, lemmas or expressions from the set. * The argument `attr : list name` adds all lemmas tagged with one of a specified list of attributes. `mk_assumption_set` returns not a `list expr`, but a `list (tactic expr) × tactic (list expr)`. There are two separate problems that need to be solved. ### Relevant local hypotheses `solve_by_elim*` works with multiple goals, and we need to use separate sets of local hypotheses for each goal. The second component of the returned value provides these local hypotheses. (Essentially using `local_context`, along with some filtering to remove hypotheses that have been explicitly removed via `only` or `[-h]`.) ### Stuck metavariables Lemmas with implicit arguments would be filled in with metavariables if we created the `expr` objects immediately, so instead we return thunks that generate the expressions on demand. This is the first component, with type `list (tactic expr)`. As an example, we have `def rfl : ∀ {α : Sort u} {a : α}, a = a`, which on elaboration will become `@rfl ?m_1 ?m_2`. Because `solve_by_elim` works by repeated application of lemmas against subgoals, the first time such a lemma is successfully applied, those metavariables will be unified, and thereafter have fixed values. This would make it impossible to apply the lemma a second time with different values of the metavariables. See https://github.com/leanprover-community/mathlib/issues/2269 As an optimisation, after we build the list of `tactic expr`s, we actually run them, and replace any that do not in fact produce metavariables with a simple `return` tactic. -/ -- We lock the tactic state so that any spurious goals generated during -- elaboration of pre-expressions are discarded /-- Configuration options for `solve_by_elim`. * `accept : list expr → tactic unit` determines whether the current branch should be explored. At each step, before the lemmas are applied, `accept` is passed the proof terms for the original goals, as reported by `get_goals` when `solve_by_elim` started. These proof terms may be metavariables (if no progress has been made on that goal) or may contain metavariables at some leaf nodes (if the goal has been partially solved by previous `apply` steps). If the `accept` tactic fails `solve_by_elim` aborts searching this branch and backtracks. By default `accept := λ _, skip` always succeeds. (There is an example usage in `tests/solve_by_elim.lean`.) * `pre_apply : tactic unit` specifies an additional tactic to run before each round of `apply`. * `discharger : tactic unit` specifies an additional tactic to apply on subgoals for which no lemma applies. If that tactic succeeds, `solve_by_elim` will continue applying lemmas on resulting goals. -/ /-- A helper function for trace messages, prepending '....' depending on the current search depth. -/ /-- A helper function to generate trace messages on successful applications. -/ /-- A helper function to generate trace messages on unsuccessful applications. -/ /-- A helper function to generate the tactic that print trace messages. This function exists to ensure the target is pretty printed only as necessary. -/ /-- The internal implementation of `solve_by_elim`, with a limiting counter. -/ /-- Arguments for `solve_by_elim`: * By default `solve_by_elim` operates only on the first goal, but with `backtrack_all_goals := true`, it operates on all goals at once, backtracking across goals as needed, and only succeeds if it discharges all goals. * `lemmas` specifies the list of lemmas to use in the backtracking search. If `none`, `solve_by_elim` uses the local hypotheses, along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`. * `lemma_thunks` provides the lemmas as a list of `tactic expr`, which are used to regenerate the `expr` objects to avoid binding metavariables. It should not usually be specified by the user. (If both `lemmas` and `lemma_thunks` are specified, only `lemma_thunks` is used.) * `ctx_thunk` is for internal use only: it returns the local hypotheses which will be used. * `max_depth` bounds the depth of the search. -/ /-- If no lemmas have been specified, generate the default set (local hypotheses, along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`). -/ end solve_by_elim /-- `solve_by_elim` repeatedly tries `apply`ing a lemma from the list of assumptions (passed via the `opt` argument), recursively operating on any generated subgoals, backtracking as necessary. `solve_by_elim` succeeds only if it discharges the goal. (By default, `solve_by_elim` focuses on the first goal, and only attempts to solve that. With the option `backtrack_all_goals := tt`, it attempts to solve all goals, and only succeeds if it does so. With `backtrack_all_goals := tt`, `solve_by_elim` will backtrack a solution it has found for one goal if it then can't discharge other goals.) If passed an empty list of assumptions, `solve_by_elim` builds a default set as per the interactive tactic, using the `local_context` along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`. To pass a particular list of assumptions, use the `lemmas` field in the configuration argument. This expects an `option (list expr)`. In certain situations it may be necessary to instead use the `lemma_thunks` field, which expects a `option (list (tactic expr))`. This allows for regenerating metavariables for each application, which might otherwise get stuck. See also the simpler tactic `apply_rules`, which does not perform backtracking. -/ namespace interactive /-- `apply_assumption` looks for an assumption of the form `... → ∀ _, ... → head` where `head` matches the current goal. If this fails, `apply_assumption` will call `symmetry` and try again. If this also fails, `apply_assumption` will call `exfalso` and try again, so that if there is an assumption of the form `P → ¬ Q`, the new tactic state will have two goals, `P` and `Q`. Optional arguments: - `lemmas`: a list of expressions to apply, instead of the local constants - `tac`: a tactic to run on each subgoal after applying an assumption; if this tactic fails, the corresponding assumption will be rejected and the next one will be attempted. -/ /-- `solve_by_elim` calls `apply` on the main goal to find an assumption whose head matches and then repeatedly calls `apply` on the generated subgoals until no subgoals remain, performing at most `max_depth` recursive steps. `solve_by_elim` discharges the current goal or fails. `solve_by_elim` performs back-tracking if subgoals can not be solved. By default, the assumptions passed to `apply` are the local context, `rfl`, `trivial`, `congr_fun` and `congr_arg`. The assumptions can be modified with similar syntax as for `simp`: * `solve_by_elim [h₁, h₂, ..., hᵣ]` also applies the named lemmas. * `solve_by_elim with attr₁ ... attrᵣ` also applies all lemmas tagged with the specified attributes. * `solve_by_elim only [h₁, h₂, ..., hᵣ]` does not include the local context, `rfl`, `trivial`, `congr_fun`, or `congr_arg` unless they are explicitly included. * `solve_by_elim [-id_1, ... -id_n]` uses the default assumptions, removing the specified ones. `solve_by_elim*` tries to solve all goals together, using backtracking if a solution for one goal makes other goals impossible. optional arguments passed via a configuration argument as `solve_by_elim { ... }` - max_depth: number of attempts at discharging generated sub-goals - discharger: a subsidiary tactic to try at each step when no lemmas apply (e.g. `cc` may be helpful). - pre_apply: a subsidiary tactic to run at each step before applying lemmas (e.g. `intros`). - accept: a subsidiary tactic `list expr → tactic unit` that at each step, before any lemmas are applied, is passed the original proof terms as reported by `get_goals` when `solve_by_elim` started (but which may by now have been partially solved by previous `apply` steps). If the `accept` tactic fails, `solve_by_elim` will abort searching the current branch and backtrack. This may be used to filter results, either at every step of the search, or filtering complete results (by testing for the absence of metavariables, and then the filtering condition). -/ end Mathlib
1011db510e8131586c11b2bdf81e3b64b53b8c12
618003631150032a5676f229d13a079ac875ff77
/src/tactic/omega/find_scalars.lean
aa1aa22653f7ebb12a0dcec09009ec2a3a1f1bd8
[ "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
3,040
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Tactic for performing Fourier–Motzkin elimination to find a contradictory linear combination of input constraints. -/ import tactic.omega.term import data.list.min_max open list.func namespace omega /-- Divide linear combinations into three groups by the coefficient of the `m`th variable in their resultant terms: negative, zero, or positive. -/ meta def trisect (m : nat) : list (list nat × term) → (list (list nat × term) × list (list nat × term) × list (list nat × term)) | [] := ([],[],[]) | ((p,t)::pts) := let (neg,zero,pos) := trisect pts in if get m t.snd < 0 then ((p,t)::neg,zero,pos) else if get m t.snd = 0 then (neg,(p,t)::zero,pos) else (neg,zero,(p,t)::pos) /-- Use two linear combinations to obtain a third linear combination whose resultant term does not include the `m`th variable. -/ meta def elim_var_aux (m : nat) : ((list nat × term) × (list nat × term)) → tactic (list nat × term) | ((p1,t1), (p2,t2)) := let n := int.nat_abs (get m t1.snd) in let o := int.nat_abs (get m t2.snd) in let lcm := (nat.lcm n o) in let n' := lcm / n in let o' := lcm / o in return (add (p1.map ((*) n')) (p2.map ((*) o')), term.add (t1.mul n') (t2.mul o')) /-- Use two lists of linear combinations (one in which the resultant terms include occurrences of the `m`th variable with positive coefficients, and one with negative coefficients) and linearly combine them in every possible way that eliminates the `m`th variable. -/ meta def elim_var (m : nat) (neg pos : list (list nat × term)) : tactic (list (list nat × term)) := let pairs := list.product neg pos in monad.mapm (elim_var_aux m) pairs /-- Search through a list of (linear combination × resultant term) pairs, find the first pair whose resultant term has a negative constant term, and return its linear combination -/ meta def find_neg_const : list (list nat × term) → tactic (list nat) | [] := tactic.failed | ((π,⟨c,_⟩)::l) := if c < 0 then return π else find_neg_const l /-- First, eliminate all variables by Fourier–Motzkin elimination. When all variables have been eliminated, find and return the linear combination which produces a constraint of the form `0 < k + t` such that `k` is the constant term of the RHS and `k < 0`. -/ meta def find_scalars_core : nat → list (list nat × term) → tactic (list nat) | 0 pts := find_neg_const pts | (m+1) pts := let (neg,zero,pos) := trisect m pts in do new ← elim_var m neg pos, find_scalars_core m (new ++ zero) /-- Perform Fourier–Motzkin elimination to find a contradictory linear combination of input constraints. -/ meta def find_scalars (ts : list term) : tactic (list nat) := find_scalars_core (ts.map (λ t : term, t.snd.length)).maximum.iget (ts.map_with_index (λ m t, (list.func.set 1 [] m, t))) end omega
b093b8cdcc792890143549c4171e6b79811437de
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/polynomial/basic.lean
c708f8ce63163590ec2701c486d061b1ca657839
[ "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
41,830
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.char_p.basic import data.mv_polynomial.comm_ring import data.mv_polynomial.equiv import data.polynomial.field_division import ring_theory.principal_ideal_domain import ring_theory.polynomial.content /-! # Ring-theoretic supplement of data.polynomial. ## Main results * `mv_polynomial.integral_domain`: If a ring is an integral domain, then so is its polynomial ring over finitely many variables. * `polynomial.is_noetherian_ring`: Hilbert basis theorem, that if a ring is noetherian then so is its polynomial ring. * `polynomial.wf_dvd_monoid`: If an integral domain is a `wf_dvd_monoid`, then so is its polynomial ring. * `polynomial.unique_factorization_monoid`: If an integral domain is a `unique_factorization_monoid`, then so is its polynomial ring. -/ noncomputable theory open_locale classical big_operators universes u v w namespace polynomial instance {R : Type u} [semiring R] (p : ℕ) [h : char_p R p] : char_p (polynomial R) p := let ⟨h⟩ := h in ⟨λ n, by rw [← C.map_nat_cast, ← C_0, C_inj, h]⟩ variables (R : Type u) [comm_ring R] /-- The `R`-submodule of `R[X]` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := ⨅ k : ℕ, ⨅ h : ↑k > n, (lcoeff R k).ker /-- The `R`-submodule of `R[X]` consisting of polynomials of degree < `n`. -/ def degree_lt (n : ℕ) : submodule R (polynomial R) := ⨅ k : ℕ, ⨅ h : k ≥ n, (lcoeff R k).ker variable {R} theorem mem_degree_le {n : with_bot ℕ} {f : polynomial R} : f ∈ degree_le R n ↔ degree f ≤ n := by simp only [degree_le, submodule.mem_infi, degree_le_iff_coeff_zero, linear_map.mem_ker]; refl @[mono] theorem degree_le_mono {m n : with_bot ℕ} (H : m ≤ n) : degree_le R m ≤ degree_le R n := λ f hf, mem_degree_le.2 (le_trans (mem_degree_le.1 hf) H) theorem degree_le_eq_span_X_pow {n : ℕ} : degree_le R n = submodule.span R ↑((finset.range (n+1)).image (λ n, (X : polynomial R)^n)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_le.1 hp, rw [← polynomial.sum_monomial_eq p, polynomial.sum], refine submodule.sum_mem _ (λ k hk, _), show monomial _ _ ∈ _, have := with_bot.coe_le_coe.1 (finset.sup_le_iff.1 hp k hk), rw [monomial_eq_C_mul_X, C_mul'], refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $ finset.mem_image.2 ⟨_, finset.mem_range.2 (nat.lt_succ_of_le this), rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_le.2, exact (degree_X_pow_le _).trans (with_bot.coe_le_coe.2 $ nat.le_of_lt_succ $ finset.mem_range.1 hk) end theorem mem_degree_lt {n : ℕ} {f : polynomial R} : f ∈ degree_lt R n ↔ degree f < n := by { simp_rw [degree_lt, submodule.mem_infi, linear_map.mem_ker, degree, finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff, with_bot.some_eq_coe, with_bot.coe_lt_coe, lt_iff_not_ge', ne, not_imp_not], refl } @[mono] theorem degree_lt_mono {m n : ℕ} (H : m ≤ n) : degree_lt R m ≤ degree_lt R n := λ f hf, mem_degree_lt.2 (lt_of_lt_of_le (mem_degree_lt.1 hf) $ with_bot.coe_le_coe.2 H) theorem degree_lt_eq_span_X_pow {n : ℕ} : degree_lt R n = submodule.span R ↑((finset.range n).image (λ n, X^n) : finset (polynomial R)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_lt.1 hp, rw [← polynomial.sum_monomial_eq p, polynomial.sum], refine submodule.sum_mem _ (λ k hk, _), show monomial _ _ ∈ _, have := with_bot.coe_lt_coe.1 ((finset.sup_lt_iff $ with_bot.bot_lt_coe n).1 hp k hk), rw [monomial_eq_C_mul_X, C_mul'], refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $ finset.mem_image.2 ⟨_, finset.mem_range.2 this, rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_lt.2, exact lt_of_le_of_lt (degree_X_pow_le _) (with_bot.coe_lt_coe.2 $ finset.mem_range.1 hk) end /-- The first `n` coefficients on `degree_lt n` form a linear equivalence with `fin n → F`. -/ def degree_lt_equiv (F : Type*) [field F] (n : ℕ) : degree_lt F n ≃ₗ[F] (fin n → F) := { to_fun := λ p n, (↑p : polynomial F).coeff n, inv_fun := λ f, ⟨∑ i : fin n, monomial i (f i), (degree_lt F n).sum_mem (λ i _, mem_degree_lt.mpr (lt_of_le_of_lt (degree_monomial_le i (f i)) (with_bot.coe_lt_coe.mpr i.is_lt)))⟩, map_add' := λ p q, by { ext, rw [submodule.coe_add, coeff_add], refl }, map_smul' := λ x p, by { ext, rw [submodule.coe_smul, coeff_smul], refl }, left_inv := begin rintro ⟨p, hp⟩, ext1, simp only [submodule.coe_mk], by_cases hp0 : p = 0, { subst hp0, simp only [coeff_zero, linear_map.map_zero, finset.sum_const_zero] }, rw [mem_degree_lt, degree_eq_nat_degree hp0, with_bot.coe_lt_coe] at hp, conv_rhs { rw [p.as_sum_range' n hp, ← fin.sum_univ_eq_sum_range] }, end, right_inv := begin intro f, ext i, simp only [finset_sum_coeff, submodule.coe_mk], rw [finset.sum_eq_single i, coeff_monomial, if_pos rfl], { rintro j - hji, rw [coeff_monomial, if_neg], rwa [← subtype.ext_iff] }, { intro h, exact (h (finset.mem_univ _)).elim } end } local attribute [instance] subset.ring /-- The finset of nonzero coefficients of a polynomial. -/ def frange (p : polynomial R) : finset R := finset.image (λ n, p.coeff n) p.support lemma frange_zero : frange (0 : polynomial R) = ∅ := rfl lemma mem_frange_iff {p : polynomial R} {c : R} : c ∈ p.frange ↔ ∃ n ∈ p.support, c = p.coeff n := by simp [frange, eq_comm] lemma frange_one : frange (1 : polynomial R) ⊆ {1} := begin simp [frange, finset.image_subset_iff], simp only [← C_1, coeff_C], assume n hn, simp only [exists_prop, ite_eq_right_iff, not_forall] at hn, simp [hn], end lemma coeff_mem_frange (p : polynomial R) (n : ℕ) (h : p.coeff n ≠ 0) : p.coeff n ∈ p.frange := begin simp only [frange, exists_prop, mem_support_iff, finset.mem_image, ne.def], exact ⟨n, h, rfl⟩, end /-- Given a polynomial, return the polynomial whose coefficients are in the ring closure of the original coefficients. -/ def restriction (p : polynomial R) : polynomial (ring.closure (↑p.frange : set R)) := ∑ i in p.support, monomial i (⟨p.coeff i, if H : p.coeff i = 0 then H.symm ▸ is_add_submonoid.zero_mem else ring.subset_closure (p.coeff_mem_frange _ H)⟩ : (ring.closure (↑p.frange : set R))) @[simp] theorem coeff_restriction {p : polynomial R} {n : ℕ} : ↑(coeff (restriction p) n) = coeff p n := begin simp only [restriction, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq', ne.def, ite_not], split_ifs, { rw h, refl }, { refl } end @[simp] theorem coeff_restriction' {p : polynomial R} {n : ℕ} : (coeff (restriction p) n).1 = coeff p n := coeff_restriction @[simp] lemma support_restriction (p : polynomial R) : support (restriction p) = support p := begin ext i, simp only [mem_support_iff, not_iff_not, ne.def], conv_rhs { rw [← coeff_restriction] }, exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩ end section local attribute [instance] algebra.of_is_subring subring.domain subset.comm_ring @[simp] theorem map_restriction (p : polynomial R) : p.restriction.map (algebra_map _ _) = p := ext $ λ n, by rw [coeff_map, algebra.is_subring_algebra_map_apply, coeff_restriction] end @[simp] theorem degree_restriction {p : polynomial R} : (restriction p).degree = p.degree := by simp [degree] @[simp] theorem nat_degree_restriction {p : polynomial R} : (restriction p).nat_degree = p.nat_degree := by simp [nat_degree] @[simp] theorem monic_restriction {p : polynomial R} : monic (restriction p) ↔ monic p := begin simp_rw [monic, leading_coeff, nat_degree_restriction, ← coeff_restriction], exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩ end @[simp] theorem restriction_zero : restriction (0 : polynomial R) = 0 := by simp only [restriction, finset.sum_empty, support_zero] @[simp] theorem restriction_one : restriction (1 : polynomial R) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_restriction', coeff_one, coeff_one]; split_ifs; refl variables {S : Type v} [ring S] {f : R →+* S} {x : S} theorem eval₂_restriction {p : polynomial R} : eval₂ f x p = eval₂ (f.comp (is_subring.subtype _)) x p.restriction := begin simp_rw [eval₂_eq_sum, sum, support_restriction, ← coeff_restriction], refl end section to_subring variables (p : polynomial R) (T : set R) [is_subring T] /-- Given a polynomial `p` and a subring `T` that contains the coefficients of `p`, return the corresponding polynomial whose coefficients are in `T. -/ def to_subring (hp : ↑p.frange ⊆ T) : polynomial T := ∑ i in p.support, monomial i (⟨p.coeff i, if H : p.coeff i = 0 then H.symm ▸ is_add_submonoid.zero_mem else hp (p.coeff_mem_frange _ H)⟩ : T) variables (hp : ↑p.frange ⊆ T) include hp @[simp] theorem coeff_to_subring {n : ℕ} : ↑(coeff (to_subring p T hp) n) = coeff p n := begin simp only [to_subring, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq', ne.def, ite_not], split_ifs, { rw h, refl }, { refl } end @[simp] theorem coeff_to_subring' {n : ℕ} : (coeff (to_subring p T hp) n).1 = coeff p n := coeff_to_subring _ _ hp @[simp] lemma support_to_subring : support (to_subring p T hp) = support p := begin ext i, simp only [mem_support_iff, not_iff_not, ne.def], conv_rhs { rw [← coeff_to_subring p T hp] }, exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩ end @[simp] theorem degree_to_subring : (to_subring p T hp).degree = p.degree := by simp [degree] @[simp] theorem nat_degree_to_subring : (to_subring p T hp).nat_degree = p.nat_degree := by simp [nat_degree] @[simp] theorem monic_to_subring : monic (to_subring p T hp) ↔ monic p := begin simp_rw [monic, leading_coeff, nat_degree_to_subring, ← coeff_to_subring p T hp], exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩ end omit hp @[simp] theorem to_subring_zero : to_subring (0 : polynomial R) T (by simp [frange_zero]) = 0 := by { ext i, simp } @[simp] theorem to_subring_one : to_subring (1 : polynomial R) T (set.subset.trans frange_one $finset.singleton_subset_set_iff.2 is_submonoid.one_mem) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_to_subring', coeff_one, coeff_one]; split_ifs; refl @[simp] theorem map_to_subring : (p.to_subring T hp).map (is_subring.subtype T) = p := by { ext n, simp [coeff_map] } end to_subring variables (T : set R) [is_subring T] /-- Given a polynomial whose coefficients are in some subring, return the corresponding polynomial whose coefficients are in the ambient ring. -/ def of_subring (p : polynomial T) : polynomial R := ∑ i in p.support, monomial i (p.coeff i : R) lemma coeff_of_subring (p : polynomial T) (n : ℕ) : coeff (of_subring T p) n = (coeff p n : T) := begin simp only [of_subring, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq', ite_eq_right_iff, ne.def, ite_not, not_not, ite_eq_left_iff], assume h, rw h, refl end @[simp] theorem frange_of_subring {p : polynomial T} : ↑(p.of_subring T).frange ⊆ T := begin assume i hi, simp only [frange, set.mem_image, mem_support_iff, ne.def, finset.mem_coe, finset.coe_image] at hi, rcases hi with ⟨n, hn, h'n⟩, rw [← h'n, coeff_of_subring], exact subtype.mem (coeff p n) end end polynomial variables {R : Type u} {σ : Type v} {M : Type w} [comm_ring R] [add_comm_group M] [module R M] namespace ideal open polynomial /-- If every coefficient of a polynomial is in an ideal `I`, then so is the polynomial itself -/ lemma polynomial_mem_ideal_of_coeff_mem_ideal (I : ideal (polynomial R)) (p : polynomial R) (hp : ∀ (n : ℕ), (p.coeff n) ∈ I.comap C) : p ∈ I := sum_C_mul_X_eq p ▸ submodule.sum_mem I (λ n hn, I.mul_mem_right _ (hp n)) /-- The push-forward of an ideal `I` of `R` to `polynomial R` via inclusion is exactly the set of polynomials whose coefficients are in `I` -/ theorem mem_map_C_iff {I : ideal R} {f : polynomial R} : f ∈ (ideal.map C I : ideal (polynomial R)) ↔ ∀ n : ℕ, f.coeff n ∈ I := begin split, { intros hf, apply submodule.span_induction hf, { intros f hf n, cases (set.mem_image _ _ _).mp hf with x hx, rw [← hx.right, coeff_C], by_cases (n = 0), { simpa [h] using hx.left }, { simp [h] } }, { simp }, { exact λ f g hf hg n, by simp [I.add_mem (hf n) (hg n)] }, { refine λ f g hg n, _, rw [smul_eq_mul, coeff_mul], exact I.sum_mem (λ c hc, I.smul_mem (f.coeff c.fst) (hg c.snd)) } }, { intros hf, rw ← sum_monomial_eq f, refine (I.map C : ideal (polynomial R)).sum_mem (λ n hn, _), simp [monomial_eq_C_mul_X], rw mul_comm, exact (I.map C : ideal (polynomial R)).mul_mem_left _ (mem_map_of_mem _ (hf n)) } end lemma quotient_map_C_eq_zero {I : ideal R} : ∀ a ∈ I, ((quotient.mk (map C I : ideal (polynomial R))).comp C) a = 0 := begin intros a ha, rw [ring_hom.comp_apply, quotient.eq_zero_iff_mem], exact mem_map_of_mem _ ha, end lemma eval₂_C_mk_eq_zero {I : ideal R} : ∀ f ∈ (map C I : ideal (polynomial R)), eval₂_ring_hom (C.comp (quotient.mk I)) X f = 0 := begin intros a ha, rw ← sum_monomial_eq a, dsimp, rw eval₂_sum, refine finset.sum_eq_zero (λ n hn, _), dsimp, rw eval₂_monomial (C.comp (quotient.mk I)) X, refine mul_eq_zero_of_left (polynomial.ext (λ m, _)) (X ^ n), erw coeff_C, by_cases h : m = 0, { simpa [h] using quotient.eq_zero_iff_mem.2 ((mem_map_C_iff.1 ha) n) }, { simp [h] } end /-- If `I` is an ideal of `R`, then the ring polynomials over the quotient ring `I.quotient` is isomorphic to the quotient of `polynomial R` by the ideal `map C I`, where `map C I` contains exactly the polynomials whose coefficients all lie in `I` -/ def polynomial_quotient_equiv_quotient_polynomial (I : ideal R) : polynomial (I.quotient) ≃+* (map C I : ideal (polynomial R)).quotient := { to_fun := eval₂_ring_hom (quotient.lift I ((quotient.mk (map C I : ideal (polynomial R))).comp C) quotient_map_C_eq_zero) ((quotient.mk (map C I : ideal (polynomial R)) X)), inv_fun := quotient.lift (map C I : ideal (polynomial R)) (eval₂_ring_hom (C.comp (quotient.mk I)) X) eval₂_C_mk_eq_zero, map_mul' := λ f g, by simp, map_add' := λ f g, by simp, left_inv := begin intro f, apply polynomial.induction_on' f, { simp_intros p q hp hq, rw [hp, hq] }, { rintros n ⟨x⟩, simp [monomial_eq_smul_X, C_mul'] } end, right_inv := begin rintro ⟨f⟩, apply polynomial.induction_on' f, { simp_intros p q hp hq, rw [hp, hq] }, { intros n a, simp [monomial_eq_smul_X, ← C_mul' a (X ^ n)] }, end, } /-- If `P` is a prime ideal of `R`, then `R[x]/(P)` is an integral domain. -/ lemma is_integral_domain_map_C_quotient {P : ideal R} (H : is_prime P) : is_integral_domain (quotient (map C P : ideal (polynomial R))) := ring_equiv.is_integral_domain (polynomial (quotient P)) (integral_domain.to_is_integral_domain (polynomial (quotient P))) (polynomial_quotient_equiv_quotient_polynomial P).symm /-- If `P` is a prime ideal of `R`, then `P.R[x]` is a prime ideal of `R[x]`. -/ lemma is_prime_map_C_of_is_prime {P : ideal R} (H : is_prime P) : is_prime (map C P : ideal (polynomial R)) := (quotient.is_integral_domain_iff_prime (map C P : ideal (polynomial R))).mp (is_integral_domain_map_C_quotient H) /-- Given any ring `R` and an ideal `I` of `polynomial R`, we get a map `R → R[x] → R[x]/I`. If we let `R` be the image of `R` in `R[x]/I` then we also have a map `R[x] → R'[x]`. In particular we can map `I` across this map, to get `I'` and a new map `R' → R'[x] → R'[x]/I`. This theorem shows `I'` will not contain any non-zero constant polynomials -/ lemma eq_zero_of_polynomial_mem_map_range (I : ideal (polynomial R)) (x : ((quotient.mk I).comp C).range) (hx : C x ∈ (I.map (polynomial.map_ring_hom ((quotient.mk I).comp C).range_restrict))) : x = 0 := begin let i := ((quotient.mk I).comp C).range_restrict, have hi' : (polynomial.map_ring_hom i).ker ≤ I, { refine λ f hf, polynomial_mem_ideal_of_coeff_mem_ideal I f (λ n, _), rw [mem_comap, ← quotient.eq_zero_iff_mem, ← ring_hom.comp_apply], rw [ring_hom.mem_ker, coe_map_ring_hom] at hf, replace hf := congr_arg (λ (f : polynomial _), f.coeff n) hf, simp only [coeff_map, coeff_zero] at hf, rwa [subtype.ext_iff, ring_hom.coe_range_restrict] at hf }, obtain ⟨x, hx'⟩ := x, obtain ⟨y, rfl⟩ := (ring_hom.mem_range).1 hx', refine subtype.eq _, simp only [ring_hom.comp_apply, quotient.eq_zero_iff_mem, subring.coe_zero, subtype.val_eq_coe], suffices : C (i y) ∈ (I.map (polynomial.map_ring_hom i)), { obtain ⟨f, hf⟩ := mem_image_of_mem_map_of_surjective (polynomial.map_ring_hom i) (polynomial.map_surjective _ (((quotient.mk I).comp C).range_restrict_surjective)) this, refine sub_add_cancel (C y) f ▸ I.add_mem (hi' _ : (C y - f) ∈ I) hf.1, rw [ring_hom.mem_ker, ring_hom.map_sub, hf.2, sub_eq_zero, coe_map_ring_hom, map_C] }, exact hx, end /-- `polynomial R` is never a field for any ring `R`. -/ lemma polynomial_not_is_field : ¬ is_field (polynomial R) := begin by_contradiction hR, by_cases hR' : ∃ (x y : R), x ≠ y, { haveI : nontrivial R := let ⟨x, y, hxy⟩ := hR' in nontrivial_of_ne x y hxy, obtain ⟨p, hp⟩ := hR.mul_inv_cancel X_ne_zero, by_cases hp0 : p = 0, { replace hp := congr_arg degree hp, rw [hp0, mul_zero, degree_zero, degree_one] at hp, contradiction }, { have : p.degree < (X * p).degree := (mul_comm p X) ▸ degree_lt_degree_mul_X hp0, rw [congr_arg degree hp, degree_one, nat.with_bot.lt_zero_iff, degree_eq_bot] at this, exact hp0 this } }, { push_neg at hR', exact let ⟨x, y, hxy⟩ := hR.exists_pair_ne in hxy (polynomial.ext (λ n, hR' _ _)) } end /-- The only constant in a maximal ideal over a field is `0`. -/ lemma eq_zero_of_constant_mem_of_maximal (hR : is_field R) (I : ideal (polynomial R)) [hI : I.is_maximal] (x : R) (hx : C x ∈ I) : x = 0 := begin refine classical.by_contradiction (λ hx0, hI.ne_top ((eq_top_iff_one I).2 _)), obtain ⟨y, hy⟩ := hR.mul_inv_cancel hx0, convert I.smul_mem (C y) hx, rw [smul_eq_mul, ← C.map_mul, mul_comm y x, hy, ring_hom.map_one], end /-- Transport an ideal of `R[X]` to an `R`-submodule of `R[X]`. -/ def of_polynomial (I : ideal (polynomial R)) : submodule R (polynomial R) := { carrier := I.carrier, zero_mem' := I.zero_mem, add_mem' := λ _ _, I.add_mem, smul_mem' := λ c x H, by { rw [← C_mul'], exact I.mul_mem_left _ H } } variables {I : ideal (polynomial R)} theorem mem_of_polynomial (x) : x ∈ I.of_polynomial ↔ x ∈ I := iff.rfl variables (I) /-- Given an ideal `I` of `R[X]`, make the `R`-submodule of `I` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := degree_le R n ⊓ I.of_polynomial /-- Given an ideal `I` of `R[X]`, make the ideal in `R` of leading coefficients of polynomials in `I` with degree ≤ `n`. -/ def leading_coeff_nth (n : ℕ) : ideal R := (I.degree_le n).map $ lcoeff R n theorem mem_leading_coeff_nth (n : ℕ) (x) : x ∈ I.leading_coeff_nth n ↔ ∃ p ∈ I, degree p ≤ n ∧ leading_coeff p = x := begin simp only [leading_coeff_nth, degree_le, submodule.mem_map, lcoeff_apply, submodule.mem_inf, mem_degree_le], split, { rintro ⟨p, ⟨hpdeg, hpI⟩, rfl⟩, cases lt_or_eq_of_le hpdeg with hpdeg hpdeg, { refine ⟨0, I.zero_mem, bot_le, _⟩, rw [leading_coeff_zero, eq_comm], exact coeff_eq_zero_of_degree_lt hpdeg }, { refine ⟨p, hpI, le_of_eq hpdeg, _⟩, rw [leading_coeff, nat_degree, hpdeg], refl } }, { rintro ⟨p, hpI, hpdeg, rfl⟩, have : nat_degree p + (n - nat_degree p) = n, { exact nat.add_sub_cancel' (nat_degree_le_of_degree_le hpdeg) }, refine ⟨p * X ^ (n - nat_degree p), ⟨_, I.mul_mem_right _ hpI⟩, _⟩, { apply le_trans (degree_mul_le _ _) _, apply le_trans (add_le_add (degree_le_nat_degree) (degree_X_pow_le _)) _, rw [← with_bot.coe_add, this], exact le_refl _ }, { rw [leading_coeff, ← coeff_mul_X_pow p (n - nat_degree p), this] } } end theorem mem_leading_coeff_nth_zero (x) : x ∈ I.leading_coeff_nth 0 ↔ C x ∈ I := (mem_leading_coeff_nth _ _ _).trans ⟨λ ⟨p, hpI, hpdeg, hpx⟩, by rwa [← hpx, leading_coeff, nat.eq_zero_of_le_zero (nat_degree_le_of_degree_le hpdeg), ← eq_C_of_degree_le_zero hpdeg], λ hx, ⟨C x, hx, degree_C_le, leading_coeff_C x⟩⟩ theorem leading_coeff_nth_mono {m n : ℕ} (H : m ≤ n) : I.leading_coeff_nth m ≤ I.leading_coeff_nth n := begin intros r hr, simp only [set_like.mem_coe, mem_leading_coeff_nth] at hr ⊢, rcases hr with ⟨p, hpI, hpdeg, rfl⟩, refine ⟨p * X ^ (n - m), I.mul_mem_right _ hpI, _, leading_coeff_mul_X_pow⟩, refine le_trans (degree_mul_le _ _) _, refine le_trans (add_le_add hpdeg (degree_X_pow_le _)) _, rw [← with_bot.coe_add, nat.add_sub_cancel' H], exact le_refl _ end /-- Given an ideal `I` in `R[X]`, make the ideal in `R` of the leading coefficients in `I`. -/ def leading_coeff : ideal R := ⨆ n : ℕ, I.leading_coeff_nth n theorem mem_leading_coeff (x) : x ∈ I.leading_coeff ↔ ∃ p ∈ I, polynomial.leading_coeff p = x := begin rw [leading_coeff, submodule.mem_supr_of_directed], simp only [mem_leading_coeff_nth], { split, { rintro ⟨i, p, hpI, hpdeg, rfl⟩, exact ⟨p, hpI, rfl⟩ }, rintro ⟨p, hpI, rfl⟩, exact ⟨nat_degree p, p, hpI, degree_le_nat_degree, rfl⟩ }, intros i j, exact ⟨i + j, I.leading_coeff_nth_mono (nat.le_add_right _ _), I.leading_coeff_nth_mono (nat.le_add_left _ _)⟩ end theorem is_fg_degree_le [is_noetherian_ring R] (n : ℕ) : submodule.fg (I.degree_le n) := is_noetherian_submodule_left.1 (is_noetherian_of_fg_of_noetherian _ ⟨_, degree_le_eq_span_X_pow.symm⟩) _ end ideal namespace polynomial @[priority 100] instance {R : Type*} [integral_domain R] [wf_dvd_monoid R] : wf_dvd_monoid (polynomial R) := { well_founded_dvd_not_unit := begin classical, refine rel_hom.well_founded ⟨λ p, (if p = 0 then ⊤ else ↑p.degree, p.leading_coeff), _⟩ (prod.lex_wf (with_top.well_founded_lt $ with_bot.well_founded_lt nat.lt_wf) _inst_5.well_founded_dvd_not_unit), rintros a b ⟨ane0, ⟨c, ⟨not_unit_c, rfl⟩⟩⟩, rw [polynomial.degree_mul, if_neg ane0], split_ifs with hac, { rw [hac, polynomial.leading_coeff_zero], apply prod.lex.left, exact lt_of_le_of_ne le_top with_top.coe_ne_top }, have cne0 : c ≠ 0 := right_ne_zero_of_mul hac, simp only [cne0, ane0, polynomial.leading_coeff_mul], by_cases hdeg : c.degree = 0, { simp only [hdeg, add_zero], refine prod.lex.right _ ⟨_, ⟨c.leading_coeff, (λ unit_c, not_unit_c _), rfl⟩⟩, { rwa [ne, polynomial.leading_coeff_eq_zero] }, rw [polynomial.is_unit_iff, polynomial.eq_C_of_degree_eq_zero hdeg], use [c.leading_coeff, unit_c], rw [polynomial.leading_coeff, polynomial.nat_degree_eq_of_degree_eq_some hdeg] }, { apply prod.lex.left, rw polynomial.degree_eq_nat_degree cne0 at *, rw [with_top.coe_lt_coe, polynomial.degree_eq_nat_degree ane0, ← with_bot.coe_add, with_bot.coe_lt_coe], exact lt_add_of_pos_right _ (nat.pos_of_ne_zero (λ h, hdeg (h.symm ▸ with_bot.coe_zero))) }, end } end polynomial /-- Hilbert basis theorem: a polynomial ring over a noetherian ring is a noetherian ring. -/ protected theorem polynomial.is_noetherian_ring [is_noetherian_ring R] : is_noetherian_ring (polynomial R) := is_noetherian_ring_iff.2 ⟨assume I : ideal (polynomial R), let M := well_founded.min (is_noetherian_iff_well_founded.1 (by apply_instance)) (set.range I.leading_coeff_nth) ⟨_, ⟨0, rfl⟩⟩ in have hm : M ∈ set.range I.leading_coeff_nth := well_founded.min_mem _ _ _, let ⟨N, HN⟩ := hm, ⟨s, hs⟩ := I.is_fg_degree_le N in have hm2 : ∀ k, I.leading_coeff_nth k ≤ M := λ k, or.cases_on (le_or_lt k N) (λ h, HN ▸ I.leading_coeff_nth_mono h) (λ h x hx, classical.by_contradiction $ λ hxm, have ¬M < I.leading_coeff_nth k, by refine well_founded.not_lt_min (well_founded_submodule_gt _ _) _ _ _; exact ⟨k, rfl⟩, this ⟨HN ▸ I.leading_coeff_nth_mono (le_of_lt h), λ H, hxm (H hx)⟩), have hs2 : ∀ {x}, x ∈ I.degree_le N → x ∈ ideal.span (↑s : set (polynomial R)), from hs ▸ λ x hx, submodule.span_induction hx (λ _ hx, ideal.subset_span hx) (ideal.zero_mem _) (λ _ _, ideal.add_mem _) (λ c f hf, f.C_mul' c ▸ ideal.mul_mem_left _ _ hf), ⟨s, le_antisymm (ideal.span_le.2 $ λ x hx, have x ∈ I.degree_le N, from hs ▸ submodule.subset_span hx, this.2) $ begin have : submodule.span (polynomial R) ↑s = ideal.span ↑s, by refl, rw this, intros p hp, generalize hn : p.nat_degree = k, induction k using nat.strong_induction_on with k ih generalizing p, cases le_or_lt k N, { subst k, refine hs2 ⟨polynomial.mem_degree_le.2 (le_trans polynomial.degree_le_nat_degree $ with_bot.coe_le_coe.2 h), hp⟩ }, { have hp0 : p ≠ 0, { rintro rfl, cases hn, exact nat.not_lt_zero _ h }, have : (0 : R) ≠ 1, { intro h, apply hp0, ext i, refine (mul_one _).symm.trans _, rw [← h, mul_zero], refl }, haveI : nontrivial R := ⟨⟨0, 1, this⟩⟩, have : p.leading_coeff ∈ I.leading_coeff_nth N, { rw HN, exact hm2 k ((I.mem_leading_coeff_nth _ _).2 ⟨_, hp, hn ▸ polynomial.degree_le_nat_degree, rfl⟩) }, rw I.mem_leading_coeff_nth at this, rcases this with ⟨q, hq, hdq, hlqp⟩, have hq0 : q ≠ 0, { intro H, rw [← polynomial.leading_coeff_eq_zero] at H, rw [hlqp, polynomial.leading_coeff_eq_zero] at H, exact hp0 H }, have h1 : p.degree = (q * polynomial.X ^ (k - q.nat_degree)).degree, { rw [polynomial.degree_mul', polynomial.degree_X_pow], rw [polynomial.degree_eq_nat_degree hp0, polynomial.degree_eq_nat_degree hq0], rw [← with_bot.coe_add, nat.add_sub_cancel', hn], { refine le_trans (polynomial.nat_degree_le_of_degree_le hdq) (le_of_lt h) }, rw [polynomial.leading_coeff_X_pow, mul_one], exact mt polynomial.leading_coeff_eq_zero.1 hq0 }, have h2 : p.leading_coeff = (q * polynomial.X ^ (k - q.nat_degree)).leading_coeff, { rw [← hlqp, polynomial.leading_coeff_mul_X_pow] }, have := polynomial.degree_sub_lt h1 hp0 h2, rw [polynomial.degree_eq_nat_degree hp0] at this, rw ← sub_add_cancel p (q * polynomial.X ^ (k - q.nat_degree)), refine (ideal.span ↑s).add_mem _ ((ideal.span ↑s).mul_mem_right _ _), { by_cases hpq : p - q * polynomial.X ^ (k - q.nat_degree) = 0, { rw hpq, exact ideal.zero_mem _ }, refine ih _ _ (I.sub_mem hp (I.mul_mem_right _ hq)) rfl, rwa [polynomial.degree_eq_nat_degree hpq, with_bot.coe_lt_coe, hn] at this }, exact hs2 ⟨polynomial.mem_degree_le.2 hdq, hq⟩ } end⟩⟩ attribute [instance] polynomial.is_noetherian_ring namespace polynomial theorem exists_irreducible_of_degree_pos {R : Type u} [integral_domain R] [wf_dvd_monoid R] {f : polynomial R} (hf : 0 < f.degree) : ∃ g, irreducible g ∧ g ∣ f := wf_dvd_monoid.exists_irreducible_factor (λ huf, ne_of_gt hf $ degree_eq_zero_of_is_unit huf) (λ hf0, not_lt_of_lt hf $ hf0.symm ▸ (@degree_zero R _).symm ▸ with_bot.bot_lt_coe _) theorem exists_irreducible_of_nat_degree_pos {R : Type u} [integral_domain R] [wf_dvd_monoid R] {f : polynomial R} (hf : 0 < f.nat_degree) : ∃ g, irreducible g ∧ g ∣ f := exists_irreducible_of_degree_pos $ by { contrapose! hf, exact nat_degree_le_of_degree_le hf } theorem exists_irreducible_of_nat_degree_ne_zero {R : Type u} [integral_domain R] [wf_dvd_monoid R] {f : polynomial R} (hf : f.nat_degree ≠ 0) : ∃ g, irreducible g ∧ g ∣ f := exists_irreducible_of_nat_degree_pos $ nat.pos_of_ne_zero hf lemma linear_independent_powers_iff_aeval (f : M →ₗ[R] M) (v : M) : linear_independent R (λ n : ℕ, (f ^ n) v) ↔ ∀ (p : polynomial R), aeval f p v = 0 → p = 0 := begin rw linear_independent_iff, simp only [finsupp.total_apply, aeval_endomorphism, forall_iff_forall_finsupp, sum, support, coeff, ← zero_to_finsupp], exact iff.rfl, end lemma disjoint_ker_aeval_of_coprime (f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) : disjoint (aeval f p).ker (aeval f q).ker := begin intros v hv, rcases hpq with ⟨p', q', hpq'⟩, simpa [linear_map.mem_ker.1 (submodule.mem_inf.1 hv).1, linear_map.mem_ker.1 (submodule.mem_inf.1 hv).2] using congr_arg (λ p : polynomial R, aeval f p v) hpq'.symm, end lemma sup_aeval_range_eq_top_of_coprime (f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) : (aeval f p).range ⊔ (aeval f q).range = ⊤ := begin rw eq_top_iff, intros v hv, rw submodule.mem_sup, rcases hpq with ⟨p', q', hpq'⟩, use aeval f (p * p') v, use linear_map.mem_range.2 ⟨aeval f p' v, by simp only [linear_map.mul_apply, aeval_mul]⟩, use aeval f (q * q') v, use linear_map.mem_range.2 ⟨aeval f q' v, by simp only [linear_map.mul_apply, aeval_mul]⟩, simpa only [mul_comm p p', mul_comm q q', aeval_one, aeval_add] using congr_arg (λ p : polynomial R, aeval f p v) hpq' end lemma sup_ker_aeval_le_ker_aeval_mul {f : M →ₗ[R] M} {p q : polynomial R} : (aeval f p).ker ⊔ (aeval f q).ker ≤ (aeval f (p * q)).ker := begin intros v hv, rcases submodule.mem_sup.1 hv with ⟨x, hx, y, hy, hxy⟩, have h_eval_x : aeval f (p * q) x = 0, { rw [mul_comm, aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hx, linear_map.map_zero] }, have h_eval_y : aeval f (p * q) y = 0, { rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hy, linear_map.map_zero] }, rw [linear_map.mem_ker, ←hxy, linear_map.map_add, h_eval_x, h_eval_y, add_zero], end lemma sup_ker_aeval_eq_ker_aeval_mul_of_coprime (f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) : (aeval f p).ker ⊔ (aeval f q).ker = (aeval f (p * q)).ker := begin apply le_antisymm sup_ker_aeval_le_ker_aeval_mul, intros v hv, rw submodule.mem_sup, rcases hpq with ⟨p', q', hpq'⟩, have h_eval₂_qpp' := calc aeval f (q * (p * p')) v = aeval f (p' * (p * q)) v : by rw [mul_comm, mul_assoc, mul_comm, mul_assoc, mul_comm q p] ... = 0 : by rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hv, linear_map.map_zero], have h_eval₂_pqq' := calc aeval f (p * (q * q')) v = aeval f (q' * (p * q)) v : by rw [←mul_assoc, mul_comm] ... = 0 : by rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hv, linear_map.map_zero], rw aeval_mul at h_eval₂_qpp' h_eval₂_pqq', refine ⟨aeval f (q * q') v, linear_map.mem_ker.1 h_eval₂_pqq', aeval f (p * p') v, linear_map.mem_ker.1 h_eval₂_qpp', _⟩, rw [add_comm, mul_comm p p', mul_comm q q'], simpa using congr_arg (λ p : polynomial R, aeval f p v) hpq' end end polynomial namespace mv_polynomial lemma is_noetherian_ring_fin_0 [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial (fin 0) R) := is_noetherian_ring_of_ring_equiv R ((mv_polynomial.pempty_ring_equiv R).symm.trans (rename_equiv R fin_zero_equiv'.symm).to_ring_equiv) theorem is_noetherian_ring_fin [is_noetherian_ring R] : ∀ {n : ℕ}, is_noetherian_ring (mv_polynomial (fin n) R) | 0 := is_noetherian_ring_fin_0 | (n+1) := @is_noetherian_ring_of_ring_equiv (polynomial (mv_polynomial (fin n) R)) _ _ _ (mv_polynomial.fin_succ_equiv _ n).to_ring_equiv.symm (@polynomial.is_noetherian_ring (mv_polynomial (fin n) R) _ (is_noetherian_ring_fin)) /-- The multivariate polynomial ring in finitely many variables over a noetherian ring is itself a noetherian ring. -/ instance is_noetherian_ring [fintype σ] [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial σ R) := @is_noetherian_ring_of_ring_equiv (mv_polynomial (fin (fintype.card σ)) R) _ _ _ (rename_equiv R (fintype.equiv_fin σ).symm).to_ring_equiv is_noetherian_ring_fin lemma is_integral_domain_fin_zero (R : Type u) [comm_ring R] (hR : is_integral_domain R) : is_integral_domain (mv_polynomial (fin 0) R) := ring_equiv.is_integral_domain R hR ((rename_equiv R fin_zero_equiv').to_ring_equiv.trans (mv_polynomial.pempty_ring_equiv R)) /-- Auxiliary lemma: Multivariate polynomials over an integral domain with variables indexed by `fin n` form an integral domain. This fact is proven inductively, and then used to prove the general case without any finiteness hypotheses. See `mv_polynomial.integral_domain` for the general case. -/ lemma is_integral_domain_fin (R : Type u) [comm_ring R] (hR : is_integral_domain R) : ∀ (n : ℕ), is_integral_domain (mv_polynomial (fin n) R) | 0 := is_integral_domain_fin_zero R hR | (n+1) := ring_equiv.is_integral_domain (polynomial (mv_polynomial (fin n) R)) (is_integral_domain_fin n).polynomial (mv_polynomial.fin_succ_equiv _ n).to_ring_equiv lemma is_integral_domain_fintype (R : Type u) (σ : Type v) [comm_ring R] [fintype σ] (hR : is_integral_domain R) : is_integral_domain (mv_polynomial σ R) := @ring_equiv.is_integral_domain _ (mv_polynomial (fin $ fintype.card σ) R) _ _ (mv_polynomial.is_integral_domain_fin _ hR _) (rename_equiv R (fintype.equiv_fin σ)).to_ring_equiv /-- Auxiliary definition: Multivariate polynomials in finitely many variables over an integral domain form an integral domain. This fact is proven by transport of structure from the `mv_polynomial.integral_domain_fin`, and then used to prove the general case without finiteness hypotheses. See `mv_polynomial.integral_domain` for the general case. -/ def integral_domain_fintype (R : Type u) (σ : Type v) [integral_domain R] [fintype σ] : integral_domain (mv_polynomial σ R) := @is_integral_domain.to_integral_domain _ _ $ mv_polynomial.is_integral_domain_fintype R σ $ integral_domain.to_is_integral_domain R protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {R : Type u} [integral_domain R] {σ : Type v} (p q : mv_polynomial σ R) (h : p * q = 0) : p = 0 ∨ q = 0 := begin obtain ⟨s, p, rfl⟩ := exists_finset_rename p, obtain ⟨t, q, rfl⟩ := exists_finset_rename q, have : rename (subtype.map id (finset.subset_union_left s t) : {x // x ∈ s} → {x // x ∈ s ∪ t}) p * rename (subtype.map id (finset.subset_union_right s t) : {x // x ∈ t} → {x // x ∈ s ∪ t}) q = 0, { apply rename_injective _ subtype.val_injective, simpa using h }, letI := mv_polynomial.integral_domain_fintype R {x // x ∈ (s ∪ t)}, rw mul_eq_zero at this, cases this; [left, right], all_goals { simpa using congr_arg (rename subtype.val) this } end /-- The multivariate polynomial ring over an integral domain is an integral domain. -/ instance {R : Type u} {σ : Type v} [integral_domain R] : integral_domain (mv_polynomial σ R) := { eq_zero_or_eq_zero_of_mul_eq_zero := mv_polynomial.eq_zero_or_eq_zero_of_mul_eq_zero, exists_pair_ne := ⟨0, 1, λ H, begin have : eval₂ (ring_hom.id _) (λ s, (0:R)) (0 : mv_polynomial σ R) = eval₂ (ring_hom.id _) (λ s, (0:R)) (1 : mv_polynomial σ R), { congr, exact H }, simpa, end⟩, .. (by apply_instance : comm_ring (mv_polynomial σ R)) } lemma map_mv_polynomial_eq_eval₂ {S : Type*} [comm_ring S] [fintype σ] (ϕ : mv_polynomial σ R →+* S) (p : mv_polynomial σ R) : ϕ p = mv_polynomial.eval₂ (ϕ.comp mv_polynomial.C) (λ s, ϕ (mv_polynomial.X s)) p := begin refine trans (congr_arg ϕ (mv_polynomial.as_sum p)) _, rw [mv_polynomial.eval₂_eq', ϕ.map_sum], congr, ext, simp only [monomial_eq, ϕ.map_pow, ϕ.map_prod, ϕ.comp_apply, ϕ.map_mul, finsupp.prod_pow], end lemma quotient_map_C_eq_zero {I : ideal R} {i : R} (hi : i ∈ I) : (ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R))).comp C i = 0 := begin simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient.eq_zero_iff_mem], exact ideal.mem_map_of_mem _ hi end /-- If every coefficient of a polynomial is in an ideal `I`, then so is the polynomial itself, multivariate version. -/ lemma mem_ideal_of_coeff_mem_ideal (I : ideal (mv_polynomial σ R)) (p : mv_polynomial σ R) (hcoe : ∀ (m : σ →₀ ℕ), p.coeff m ∈ I.comap C) : p ∈ I := begin rw as_sum p, suffices : ∀ m ∈ p.support, monomial m (mv_polynomial.coeff m p) ∈ I, { exact submodule.sum_mem I this }, intros m hm, rw [← mul_one (coeff m p), ← C_mul_monomial], suffices : C (coeff m p) ∈ I, { exact I.mul_mem_right (monomial m 1) this }, simpa [ideal.mem_comap] using hcoe m end /-- The push-forward of an ideal `I` of `R` to `mv_polynomial σ R` via inclusion is exactly the set of polynomials whose coefficients are in `I` -/ theorem mem_map_C_iff {I : ideal R} {f : mv_polynomial σ R} : f ∈ (ideal.map C I : ideal (mv_polynomial σ R)) ↔ ∀ (m : σ →₀ ℕ), f.coeff m ∈ I := begin split, { intros hf, apply submodule.span_induction hf, { intros f hf n, cases (set.mem_image _ _ _).mp hf with x hx, rw [← hx.right, coeff_C], by_cases (n = 0), { simpa [h] using hx.left }, { simp [ne.symm h] } }, { simp }, { exact λ f g hf hg n, by simp [I.add_mem (hf n) (hg n)] }, { refine λ f g hg n, _, rw [smul_eq_mul, coeff_mul], exact I.sum_mem (λ c hc, I.smul_mem (f.coeff c.fst) (hg c.snd)) } }, { intros hf, rw as_sum f, suffices : ∀ m ∈ f.support, monomial m (coeff m f) ∈ (ideal.map C I : ideal (mv_polynomial σ R)), { exact submodule.sum_mem _ this }, intros m hm, rw [← mul_one (coeff m f), ← C_mul_monomial], suffices : C (coeff m f) ∈ (ideal.map C I : ideal (mv_polynomial σ R)), { exact ideal.mul_mem_right _ _ this }, apply ideal.mem_map_of_mem _, exact hf m } end lemma eval₂_C_mk_eq_zero {I : ideal R} {a : mv_polynomial σ R} (ha : a ∈ (ideal.map C I : ideal (mv_polynomial σ R))) : eval₂_hom (C.comp (ideal.quotient.mk I)) X a = 0 := begin rw as_sum a, rw [coe_eval₂_hom, eval₂_sum], refine finset.sum_eq_zero (λ n hn, _), simp only [eval₂_monomial, function.comp_app, ring_hom.coe_comp], refine mul_eq_zero_of_left _ _, suffices : coeff n a ∈ I, { rw [← @ideal.mk_ker R _ I, ring_hom.mem_ker] at this, simp only [this, C_0] }, exact mem_map_C_iff.1 ha n end /-- If `I` is an ideal of `R`, then the ring `mv_polynomial σ I.quotient` is isomorphic as an `R`-algebra to the quotient of `mv_polynomial σ R` by the ideal generated by `I`. -/ def quotient_equiv_quotient_mv_polynomial (I : ideal R) : mv_polynomial σ I.quotient ≃ₐ[R] (ideal.map C I : ideal (mv_polynomial σ R)).quotient := { to_fun := eval₂_hom (ideal.quotient.lift I ((ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R))).comp C) (λ i hi, quotient_map_C_eq_zero hi)) (λ i, ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R)) (X i)), inv_fun := ideal.quotient.lift (ideal.map C I : ideal (mv_polynomial σ R)) (eval₂_hom (C.comp (ideal.quotient.mk I)) X) (λ a ha, eval₂_C_mk_eq_zero ha), map_mul' := ring_hom.map_mul _, map_add' := ring_hom.map_add _, left_inv := begin intro f, apply induction_on f, { rintro ⟨r⟩, rw [coe_eval₂_hom, eval₂_C], simp only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, bind₂_C_right, ring_hom.coe_comp] }, { simp_intros p q hp hq only [ring_hom.map_add, mv_polynomial.coe_eval₂_hom, coe_eval₂_hom, mv_polynomial.eval₂_add, mv_polynomial.eval₂_hom_eq_bind₂, eval₂_hom_eq_bind₂], rw [hp, hq] }, { simp_intros p i hp only [eval₂_hom_eq_bind₂, coe_eval₂_hom], simp only [hp, eval₂_hom_eq_bind₂, coe_eval₂_hom, ideal.quotient.lift_mk, bind₂_X_right, eval₂_mul, ring_hom.map_mul, eval₂_X] } end, right_inv := begin rintro ⟨f⟩, apply induction_on f, { intros r, simp only [submodule.quotient.quot_mk_eq_mk, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, ring_hom.coe_comp, eval₂_hom_C] }, { simp_intros p q hp hq only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, eval₂_add, ring_hom.map_add, coe_eval₂_hom, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk], rw [hp, hq] }, { simp_intros p i hp only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, coe_eval₂_hom, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, bind₂_X_right, eval₂_mul, ring_hom.map_mul, eval₂_X], simp only [hp] } end, commutes' := λ r, eval₂_hom_C _ _ (ideal.quotient.mk I r) } end mv_polynomial namespace polynomial open unique_factorization_monoid variables {D : Type u} [integral_domain D] [unique_factorization_monoid D] @[priority 100] instance unique_factorization_monoid : unique_factorization_monoid (polynomial D) := begin haveI := arbitrary (normalization_monoid D), haveI := to_gcd_monoid D, exact ufm_of_gcd_of_wf_dvd_monoid end end polynomial
154b59e67bc8bf26b41b46d06dd2564955b42ee7
3dd1b66af77106badae6edb1c4dea91a146ead30
/library/hott/prop.lean
01e520b6d6480a761dbb20563e9f31f6ae8576cf
[ "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
311
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 definition is_prop (A : Type) := Π (x y : A), x = y inductive hprop : Type := | hprop_intro : Π (A : Type), is_prop A → hprop
f86fdda8c79d79426b4089573a49bd07ab850300
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/complex/liouville.lean
aa2b6a8ae40ebcdbc1b555bbe6fb2ee37ffe41f0
[ "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,824
lean
/- Copyright (c) 2022 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.complex.cauchy_integral import analysis.calculus.fderiv_analytic import analysis.normed_space.completion /-! # Liouville's theorem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove Liouville's theorem: if `f : E → F` is complex differentiable on the whole space and its range is bounded, then the function is a constant. Various versions of this theorem are formalized in `differentiable.apply_eq_apply_of_bounded`, `differentiable.exists_const_forall_eq_of_bounded`, and `differentiable.exists_eq_const_of_bounded`. The proof is based on the Cauchy integral formula for the derivative of an analytic function, see `complex.deriv_eq_smul_circle_integral`. -/ open topological_space metric set filter asymptotics function measure_theory open_locale topology filter nnreal real universes u v variables {E : Type u} [normed_add_comm_group E] [normed_space ℂ E] {F : Type v} [normed_add_comm_group F] [normed_space ℂ F] local postfix `̂`:100 := uniform_space.completion namespace complex /-- If `f` is complex differentiable on an open disc with center `c` and radius `R > 0` and is continuous on its closure, then `f' c` can be represented as an integral over the corresponding circle. TODO: add a version for `w ∈ metric.ball c R`. TODO: add a version for higher derivatives. -/ lemma deriv_eq_smul_circle_integral [complete_space F] {R : ℝ} {c : ℂ} {f : ℂ → F} (hR : 0 < R) (hf : diff_cont_on_cl ℂ f (ball c R)) : deriv f c = (2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - c) ^ (-2 : ℤ) • f z := begin lift R to ℝ≥0 using hR.le, refine (hf.has_fpower_series_on_ball hR).has_fpower_series_at.deriv.trans _, simp only [cauchy_power_series_apply, one_div, zpow_neg, pow_one, smul_smul, zpow_two, mul_inv] end lemma norm_deriv_le_aux [complete_space F] {c : ℂ} {R C : ℝ} {f : ℂ → F} (hR : 0 < R) (hf : diff_cont_on_cl ℂ f (ball c R)) (hC : ∀ z ∈ sphere c R, ‖f z‖ ≤ C) : ‖deriv f c‖ ≤ C / R := begin have : ∀ z ∈ sphere c R, ‖(z - c) ^ (-2 : ℤ) • f z‖ ≤ C / (R * R), from λ z (hz : abs (z - c) = R), by simpa [-mul_inv_rev, norm_smul, hz, zpow_two, ←div_eq_inv_mul] using (div_le_div_right (mul_pos hR hR)).2 (hC z hz), calc ‖deriv f c‖ = ‖(2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - c) ^ (-2 : ℤ) • f z‖ : congr_arg norm (deriv_eq_smul_circle_integral hR hf) ... ≤ R * (C / (R * R)) : circle_integral.norm_two_pi_I_inv_smul_integral_le_of_norm_le_const hR.le this ... = C / R : by rw [mul_div_left_comm, div_self_mul_self', div_eq_mul_inv] end /-- If `f` is complex differentiable on an open disc of radius `R > 0`, is continuous on its closure, and its values on the boundary circle of this disc are bounded from above by `C`, then the norm of its derivative at the center is at most `C / R`. -/ lemma norm_deriv_le_of_forall_mem_sphere_norm_le {c : ℂ} {R C : ℝ} {f : ℂ → F} (hR : 0 < R) (hd : diff_cont_on_cl ℂ f (ball c R)) (hC : ∀ z ∈ sphere c R, ‖f z‖ ≤ C) : ‖deriv f c‖ ≤ C / R := begin set e : F →L[ℂ] F̂ := uniform_space.completion.to_complL, have : has_deriv_at (e ∘ f) (e (deriv f c)) c, from e.has_fderiv_at.comp_has_deriv_at c (hd.differentiable_at is_open_ball $ mem_ball_self hR).has_deriv_at, calc ‖deriv f c‖ = ‖deriv (e ∘ f) c‖ : by { rw this.deriv, exact (uniform_space.completion.norm_coe _).symm } ... ≤ C / R : norm_deriv_le_aux hR (e.differentiable.comp_diff_cont_on_cl hd) (λ z hz, (uniform_space.completion.norm_coe _).trans_le (hC z hz)) end /-- An auxiliary lemma for Liouville's theorem `differentiable.apply_eq_apply_of_bounded`. -/ lemma liouville_theorem_aux {f : ℂ → F} (hf : differentiable ℂ f) (hb : bounded (range f)) (z w : ℂ) : f z = f w := begin suffices : ∀ c, deriv f c = 0, from is_const_of_deriv_eq_zero hf this z w, clear z w, intro c, obtain ⟨C, C₀, hC⟩ : ∃ C > (0 : ℝ), ∀ z, ‖f z‖ ≤ C, { rcases bounded_iff_forall_norm_le.1 hb with ⟨C, hC⟩, exact ⟨max C 1, lt_max_iff.2 (or.inr zero_lt_one), λ z, (hC (f z) (mem_range_self _)).trans (le_max_left _ _)⟩ }, refine norm_le_zero_iff.1 (le_of_forall_le_of_dense $ λ ε ε₀, _), calc ‖deriv f c‖ ≤ C / (C / ε) : norm_deriv_le_of_forall_mem_sphere_norm_le (div_pos C₀ ε₀) hf.diff_cont_on_cl (λ z _, hC z) ... = ε : div_div_cancel' C₀.lt.ne' end end complex namespace differentiable open complex /-- **Liouville's theorem**: a complex differentiable bounded function `f : E → F` is a constant. -/ lemma apply_eq_apply_of_bounded {f : E → F} (hf : differentiable ℂ f) (hb : bounded (range f)) (z w : E) : f z = f w := begin set g : ℂ → F := f ∘ (λ t : ℂ, t • (w - z) + z), suffices : g 0 = g 1, by simpa [g], apply liouville_theorem_aux, exacts [hf.comp ((differentiable_id.smul_const (w - z)).add_const z), hb.mono (range_comp_subset_range _ _)] end /-- **Liouville's theorem**: a complex differentiable bounded function is a constant. -/ lemma exists_const_forall_eq_of_bounded {f : E → F} (hf : differentiable ℂ f) (hb : bounded (range f)) : ∃ c, ∀ z, f z = c := ⟨f 0, λ z, hf.apply_eq_apply_of_bounded hb _ _⟩ /-- **Liouville's theorem**: a complex differentiable bounded function is a constant. -/ lemma exists_eq_const_of_bounded {f : E → F} (hf : differentiable ℂ f) (hb : bounded (range f)) : ∃ c, f = const E c := (hf.exists_const_forall_eq_of_bounded hb).imp $ λ c, funext end differentiable
f8478499f48a0a679ad6584ebdcf9c6d075275e8
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/algebra/category/CommRing/colimits.lean
1093af8707fa2c1d8ca09a0ca773cd1329ed3802
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
12,766
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 algebra.category.CommRing.basic import category_theory.limits.limits import category_theory.limits.concrete_category /-! # The category of commutative rings has all colimits. This file uses a "pre-automated" approach, just as for `Mon/colimits.lean`. It is a very uniform approach, that conceivably could be synthesised directly by a tactic that analyses the shape of `comm_ring` and `ring_hom`. -/ universes u v open category_theory open category_theory.limits -- [ROBOT VOICE]: -- You should pretend for now that this file was automatically generated. -- It follows the same template as colimits in Mon. /- `#print comm_ring` says: structure comm_ring : Type u → Type u fields: comm_ring.zero : Π (α : Type u) [c : comm_ring α], α comm_ring.one : Π (α : Type u) [c : comm_ring α], α comm_ring.neg : Π {α : Type u} [c : comm_ring α], α → α comm_ring.add : Π {α : Type u} [c : comm_ring α], α → α → α comm_ring.mul : Π {α : Type u} [c : comm_ring α], α → α → α comm_ring.zero_add : ∀ {α : Type u} [c : comm_ring α] (a : α), 0 + a = a comm_ring.add_zero : ∀ {α : Type u} [c : comm_ring α] (a : α), a + 0 = a comm_ring.one_mul : ∀ {α : Type u} [c : comm_ring α] (a : α), 1 * a = a comm_ring.mul_one : ∀ {α : Type u} [c : comm_ring α] (a : α), a * 1 = a comm_ring.add_left_neg : ∀ {α : Type u} [c : comm_ring α] (a : α), -a + a = 0 comm_ring.add_comm : ∀ {α : Type u} [c : comm_ring α] (a b : α), a + b = b + a comm_ring.mul_comm : ∀ {α : Type u} [c : comm_ring α] (a b : α), a * b = b * a comm_ring.add_assoc : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a + b + c_1 = a + (b + c_1) comm_ring.mul_assoc : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a * b * c_1 = a * (b * c_1) comm_ring.left_distrib : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a * (b + c_1) = a * b + a * c_1 comm_ring.right_distrib : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), (a + b) * c_1 = a * c_1 + b * c_1 -/ namespace CommRing.colimits /-! We build the colimit of a diagram in `CommRing` by constructing the free commutative ring on the disjoint union of all the commutative rings in the diagram, then taking the quotient by the commutative ring laws within each commutative ring, and the identifications given by the morphisms in the diagram. -/ variables {J : Type v} [small_category J] (F : J ⥤ CommRing.{v}) /-- An inductive type representing all commutative ring expressions (without relations) on a collection of types indexed by the objects of `J`. -/ inductive prequotient -- There's always `of` | of : Π (j : J) (x : F.obj j), prequotient -- Then one generator for each operation | zero : prequotient | one : prequotient | neg : prequotient → prequotient | add : prequotient → prequotient → prequotient | mul : prequotient → prequotient → prequotient instance : inhabited (prequotient F) := ⟨prequotient.zero⟩ open prequotient /-- The relation on `prequotient` saying when two expressions are equal because of the commutative ring laws, or because one element is mapped to another by a morphism in the diagram. -/ inductive relation : prequotient F → prequotient F → Prop -- Make it an equivalence relation: | refl : Π (x), relation x x | symm : Π (x y) (h : relation x y), relation y x | trans : Π (x y z) (h : relation x y) (k : relation y z), relation x z -- There's always a `map` relation | map : Π (j j' : J) (f : j ⟶ j') (x : F.obj j), relation (of j' (F.map f x)) (of j x) -- Then one relation per operation, describing the interaction with `of` | zero : Π (j), relation (of j 0) zero | one : Π (j), relation (of j 1) one | neg : Π (j) (x : F.obj j), relation (of j (-x)) (neg (of j x)) | add : Π (j) (x y : F.obj j), relation (of j (x + y)) (add (of j x) (of j y)) | mul : Π (j) (x y : F.obj j), relation (of j (x * y)) (mul (of j x) (of j y)) -- Then one relation per argument of each operation | neg_1 : Π (x x') (r : relation x x'), relation (neg x) (neg x') | add_1 : Π (x x' y) (r : relation x x'), relation (add x y) (add x' y) | add_2 : Π (x y y') (r : relation y y'), relation (add x y) (add x y') | mul_1 : Π (x x' y) (r : relation x x'), relation (mul x y) (mul x' y) | mul_2 : Π (x y y') (r : relation y y'), relation (mul x y) (mul x y') -- And one relation per axiom | zero_add : Π (x), relation (add zero x) x | add_zero : Π (x), relation (add x zero) x | one_mul : Π (x), relation (mul one x) x | mul_one : Π (x), relation (mul x one) x | add_left_neg : Π (x), relation (add (neg x) x) zero | add_comm : Π (x y), relation (add x y) (add y x) | mul_comm : Π (x y), relation (mul x y) (mul y x) | add_assoc : Π (x y z), relation (add (add x y) z) (add x (add y z)) | mul_assoc : Π (x y z), relation (mul (mul x y) z) (mul x (mul y z)) | left_distrib : Π (x y z), relation (mul x (add y z)) (add (mul x y) (mul x z)) | right_distrib : Π (x y z), relation (mul (add x y) z) (add (mul x z) (mul y z)) /-- The setoid corresponding to commutative expressions modulo monoid relations and identifications. -/ def colimit_setoid : setoid (prequotient F) := { r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ } attribute [instance] colimit_setoid /-- The underlying type of the colimit of a diagram in `CommRing`. -/ @[derive inhabited] def colimit_type : Type v := quotient (colimit_setoid F) instance : comm_ring (colimit_type F) := { zero := begin exact quot.mk _ zero end, one := begin exact quot.mk _ one end, neg := begin fapply @quot.lift, { intro x, exact quot.mk _ (neg x) }, { intros x x' r, apply quot.sound, exact relation.neg_1 _ _ r }, end, add := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (add x y) }, { intros y y' r, apply quot.sound, exact relation.add_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.add_1 _ _ _ r }, { refl } }, end, mul := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (mul x y) }, { intros y y' r, apply quot.sound, exact relation.mul_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.mul_1 _ _ _ r }, { refl } }, end, zero_add := λ x, begin induction x, dsimp, apply quot.sound, apply relation.zero_add, refl, end, add_zero := λ x, begin induction x, dsimp, apply quot.sound, apply relation.add_zero, refl, end, one_mul := λ x, begin induction x, dsimp, apply quot.sound, apply relation.one_mul, refl, end, mul_one := λ x, begin induction x, dsimp, apply quot.sound, apply relation.mul_one, refl, end, add_left_neg := λ x, begin induction x, dsimp, apply quot.sound, apply relation.add_left_neg, refl, end, add_comm := λ x y, begin induction x, induction y, dsimp, apply quot.sound, apply relation.add_comm, refl, refl, end, mul_comm := λ x y, begin induction x, induction y, dsimp, apply quot.sound, apply relation.mul_comm, refl, refl, end, add_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.add_assoc, refl, refl, refl, end, mul_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.mul_assoc, refl, refl, refl, end, left_distrib := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.left_distrib, refl, refl, refl, end, right_distrib := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.right_distrib, refl, refl, refl, end, } @[simp] lemma quot_zero : quot.mk setoid.r zero = (0 : colimit_type F) := rfl @[simp] lemma quot_one : quot.mk setoid.r one = (1 : colimit_type F) := rfl @[simp] lemma quot_neg (x) : quot.mk setoid.r (neg x) = (-(quot.mk setoid.r x) : colimit_type F) := rfl @[simp] lemma quot_add (x y) : quot.mk setoid.r (add x y) = ((quot.mk setoid.r x) + (quot.mk setoid.r y) : colimit_type F) := rfl @[simp] lemma quot_mul (x y) : quot.mk setoid.r (mul x y) = ((quot.mk setoid.r x) * (quot.mk setoid.r y) : colimit_type F) := rfl /-- The bundled commutative ring giving the colimit of a diagram. -/ def colimit : CommRing := CommRing.of (colimit_type F) /-- The function from a given commutative ring in the diagram to the colimit commutative ring. -/ def cocone_fun (j : J) (x : F.obj j) : colimit_type F := quot.mk _ (of j x) /-- The ring homomorphism from a given commutative ring in the diagram to the colimit commutative ring. -/ def cocone_morphism (j : J) : F.obj j ⟶ colimit F := { to_fun := cocone_fun F j, map_one' := by apply quot.sound; apply relation.one, map_mul' := by intros; apply quot.sound; apply relation.mul, map_zero' := by apply quot.sound; apply relation.zero, map_add' := by intros; apply quot.sound; apply relation.add } @[simp] lemma cocone_naturality {j j' : J} (f : j ⟶ j') : F.map f ≫ (cocone_morphism F j') = cocone_morphism F j := begin ext, apply quot.sound, apply relation.map, end @[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟶ j') (x : F.obj j): (cocone_morphism F j') (F.map f x) = (cocone_morphism F j) x := by { rw ←cocone_naturality F f, refl } /-- The cocone over the proposed colimit commutative ring. -/ def colimit_cocone : cocone F := { X := colimit F, ι := { app := cocone_morphism F } }. /-- The function from the free commutative ring on the diagram to the cone point of any other cocone. -/ @[simp] def desc_fun_lift (s : cocone F) : prequotient F → s.X | (of j x) := (s.ι.app j) x | zero := 0 | one := 1 | (neg x) := -(desc_fun_lift x) | (add x y) := desc_fun_lift x + desc_fun_lift y | (mul x y) := desc_fun_lift x * desc_fun_lift y /-- The function from the colimit commutative ring to the cone point of any other cocone. -/ def desc_fun (s : cocone F) : colimit_type F → s.X := begin fapply quot.lift, { exact desc_fun_lift F s }, { intros x y r, induction r; try { dsimp }, -- refl { refl }, -- symm { exact r_ih.symm }, -- trans { exact eq.trans r_ih_h r_ih_k }, -- map { simp, }, -- zero { simp, }, -- one { simp, }, -- neg { simp, }, -- add { simp, }, -- mul { simp, }, -- neg_1 { rw r_ih, }, -- add_1 { rw r_ih, }, -- add_2 { rw r_ih, }, -- mul_1 { rw r_ih, }, -- mul_2 { rw r_ih, }, -- zero_add { rw zero_add, }, -- add_zero { rw add_zero, }, -- one_mul { rw one_mul, }, -- mul_one { rw mul_one, }, -- add_left_neg { rw add_left_neg, }, -- add_comm { rw add_comm, }, -- mul_comm { rw mul_comm, }, -- add_assoc { rw add_assoc, }, -- mul_assoc { rw mul_assoc, }, -- left_distrib { rw left_distrib, }, -- right_distrib { rw right_distrib, }, } end /-- The ring homomorphism from the colimit commutative ring to the cone point of any other cocone. -/ def desc_morphism (s : cocone F) : colimit F ⟶ s.X := { to_fun := desc_fun F s, map_one' := rfl, map_zero' := rfl, map_add' := λ x y, by { induction x; induction y; refl }, map_mul' := λ x y, by { induction x; induction y; refl }, } /-- Evidence that the proposed colimit is the colimit. -/ def colimit_is_colimit : is_colimit (colimit_cocone F) := { desc := λ s, desc_morphism F s, uniq' := λ s m w, begin ext, induction x, induction x, { have w' := congr_fun (congr_arg (λ f : F.obj x_j ⟶ s.X, (f : F.obj x_j → s.X)) (w x_j)) x_x, erw w', refl, }, { simp, }, { simp, }, { simp *, }, { simp *, }, { simp *, }, refl end }. instance has_colimits_CommRing : has_colimits CommRing := { has_colimits_of_shape := λ J 𝒥, { has_colimit := λ F, by exactI { cocone := colimit_cocone F, is_colimit := colimit_is_colimit F } } } end CommRing.colimits
6f699769e42ca9739daf5ac1812dcd17250b961d
d31b9f832ff922a603f76cf32e0f3aa822640508
/src/hott/hit/trunc.lean
94c8a1abaea3bda2a0f7286aa2c8a04f6535f2ba
[ "Apache-2.0" ]
permissive
javra/hott3
6e7a9e72a991a2fae32e5764982e521dca617b16
cd51f2ab2aa48c1246a188f9b525b30f76c3d651
refs/heads/master
1,585,819,679,148
1,531,232,382,000
1,536,682,965,000
154,294,022
0
0
Apache-2.0
1,540,284,376,000
1,540,284,375,000
null
UTF-8
Lean
false
false
6,073
lean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn n-truncation of types. Ported from Coq HoTT -/ /- The hit n-truncation is primitive, declared in init.hit. -/ import hott.types.sigma hott.types.pointed universes u v w hott_theory namespace hott open hott.is_trunc hott.eq hott.equiv hott.is_equiv function prod sum sigma namespace trunc @[hott, induction, priority 1500] protected def elim {n : ℕ₋₂} {A : Type _} {P : Type _} [Pt : is_trunc n P] (H : A → P) : trunc n A → P := trunc.rec H @[hott] protected def elim_on {n : ℕ₋₂} {A : Type _} {P : Type _} (aa : trunc n A) [Pt : is_trunc n P] (H : A → P) : P := trunc.elim H aa variables {X : Type _} {Y : Type _} {Z : Type _} {P : X → Type _} {m : ℕ₋₂} (n : ℕ₋₂) (A : Type _) (B : Type _) @[hott] def untrunc_of_is_trunc [H : is_trunc m X] : trunc m X → X := trunc.rec id variables (A n) @[hott, instance] def is_equiv_tr [H : is_trunc n A] : is_equiv (@tr n A) := adjointify _ (untrunc_of_is_trunc) (λaa, trunc.rec_on aa (λa, idp)) (λa, idp) @[hott] def trunc_equiv [H : is_trunc n A] : trunc n A ≃ A := (equiv.mk tr (is_equiv_tr n A))⁻¹ᵉ @[hott] def is_trunc_of_is_equiv_tr [H : is_equiv (@tr n A)] : is_trunc n A := is_trunc_is_equiv_closed_rev n (@tr n A) (by infer) /- Functoriality -/ @[hott] def trunc_functor (f : X → Y) : trunc n X → trunc n Y := λxx, trunc.rec_on xx (λx, tr (f x)) @[hott] def trunc_functor_compose (g : Y → Z) (f : X → Y) : trunc_functor n (g ∘ f) ~ trunc_functor n g ∘ trunc_functor n f := λxx, trunc.rec_on xx (λx, idp) @[hott] def trunc_functor_id : trunc_functor n (@id A) ~ id := λxx, trunc.rec_on xx (λx, idp) @[hott] def trunc_functor_cast {X Y : Type _} (n : ℕ₋₂) (p : X = Y) : trunc_functor n (cast p) ~ cast (ap (trunc n) p) := begin intro x, hinduction x using trunc.rec with x, exact fn_tr_eq_tr_fn p (λy, tr) x ⬝ tr_eq_cast_ap _ _ end @[hott] def is_equiv_trunc_functor (f : X → Y) [H : is_equiv f] : is_equiv (trunc_functor n f) := adjointify _ (trunc_functor n f⁻¹ᶠ) (λyy, trunc.rec_on yy (λy, ap tr (right_inv _ _))) (λxx, trunc.rec_on xx (λx, ap tr (left_inv _ _))) @[hott] def trunc_homotopy {f g : X → Y} (p : f ~ g) : trunc_functor n f ~ trunc_functor n g := λxx, trunc.rec_on xx (λx, ap tr (p x)) section @[hott] def trunc_equiv_trunc (f : X ≃ Y) : trunc n X ≃ trunc n Y := equiv.mk _ (is_equiv_trunc_functor n f) end section @[hott] def trunc_prod_equiv : trunc n (X × Y) ≃ trunc n X × trunc n Y := begin fapply equiv.MK, { exact (λpp, trunc.rec_on pp (λp, (tr p.1, tr p.2))) }, { intro p, induction p with xx yy, hinduction xx with x, hinduction yy with y, exact tr (x,y) }, { intro p, induction p with xx yy, hinduction xx with x, hinduction yy with y, refl }, { intro pp, hinduction pp with p, induction p, refl } end end /- Propositional truncation -/ @[hott] def ttrunc (n : ℕ₋₂) (X : Type _) : n-Type := trunctype.mk (trunc n X) (by infer) @[hott, hsimp] def carrier_ttrunc (n : ℕ₋₂) (X : Type _) : @coe_sort _ (hott.has_coe_to_sort n) (ttrunc n X) = trunc n X := by refl @[hott, reducible] def merely (A : Type _) : Prop := ttrunc -1 A notation `∥`:max A `∥`:0 := merely A @[hott, reducible] def Exists (P : X → Type _) : Prop := ∥ sigma P ∥ @[hott, reducible] def or (A B : Type _) : Prop := ∥ A ⊎ B ∥ hott_theory_cmd "local notation `exists` binders `,` r:(scoped P, hott.trunc.Exists P) := r" hott_theory_cmd "local notation `∃` binders `,` r:(scoped P, hott.trunc.Exists P) := r" hott_theory_cmd "local notation [parsing_only] A ` \\/ ` B := hott.trunc.or A B" hott_theory_cmd "local notation A ∨ B := hott.trunc.or A B" @[hott, reducible] def merely.intro (a : A) : ∥ A ∥ := tr a @[hott, reducible] def exists.intro (x : X) (p : P x) : ∃x, P x := tr ⟨x, p⟩ @[hott, reducible] def or.intro_left (x : X) : X ∨ Y := tr (inl x) @[hott, reducible] def or.intro_right (y : Y) : X ∨ Y := tr (inr y) -- to do: give induction attribute @[hott] def merely.rec {A : Type u} {P : ∥A∥ → Type v} [Pt : Π (aa : ∥A∥), is_prop (P aa)] (H : Π(a : A), P (tr a)) (x : ∥A∥) : P x := begin hinduction x with a, exact H a end -- to do: give induction attribute @[hott] def exists.elim {A : Type _} {p : A → Type _} {B : Type _} [is_prop B] (H : Exists p) (H' : ∀ (a : A), p a → B) : B := begin hinduction H with x, induction x with a x, exact H' a x end @[hott] def is_contr_of_merely_prop [H : is_prop A] (aa : merely A) : is_contr A := is_contr_of_inhabited_prop (trunc.rec_on aa id) @[hott] def trunc_sigma_equiv : trunc n (Σ x, P x) ≃ trunc n (Σ x, trunc n (P x)) := begin fapply equiv.MK; intro x, { hinduction x with p, exact tr ⟨p.1, tr p.2⟩ }, { hinduction x with p, induction p with a p, hinduction p with p, exact tr ⟨a, p⟩ }, { hinduction x with p, induction p with a p, hinduction p with p, refl }, { hinduction x with p, induction p with a p, refl } end @[hott] def trunc_sigma_equiv_of_is_trunc [H : is_trunc n X] : trunc n (Σ x, P x) ≃ Σ x, trunc n (P x) := calc trunc n (Σ x, P x) ≃ trunc n (Σ x, trunc n (P x)) : trunc_sigma_equiv _ ... ≃ Σ x, trunc n (P x) : trunc_equiv _ _ /- the (non-dependent) universal property -/ @[hott] def trunc_arrow_equiv [H : is_trunc n B] : (trunc n A → B) ≃ (A → B) := begin fapply equiv.MK, { intros g a, exact g (tr a) }, { intros f x, hinduction x with a, exact f a }, { intro f, apply eq_of_homotopy, intro a, refl }, { intro g, apply eq_of_homotopy, intro x, hinduction x, refl }, end end trunc end hott
be5003bfd8f8ef27f6ba9d6fe1b161793f812dfc
1446f520c1db37e157b631385707cc28a17a595e
/src/Init/Lean/Meta/AppBuilder.lean
2bb34dbf8f02b11c23045f7ef721331b2c7d0624
[ "Apache-2.0" ]
permissive
bdbabiak/lean4
cab06b8a2606d99a168dd279efdd404edb4e825a
3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac
refs/heads/master
1,615,045,275,530
1,583,793,696,000
1,583,793,696,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,912
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Init.Lean.Meta.SynthInstance namespace Lean @[inline] def Expr.eq? (p : Expr) : Option (Expr × Expr × Expr) := if p.isAppOfArity `Eq 3 then some (p.getArg! 0, p.getArg! 1, p.getArg! 2) else none @[inline] def Expr.iff? (p : Expr) : Option (Expr × Expr) := if p.isAppOfArity `Iff 2 then some (p.getArg! 0, p.getArg! 1) else none @[inline] def Expr.heq? (p : Expr) : Option (Expr × Expr × Expr × Expr) := if p.isAppOfArity `HEq 4 then some (p.getArg! 0, p.getArg! 1, p.getArg! 2, p.getArg! 4) else none @[inline] def Expr.arrow? : Expr → Option (Expr × Expr) | Expr.forallE _ α β _ => if β.hasLooseBVars then none else some (α, β) | _ => none namespace Meta def mkEq (a b : Expr) : MetaM Expr := do aType ← inferType a; u ← getLevel aType; pure $ mkApp3 (mkConst `Eq [u]) aType a b def mkHEq (a b : Expr) : MetaM Expr := do aType ← inferType a; bType ← inferType b; u ← getLevel aType; pure $ mkApp4 (mkConst `HEq [u]) aType a bType b def mkEqRefl (a : Expr) : MetaM Expr := do aType ← inferType a; u ← getLevel aType; pure $ mkApp2 (mkConst `Eq.refl [u]) aType a def mkHEqRefl (a : Expr) : MetaM Expr := do aType ← inferType a; u ← getLevel aType; pure $ mkApp2 (mkConst `HEq.refl [u]) aType a private def infer (h : Expr) : MetaM Expr := do hType ← inferType h; whnfD hType def mkEqSymm (h : Expr) : MetaM Expr := if h.isAppOf `Eq.refl then pure h else do hType ← infer h; match hType.eq? with | some (α, a, b) => do u ← getLevel α; pure $ mkApp4 (mkConst `Eq.symm [u]) α a b h | none => throwEx $ Exception.appBuilder `Eq.symm "equality proof expected" #[h] def mkEqTrans (h₁ h₂ : Expr) : MetaM Expr := if h₁.isAppOf `Eq.refl then pure h₂ else if h₂.isAppOf `Eq.refl then pure h₁ else do hType₁ ← infer h₁; hType₂ ← infer h₂; match hType₁.eq?, hType₂.eq? with | some (α, a, b), some (_, _, c) => do u ← getLevel α; pure $ mkApp6 (mkConst `Eq.trans [u]) α a b c h₁ h₂ | _, _ => throwEx $ Exception.appBuilder `Eq.trans "equality proof expected" #[h₁, h₂] def mkHEqSymm (h : Expr) : MetaM Expr := if h.isAppOf `HEq.refl then pure h else do hType ← infer h; match hType.heq? with | some (α, a, β, b) => do u ← getLevel α; pure $ mkApp5 (mkConst `HEq.symm [u]) α β a b h | none => throwEx $ Exception.appBuilder `HEq.symm "heterogeneous equality proof expected" #[h] def mkHEqTrans (h₁ h₂ : Expr) : MetaM Expr := if h₁.isAppOf `HEq.refl then pure h₂ else if h₂.isAppOf `HEq.refl then pure h₁ else do hType₁ ← infer h₁; hType₂ ← infer h₂; match hType₁.heq?, hType₂.heq? with | some (α, a, β, b), some (_, _, γ, c) => do u ← getLevel α; pure $ mkApp8 (mkConst `HEq.trans [u]) α β γ a b c h₁ h₂ | _, _ => throwEx $ Exception.appBuilder `HEq.trans "heterogeneous equality proof expected" #[h₁, h₂] def mkEqOfHEq (h : Expr) : MetaM Expr := do hType ← infer h; match hType.heq? with | some (α, a, β, b) => do unlessM (isDefEq α β) $ throwEx $ Exception.appBuilder `eqOfHEq "heterogeneous equality types are not definitionally equal" #[α, β]; u ← getLevel α; pure $ mkApp4 (mkConst `eqOfHEq [u]) α a b h | _ => throwEx $ Exception.appBuilder `HEq.trans "heterogeneous equality proof expected" #[h] def mkCongrArg (f h : Expr) : MetaM Expr := do hType ← infer h; fType ← infer f; match fType.arrow?, hType.eq? with | some (α, β), some (_, a, b) => do u ← getLevel α; v ← getLevel β; pure $ mkApp6 (mkConst `congrArg [u, v]) α β a b f h | none, _ => throwEx $ Exception.appBuilder `congrArg "non-dependent function expected" #[f, h] | _, none => throwEx $ Exception.appBuilder `congrArg "equality proof expected" #[f, h] def mkCongrFun (h a : Expr) : MetaM Expr := do hType ← infer h; match hType.eq? with | some (ρ, f, g) => do ρ ← whnfD ρ; match ρ with | Expr.forallE n α β _ => do let β' := Lean.mkLambda n BinderInfo.default α β; u ← getLevel α; v ← getLevel (mkApp β' a); pure $ mkApp6 (mkConst `congrFun [u, v]) α β' f g h a | _ => throwEx $ Exception.appBuilder `congrFun "equality proof between functions expected" #[h, a] | _ => throwEx $ Exception.appBuilder `congrFun "equality proof expected" #[h, a] def mkCongr (h₁ h₂ : Expr) : MetaM Expr := do hType₁ ← infer h₁; hType₂ ← infer h₂; match hType₁.eq?, hType₂.eq? with | some (ρ, f, g), some (α, a, b) => do ρ ← whnfD ρ; match ρ.arrow? with | some (_, β) => do u ← getLevel α; v ← getLevel β; pure $ mkApp8 (mkConst `congr [u, v]) α β f g a b h₁ h₂ | _ => throwEx $ Exception.appBuilder `congr "non-dependent function expected" #[h₁, h₂] | _, _ => throwEx $ Exception.appBuilder `congr "equality proof expected" #[h₁, h₂] private def mkAppMFinal (f : Expr) (args : Array Expr) (instMVars : Array MVarId) : MetaM Expr := do instMVars.forM $ fun mvarId => do { mvarDecl ← getMVarDecl mvarId; mvarVal ← synthInstance mvarDecl.type; assignExprMVar mvarId mvarVal }; result ← instantiateMVars (mkAppN f args); whenM (hasAssignableMVar result) $ throwEx $ Exception.appBuilder `mkAppM "result contains metavariables" #[result]; pure result private partial def mkAppMAux (f : Expr) (xs : Array Expr) : Nat → Array Expr → Nat → Array MVarId → Expr → MetaM Expr | i, args, j, instMVars, Expr.forallE n d b c => do let d := d.instantiateRevRange j args.size args; match c.binderInfo with | BinderInfo.implicit => do mvar ← mkFreshExprMVar d n; mkAppMAux i (args.push mvar) j instMVars b | BinderInfo.instImplicit => do mvar ← mkFreshExprMVar d n MetavarKind.synthetic; mkAppMAux i (args.push mvar) j (instMVars.push mvar.mvarId!) b | _ => if h : i < xs.size then do let x := xs.get ⟨i, h⟩; xType ← inferType x; condM (isDefEq d xType) (mkAppMAux (i+1) (args.push x) j instMVars b) (throwEx $ Exception.appTypeMismatch (mkAppN f args) x) else mkAppMFinal f args instMVars | i, args, j, instMVars, type => do let type := type.instantiateRevRange j args.size args; type ← whnfD type; if type.isForall then mkAppMAux i args args.size instMVars type else if i == xs.size then mkAppMFinal f args instMVars else throwEx $ Exception.appBuilder `mkAppM "too many explicit arguments provided" (#[f] ++ xs) def mkAppM (constName : Name) (xs : Array Expr) : MetaM Expr := traceCtx `Meta.appBuilder $ withNewMCtxDepth $ do cinfo ← getConstInfo constName; us ← cinfo.lparams.mapM $ fun _ => mkFreshLevelMVar; let f := mkConst constName us; let fType := cinfo.instantiateTypeLevelParams us; mkAppMAux f xs 0 #[] 0 #[] fType def mkEqNDRec (motive h1 h2 : Expr) : MetaM Expr := if h2.isAppOf `Eq.refl then pure h1 else do h2Type ← infer h2; match h2Type.eq? with | none => throwEx $ Exception.appBuilder `Eq.ndrec "equality proof expected" #[h2] | some (α, a, b) => do u2 ← getLevel α; motiveType ← infer motive; match motiveType with | Expr.forallE _ _ (Expr.sort u1 _) _ => pure $ mkAppN (mkConst `Eq.ndrec [u1, u2]) #[α, a, motive, h1, b, h2] | _ => throwEx $ Exception.appBuilder `Eq.ndrec "invalid motive" #[motive] def mkEqRec (motive h1 h2 : Expr) : MetaM Expr := if h2.isAppOf `Eq.refl then pure h1 else do h2Type ← infer h2; match h2Type.eq? with | none => throwEx $ Exception.appBuilder `Eq.rec "equality proof expected" #[h2] | some (α, a, b) => do u2 ← getLevel α; motiveType ← infer motive; match motiveType with | Expr.forallE _ _ (Expr.forallE _ _ (Expr.sort u1 _) _) _ => pure $ mkAppN (mkConst `Eq.rec [u1, u2]) #[α, a, motive, h1, b, h2] | _ => throwEx $ Exception.appBuilder `Eq.rec "invalid motive" #[motive] def mkEqMP (eqProof pr : Expr) : MetaM Expr := mkAppM `Eq.mp #[eqProof, pr] def mkEqMPR (eqProof pr : Expr) : MetaM Expr := mkAppM `Eq.mpr #[eqProof, pr] def mkNoConfusion (target : Expr) (h : Expr) : MetaM Expr := do type ← inferType h; type ← whnf type; match type.eq? with | none => throwEx $ Exception.appBuilder `noConfusion "equality expected" #[h] | some (α, a, b) => do α ← whnf α; env ← getEnv; let f := α.getAppFn; matchConst env f (fun _ => throwEx $ Exception.appBuilder `noConfusion "inductive type expected" #[α]) $ fun cinfo us => match cinfo with | ConstantInfo.inductInfo v => do u ← getLevel target; pure $ mkAppN (mkConst (mkNameStr v.name "noConfusion") (u :: us)) (α.getAppArgs ++ #[target, a, b, h]) | _ => throwEx $ Exception.appBuilder `noConfusion "inductive type expected" #[α] end Meta end Lean
e77c0dfe782f531fdd622e3a1881bd218343dbdd
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Meta/ExprDefEq.lean
bb57345edba23e06a3fc2baf0f1a782920bc0cab
[ "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
77,343
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Offset import Lean.Meta.UnificationHint import Lean.Util.OccursCheck namespace Lean.Meta /-- Return true if `b` is of the form `mk a.1 ... a.n`, and `a` is not a constructor application. If `a` and `b` are constructor applications, the method returns `false` to force `isDefEq` to use `isDefEqArgs`. For example, suppose we are trying to solve the constraint ``` Fin.mk ?n ?h =?= Fin.mk n h ``` If this method is applied, the constraints are reduced to ``` n =?= (Fin.mk ?n ?h).1 h =?= (Fin.mk ?n ?h).2 ``` The first constraint produces the assignment `?n := n`. Then, the second constraint is solved using proof irrelevance without assigning `?h`. TODO: investigate better solutions for the proof irrelevance issue. The problem above can happen is other scenarios. That is, proof irrelevance may prevent us from performing desired mvar assignments. -/ private def isDefEqEtaStruct (a b : Expr) : MetaM Bool := do matchConstCtor b.getAppFn (fun _ => return false) fun ctorVal us => do if (← useEtaStruct ctorVal.induct) then matchConstCtor a.getAppFn (fun _ => go ctorVal us) fun _ _ => return false else return false where go ctorVal us := do if ctorVal.numParams + ctorVal.numFields != b.getAppNumArgs then trace[Meta.isDefEq.eta.struct] "failed, insufficient number of arguments at{indentExpr b}" return false else if !isStructureLike (← getEnv) ctorVal.induct then trace[Meta.isDefEq.eta.struct] "failed, type is not a structure{indentExpr b}" return false else if (← isDefEq (← inferType a) (← inferType b)) then checkpointDefEq do let args := b.getAppArgs let params := args[:ctorVal.numParams].toArray for i in [ctorVal.numParams : args.size] do let j := i - ctorVal.numParams let proj ← mkProjFn ctorVal us params j a trace[Meta.isDefEq.eta.struct] "{a} =?= {b} @ [{j}], {proj} =?= {args[i]!}" unless (← isDefEq proj args[i]!) do trace[Meta.isDefEq.eta.struct] "failed, unexpect arg #{i}, projection{indentExpr proj}\nis not defeq to{indentExpr args[i]!}" return false return true else return false /-- Try to solve `a := (fun x => t) =?= b` by eta-expanding `b`. Remark: eta-reduction is not a good alternative even in a system without universe cumulativity like Lean. Example: ``` (fun x : A => f ?m) =?= f ``` The left-hand side of the constraint above it not eta-reduced because `?m` is a metavariable. -/ private def isDefEqEta (a b : Expr) : MetaM Bool := do if a.isLambda && !b.isLambda then let bType ← inferType b let bType ← whnfD bType match bType with | Expr.forallE n d _ c => let b' := mkLambda n c d (mkApp b (mkBVar 0)) checkpointDefEq <| Meta.isExprDefEqAux a b' | _ => pure false else return false /-- Support for `Lean.reduceBool` and `Lean.reduceNat` -/ def isDefEqNative (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t let s? ← reduceNative? s let t? ← reduceNative? t match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for reducing Nat basic operations. -/ def isDefEqNat (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t if s.hasFVar || s.hasMVar || t.hasFVar || t.hasMVar then pure LBool.undef else let s? ← reduceNat? s let t? ← reduceNat? t match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for constraints of the form `("..." =?= String.mk cs)` -/ def isDefEqStringLit (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t if s.isStringLit && t.isAppOf ``String.mk then isDefEq s.toCtorIfLit t else if s.isAppOf `String.mk && t.isStringLit then isDefEq s t.toCtorIfLit else pure LBool.undef /-- Return `true` if `e` is of the form `fun (x_1 ... x_n) => ?m x_1 ... x_n)`, and `?m` is unassigned. Remark: `n` may be 0. -/ def isEtaUnassignedMVar (e : Expr) : MetaM Bool := do match e.etaExpanded? with | some (Expr.mvar mvarId) => if (← mvarId.isReadOnlyOrSyntheticOpaque) then pure false else if (← mvarId.isAssigned) then pure false else pure true | _ => pure false private def trySynthPending (e : Expr) : MetaM Bool := do let mvarId? ← getStuckMVar? e match mvarId? with | some mvarId => Meta.synthPending mvarId | none => pure false /-- Result type for `isDefEqArgsFirstPass`. -/ inductive DefEqArgsFirstPassResult where /-- Failed to establish that explicit arguments are def-eq. Remark: higher output parameters, and parameters that depend on them are postponed. -/ | failed /-- Succeeded. The array `postponedImplicit` contains the position of the implicit arguments for which def-eq has been postponed. `postponedHO` contains the higher order output parameters, and parameters that depend on them. They should be processed after the implict ones. `postponedHO` is used to handle applications involving functions that contain higher order output parameters. Example: ```lean getElem : {cont : Type u_1} → {idx : Type u_2} → {elem : Type u_3} → {dom : cont → idx → Prop} → [self : GetElem cont idx elem dom] → (xs : cont) → (i : idx) → (h : dom xs i) → elem ``` The argumengs `dom` and `h` must be processed after all implicit arguments otherwise higher-order unification problems are generated. See issue #1299, when trying to solve ``` getElem ?a ?i ?h =?= getElem a i (Fin.val_lt_of_le i ...) ``` we have to solve the constraint ``` ?dom a i.val =?= LT.lt i.val (Array.size a) ``` by solving after the instance has been synthesized, we reduce this constraint to a simple check. -/ | ok (postponedImplicit : Array Nat) (postponedHO : Array Nat) /-- First pass for `isDefEqArgs`. We unify explicit arguments, *and* easy cases Here, we say a case is easy if it is of the form ?m =?= t or t =?= ?m where `?m` is unassigned. These easy cases are not just an optimization. When `?m` is a function, by assigning it to t, we make sure a unification constraint (in the explicit part) ``` ?m t =?= f s ``` is not higher-order. We also handle the eta-expanded cases: ``` fun x₁ ... xₙ => ?m x₁ ... xₙ =?= t t =?= fun x₁ ... xₙ => ?m x₁ ... xₙ ``` This is important because type inference often produces eta-expanded terms, and without this extra case, we could introduce counter intuitive behavior. Pre: `paramInfo.size <= args₁.size = args₂.size` See `DefEqArgsFirstPassResult` for additional information. -/ private def isDefEqArgsFirstPass (paramInfo : Array ParamInfo) (args₁ args₂ : Array Expr) : MetaM DefEqArgsFirstPassResult := do let mut postponedImplicit := #[] let mut postponedHO := #[] for i in [:paramInfo.size] do let info := paramInfo[i]! let a₁ := args₁[i]! let a₂ := args₂[i]! if info.dependsOnHigherOrderOutParam || info.higherOrderOutParam then trace[Meta.isDefEq] "found messy {a₁} =?= {a₂}" postponedHO := postponedHO.push i else if info.isExplicit then unless (← Meta.isExprDefEqAux a₁ a₂) do return .failed else if (← isEtaUnassignedMVar a₁ <||> isEtaUnassignedMVar a₂) then unless (← Meta.isExprDefEqAux a₁ a₂) do return .failed else postponedImplicit := postponedImplicit.push i return .ok postponedImplicit postponedHO private partial def isDefEqArgs (f : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := do unless args₁.size == args₂.size do return false let finfo ← getFunInfoNArgs f args₁.size let .ok postponedImplicit postponedHO ← isDefEqArgsFirstPass finfo.paramInfo args₁ args₂ | pure false -- finfo.paramInfo.size may be smaller than args₁.size for i in [finfo.paramInfo.size:args₁.size] do unless (← Meta.isExprDefEqAux args₁[i]! args₂[i]!) do return false for i in postponedImplicit do /- Second pass: unify implicit arguments. In the second pass, we make sure we are unfolding at least non reducible definitions (default setting). -/ let a₁ := args₁[i]! let a₂ := args₂[i]! let info := finfo.paramInfo[i]! if info.isInstImplicit then discard <| trySynthPending a₁ discard <| trySynthPending a₂ unless (← withAtLeastTransparency TransparencyMode.default <| Meta.isExprDefEqAux a₁ a₂) do return false for i in postponedHO do let a₁ := args₁[i]! let a₂ := args₂[i]! let info := finfo.paramInfo[i]! if info.isInstImplicit then unless (← withAtLeastTransparency TransparencyMode.default <| Meta.isExprDefEqAux a₁ a₂) do return false else unless (← Meta.isExprDefEqAux a₁ a₂) do return false return true /-- Check whether the types of the free variables at `fvars` are definitionally equal to the types at `ds₂`. Pre: `fvars.size == ds₂.size` This method also updates the set of local instances, and invokes the continuation `k` with the updated set. We can't use `withNewLocalInstances` because the `isDeq fvarType d₂` may use local instances. -/ @[specialize] partial def isDefEqBindingDomain (fvars : Array Expr) (ds₂ : Array Expr) (k : MetaM Bool) : MetaM Bool := let rec loop (i : Nat) := do if h : i < fvars.size then do let fvar := fvars.get ⟨i, h⟩ let fvarDecl ← getFVarLocalDecl fvar let fvarType := fvarDecl.type let d₂ := ds₂[i]! if (← Meta.isExprDefEqAux fvarType d₂) then match (← isClass? fvarType) with | some className => withNewLocalInstance className fvar <| loop (i+1) | none => loop (i+1) else pure false else k loop 0 /-- Auxiliary function for `isDefEqBinding` for handling binders `forall/fun`. It accumulates the new free variables in `fvars`, and declare them at `lctx`. We use the domain types of `e₁` to create the new free variables. We store the domain types of `e₂` at `ds₂`. -/ private partial def isDefEqBindingAux (lctx : LocalContext) (fvars : Array Expr) (e₁ e₂ : Expr) (ds₂ : Array Expr) : MetaM Bool := let process (n : Name) (d₁ d₂ b₁ b₂ : Expr) : MetaM Bool := do let d₁ := d₁.instantiateRev fvars let d₂ := d₂.instantiateRev fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLocalDecl fvarId n d₁ let fvars := fvars.push (mkFVar fvarId) isDefEqBindingAux lctx fvars b₁ b₂ (ds₂.push d₂) match e₁, e₂ with | Expr.forallE n d₁ b₁ _, Expr.forallE _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | Expr.lam n d₁ b₁ _, Expr.lam _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | _, _ => withReader (fun ctx => { ctx with lctx := lctx }) do isDefEqBindingDomain fvars ds₂ do Meta.isExprDefEqAux (e₁.instantiateRev fvars) (e₂.instantiateRev fvars) @[inline] private def isDefEqBinding (a b : Expr) : MetaM Bool := do let lctx ← getLCtx isDefEqBindingAux lctx #[] a b #[] private def checkTypesAndAssign (mvar : Expr) (v : Expr) : MetaM Bool := withTraceNode `Meta.isDefEq.assign.checkTypes (return m!"{exceptBoolEmoji ·} ({mvar} : {← inferType mvar}) := ({v} : {← inferType v})") do if !mvar.isMVar then trace[Meta.isDefEq.assign.checkTypes] "metavariable expected" return false else -- must check whether types are definitionally equal or not, before assigning and returning true let mvarType ← inferType mvar let vType ← inferType v if (← withTransparency TransparencyMode.default <| Meta.isExprDefEqAux mvarType vType) then mvar.mvarId!.assign v pure true else pure false /-- Auxiliary method for solving constraints of the form `?m xs := v`. It creates a lambda using `mkLambdaFVars ys v`, where `ys` is a superset of `xs`. `ys` is often equal to `xs`. It is a bigger when there are let-declaration dependencies in `xs`. For example, suppose we have `xs` of the form `#[a, c]` where ``` a : Nat b : Nat := f a c : b = a ``` In this scenario, the type of `?m` is `(x1 : Nat) -> (x2 : f x1 = x1) -> C[x1, x2]`, and type of `v` is `C[a, c]`. Note that, `?m a c` is type correct since `f a = a` is definitionally equal to the type of `c : b = a`, and the type of `?m a c` is equal to the type of `v`. Note that `fun xs => v` is the term `fun (x1 : Nat) (x2 : b = x1) => v` which has type `(x1 : Nat) -> (x2 : b = x1) -> C[x1, x2]` which is not definitionally equal to the type of `?m`, and may not even be type correct. The issue here is that we are not capturing the `let`-declarations. This method collects let-declarations `y` occurring between `xs[0]` and `xs.back` s.t. some `x` in `xs` depends on `y`. `ys` is the `xs` with these extra let-declarations included. In the example above, `ys` is `#[a, b, c]`, and `mkLambdaFVars ys v` produces `fun a => let b := f a; fun (c : b = a) => v` which has a type definitionally equal to the type of `?m`. Recall that the method `checkAssignment` ensures `v` does not contain offending `let`-declarations. This method assumes that for any `xs[i]` and `xs[j]` where `i < j`, we have that `index of xs[i]` < `index of xs[j]`. where the index is the position in the local context. -/ private partial def mkLambdaFVarsWithLetDeps (xs : Array Expr) (v : Expr) : MetaM (Option Expr) := do if not (← hasLetDeclsInBetween) then mkLambdaFVars xs v else let ys ← addLetDeps mkLambdaFVars ys v where /-- Return true if there are let-declarions between `xs[0]` and `xs[xs.size-1]`. We use it a quick-check to avoid the more expensive collection procedure. -/ hasLetDeclsInBetween : MetaM Bool := do let check (lctx : LocalContext) : Bool := Id.run do let start := lctx.getFVar! xs[0]! |>.index let stop := lctx.getFVar! xs.back |>.index for i in [start+1:stop] do match lctx.getAt? i with | some localDecl => if localDecl.isLet then return true | _ => pure () return false if xs.size <= 1 then return false else return check (← getLCtx) /-- Traverse `e` and stores in the state `NameHashSet` any let-declaration with index greater than `(← read)`. The context `Nat` is the position of `xs[0]` in the local context. -/ collectLetDeclsFrom (e : Expr) : ReaderT Nat (StateRefT FVarIdHashSet MetaM) Unit := do let rec visit (e : Expr) : MonadCacheT Expr Unit (ReaderT Nat (StateRefT FVarIdHashSet MetaM)) Unit := checkCache e fun _ => do match e with | Expr.forallE _ d b _ => visit d; visit b | Expr.lam _ d b _ => visit d; visit b | Expr.letE _ t v b _ => visit t; visit v; visit b | Expr.app f a => visit f; visit a | Expr.mdata _ b => visit b | Expr.proj _ _ b => visit b | Expr.fvar fvarId => let localDecl ← fvarId.getDecl if localDecl.isLet && localDecl.index > (← read) then modify fun s => s.insert localDecl.fvarId | _ => pure () visit (← instantiateMVars e) |>.run /-- Auxiliary definition for traversing all declarations between `xs[0]` ... `xs.back` backwards. The `Nat` argument is the current position in the local context being visited, and it is less than or equal to the position of `xs.back` in the local context. The `Nat` context `(← read)` is the position of `xs[0]` in the local context. -/ collectLetDepsAux : Nat → ReaderT Nat (StateRefT FVarIdHashSet MetaM) Unit | 0 => return () | i+1 => do if i+1 == (← read) then return () else match (← getLCtx).getAt? (i+1) with | none => collectLetDepsAux i | some localDecl => if (← get).contains localDecl.fvarId then collectLetDeclsFrom localDecl.type match localDecl.value? with | some val => collectLetDeclsFrom val | _ => pure () collectLetDepsAux i /-- Computes the set `ys`. It is a set of `FVarId`s, -/ collectLetDeps : MetaM FVarIdHashSet := do let lctx ← getLCtx let start := lctx.getFVar! xs[0]! |>.index let stop := lctx.getFVar! xs.back |>.index let s := xs.foldl (init := {}) fun s x => s.insert x.fvarId! let (_, s) ← collectLetDepsAux stop |>.run start |>.run s return s /-- Computes the array `ys` containing let-decls between `xs[0]` and `xs.back` that some `x` in `xs` depends on. -/ addLetDeps : MetaM (Array Expr) := do let lctx ← getLCtx let s ← collectLetDeps /- Convert `s` into the array `ys` -/ let start := lctx.getFVar! xs[0]! |>.index let stop := lctx.getFVar! xs.back |>.index let mut ys := #[] for i in [start:stop+1] do match lctx.getAt? i with | none => pure () | some localDecl => if s.contains localDecl.fvarId then ys := ys.push localDecl.toExpr return ys /-! Each metavariable is declared in a particular local context. We use the notation `C |- ?m : t` to denote a metavariable `?m` that was declared at the local context `C` with type `t` (see `MetavarDecl`). We also use `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`. The following method process the unification constraint ?m@C a₁ ... aₙ =?= t We say the unification constraint is a pattern IFF 1) `a₁ ... aₙ` are pairwise distinct free variables that are ​*not*​ let-variables. 2) `a₁ ... aₙ` are not in `C` 3) `t` only contains free variables in `C` and/or `{a₁, ..., aₙ}` 4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C` 5) `?m` does not occur in `t` Claim: we don't have to check free variable declarations. That is, if `t` contains a reference to `x : A := v`, we don't need to check `v`. Reason: The reference to `x` is a free variable, and it must be in `C` (by 1 and 3). If `x` is in `C`, then any metavariable occurring in `v` must have been defined in a strict subprefix of `C`. So, condition 4 and 5 are satisfied. If the conditions above have been satisfied, then the solution for the unification constrain is ?m := fun a₁ ... aₙ => t Now, we consider some workarounds/approximations. A1) Suppose `t` contains a reference to `x : A := v` and `x` is not in `C` (failed condition 3) (precise) solution: unfold `x` in `t`. A2) Suppose some `aᵢ` is in `C` (failed condition 2) (approximated) solution (when `config.quasiPatternApprox` is set to true) : ignore condition and also use ?m := fun a₁ ... aₙ => t Here is an example where this approximation fails: Given `C` containing `a : nat`, consider the following two constraints ?m@C a =?= a ?m@C b =?= a If we use the approximation in the first constraint, we get ?m := fun x => x when we apply this solution to the second one we get a failure. IMPORTANT: When applying this approximation we need to make sure the abstracted term `fun a₁ ... aₙ => t` is type correct. The check can only be skipped in the pattern case described above. Consider the following example. Given the local context (α : Type) (a : α) we try to solve ?m α =?= @id α a If we use the approximation above we obtain: ?m := (fun α' => @id α' a) which is a type incorrect term. `a` has type `α` but it is expected to have type `α'`. The problem occurs because the right hand side contains a free variable `a` that depends on the free variable `α` being abstracted. Note that this dependency cannot occur in patterns. We can address this by type checking the term after abstraction. This is not a significant performance bottleneck because this case doesn't happen very often in practice (262 times when compiling stdlib on Jan 2018). The second example is trickier, but it also occurs less frequently (8 times when compiling stdlib on Jan 2018, and all occurrences were at Init/Control when we define monads and auxiliary combinators for them). We considered three options for the addressing the issue on the second example: A3) `a₁ ... aₙ` are not pairwise distinct (failed condition 1). In Lean3, we would try to approximate this case using an approach similar to A2. However, this approximation complicates the code, and is never used in the Lean3 stdlib and mathlib. A4) `t` contains a metavariable `?m'@C'` where `C'` is not a subprefix of `C`. If `?m'` is assigned, we substitute. If not, we create an auxiliary metavariable with a smaller scope. Actually, we let `elimMVarDeps` at `MetavarContext.lean` to perform this step. A5) If some `aᵢ` is not a free variable, then we use first-order unification (if `config.foApprox` is set to true) ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k reduces to ?M a_1 ... a_i =?= f a_{i+1} =?= b_1 ... a_{i+k} =?= b_k A6) If (m =?= v) is of the form ?m a_1 ... a_n =?= ?m b_1 ... b_k then we use first-order unification (if `config.foApprox` is set to true) A7) When `foApprox`, we may use another approximation (`constApprox`) for solving constraints of the form ``` ?m s₁ ... sₙ =?= t ``` where `s₁ ... sₙ` are arbitrary terms. We solve them by assigning the constant function to `?m`. ``` ?m := fun _ ... _ => t ``` In general, this approximation may produce bad solutions, and may prevent coercions from being tried. For example, consider the term `pure (x > 0)` with inferred type `?m Prop` and expected type `IO Bool`. In this situation, the elaborator generates the unification constraint ``` ?m Prop =?= IO Bool ``` It is not a higher-order pattern, nor first-order approximation is applicable. However, constant approximation produces the bogus solution `?m := fun _ => IO Bool`, and prevents the system from using the coercion from the decidable proposition `x > 0` to `Bool`. On the other hand, the constant approximation is desirable for elaborating the term ``` let f (x : _) := pure "hello"; f () ``` with expected type `IO String`. In this example, the following unification contraint is generated. ``` ?m () String =?= IO String ``` It is not a higher-order pattern, first-order approximation reduces it to ``` ?m () =?= IO ``` which fails to be solved. However, constant approximation solves it by assigning ``` ?m := fun _ => IO ``` Note that `f`s type is `(x : ?α) -> ?m x String`. The metavariable `?m` may depend on `x`. If `constApprox` is set to true, we use constant approximation. Otherwise, we use a heuristic to decide whether we should apply it or not. The heuristic is based on observing where the constraints above come from. In the first example, the constraint `?m Prop =?= IO Bool` come from polymorphic method where `?m` is expected to be a **function** of type `Type -> Type`. In the second example, the first argument of `?m` is used to model a **potential** dependency on `x`. By using constant approximation here, we are just saying the type of `f` does **not** depend on `x`. We claim this is a reasonable approximation in practice. Moreover, it is expected by any functional programmer used to non-dependently type languages (e.g., Haskell). We distinguish the two cases above by using the field `numScopeArgs` at `MetavarDecl`. This fiels tracks how many metavariable arguments are representing dependencies. -/ def mkAuxMVar (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAt lctx localInsts type MetavarKind.natural Name.anonymous numScopeArgs namespace CheckAssignment builtin_initialize checkAssignmentExceptionId : InternalExceptionId ← registerInternalExceptionId `checkAssignment builtin_initialize outOfScopeExceptionId : InternalExceptionId ← registerInternalExceptionId `outOfScope structure State where cache : ExprStructMap Expr := {} structure Context where mvarId : MVarId mvarDecl : MetavarDecl fvars : Array Expr hasCtxLocals : Bool rhs : Expr abbrev CheckAssignmentM := ReaderT Context $ StateRefT State MetaM def throwCheckAssignmentFailure : CheckAssignmentM α := throw <| Exception.internal checkAssignmentExceptionId def throwOutOfScopeFVar : CheckAssignmentM α := throw <| Exception.internal outOfScopeExceptionId private def findCached? (e : Expr) : CheckAssignmentM (Option Expr) := do return (← get).cache.find? e private def cache (e r : Expr) : CheckAssignmentM Unit := do modify fun s => { s with cache := s.cache.insert e r } instance : MonadCache Expr Expr CheckAssignmentM where findCached? := findCached? cache := cache private def addAssignmentInfo (msg : MessageData) : CheckAssignmentM MessageData := do let ctx ← read return m!"{msg} @ {mkMVar ctx.mvarId} {ctx.fvars} := {ctx.rhs}" @[inline] def run (x : CheckAssignmentM Expr) (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do let mvarDecl ← mvarId.getDecl let ctx := { mvarId := mvarId, mvarDecl := mvarDecl, fvars := fvars, hasCtxLocals := hasCtxLocals, rhs := v : Context } let x : CheckAssignmentM (Option Expr) := catchInternalIds [outOfScopeExceptionId, checkAssignmentExceptionId] (do let e ← x; return some e) (fun _ => pure none) x.run ctx |>.run' {} mutual partial def checkFVar (fvar : Expr) : CheckAssignmentM Expr := do let ctxMeta ← readThe Meta.Context let ctx ← read if ctx.mvarDecl.lctx.containsFVar fvar then pure fvar else let lctx := ctxMeta.lctx match lctx.findFVar? fvar with | some (.ldecl (value := v) ..) => check v | _ => if ctx.fvars.contains fvar then pure fvar else traceM `Meta.isDefEq.assign.outOfScopeFVar do addAssignmentInfo fvar throwOutOfScopeFVar partial def checkMVar (mvar : Expr) : CheckAssignmentM Expr := do let mvarId := mvar.mvarId! let ctx ← read if mvarId == ctx.mvarId then traceM `Meta.isDefEq.assign.occursCheck <| addAssignmentInfo "occurs check failed" throwCheckAssignmentFailure else match (← getExprMVarAssignment? mvarId) with | some v => check v | none => match (← mvarId.findDecl?) with | none => throwUnknownMVar mvarId | some mvarDecl => if ctx.hasCtxLocals then throwCheckAssignmentFailure -- It is not a pattern, then we fail and fall back to FO unification else if mvarDecl.lctx.isSubPrefixOf ctx.mvarDecl.lctx ctx.fvars then /- The local context of `mvar` - free variables being abstracted is a subprefix of the metavariable being assigned. We "substract" variables being abstracted because we use `elimMVarDeps` -/ pure mvar else if mvarDecl.depth != (← getMCtx).depth || mvarDecl.kind.isSyntheticOpaque then traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId) throwCheckAssignmentFailure else let ctxMeta ← readThe Meta.Context if ctxMeta.config.ctxApprox && ctx.mvarDecl.lctx.isSubPrefixOf mvarDecl.lctx then /- Create an auxiliary metavariable with a smaller context and "checked" type. Note that `mvarType` may be different from `mvarDecl.type`. Example: `mvarType` contains a metavariable that we also need to reduce the context. We remove from `ctx.mvarDecl.lctx` any variable that is not in `mvarDecl.lctx` or in `ctx.fvars`. We don't need to remove the ones in `ctx.fvars` because `elimMVarDeps` will take care of them. First, we collect `toErase` the variables that need to be erased. Notat that if a variable is `ctx.fvars`, but it depends on variable at `toErase`, we must also erase it. -/ let toErase ← mvarDecl.lctx.foldlM (init := #[]) fun toErase localDecl => do if ctx.mvarDecl.lctx.contains localDecl.fvarId then return toErase else if ctx.fvars.any fun fvar => fvar.fvarId! == localDecl.fvarId then if (← findLocalDeclDependsOn localDecl fun fvarId => toErase.contains fvarId) then -- localDecl depends on a variable that will be erased. So, we must add it to `toErase` too return toErase.push localDecl.fvarId else return toErase else return toErase.push localDecl.fvarId let lctx := toErase.foldl (init := mvarDecl.lctx) fun lctx toEraseFVar => lctx.erase toEraseFVar /- Compute new set of local instances. -/ let localInsts := mvarDecl.localInstances.filter fun localInst => toErase.contains localInst.fvar.fvarId! let mvarType ← check mvarDecl.type let newMVar ← mkAuxMVar lctx localInsts mvarType mvarDecl.numScopeArgs mvarId.assign newMVar pure newMVar else traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId) throwCheckAssignmentFailure /-- Auxiliary function used to "fix" subterms of the form `?m x_1 ... x_n` where `x_i`s are free variables, and one of them is out-of-scope. See `Expr.app` case at `check`. If `ctxApprox` is true, then we solve this case by creating a fresh metavariable ?n with the correct scope, an assigning `?m := fun _ ... _ => ?n` -/ partial def assignToConstFun (mvar : Expr) (numArgs : Nat) (newMVar : Expr) : MetaM Bool := do let mvarType ← inferType mvar forallBoundedTelescope mvarType numArgs fun xs _ => do if xs.size != numArgs then pure false else let some v ← mkLambdaFVarsWithLetDeps xs newMVar | return false match (← checkAssignmentAux mvar.mvarId! #[] false v) with | some v => checkTypesAndAssign mvar v | none => return false -- See checkAssignment partial def checkAssignmentAux (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do run (check v) mvarId fvars hasCtxLocals v partial def checkApp (e : Expr) : CheckAssignmentM Expr := e.withApp fun f args => do let ctxMeta ← readThe Meta.Context if f.isMVar && ctxMeta.config.ctxApprox && args.all Expr.isFVar then let f ← check f catchInternalId outOfScopeExceptionId (do let args ← args.mapM check return mkAppN f args) (fun ex => do if !f.isMVar then throw ex else if (← f.mvarId!.isDelayedAssigned) then throw ex else let eType ← inferType e let mvarType ← check eType /- Create an auxiliary metavariable with a smaller context and "checked" type, assign `?f := fun _ => ?newMVar` Note that `mvarType` may be different from `eType`. -/ let ctx ← read let newMVar ← mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType if (← assignToConstFun f args.size newMVar) then pure newMVar else throw ex) else let f ← check f let args ← args.mapM check return mkAppN f args partial def check (e : Expr) : CheckAssignmentM Expr := do if !e.hasExprMVar && !e.hasFVar then return e else checkCache e fun _ => match e with | Expr.mdata _ b => return e.updateMData! (← check b) | Expr.proj _ _ s => return e.updateProj! (← check s) | Expr.lam _ d b _ => return e.updateLambdaE! (← check d) (← check b) | Expr.forallE _ d b _ => return e.updateForallE! (← check d) (← check b) | Expr.letE _ t v b _ => return e.updateLet! (← check t) (← check v) (← check b) | Expr.bvar .. => return e | Expr.sort .. => return e | Expr.const .. => return e | Expr.lit .. => return e | Expr.fvar .. => checkFVar e | Expr.mvar .. => checkMVar e | Expr.app .. => checkApp e -- TODO: investigate whether the following feature is too expensive or not /- catchInternalIds [checkAssignmentExceptionId, outOfScopeExceptionId] (checkApp e) fun ex => do let e' ← whnfR e if e != e' then check e' else throw ex -/ end end CheckAssignment namespace CheckAssignmentQuick partial def check (hasCtxLocals : Bool) (mctx : MetavarContext) (lctx : LocalContext) (mvarDecl : MetavarDecl) (mvarId : MVarId) (fvars : Array Expr) (e : Expr) : Bool := let rec visit (e : Expr) : Bool := if !e.hasExprMVar && !e.hasFVar then true else match e with | Expr.mdata _ b => visit b | Expr.proj _ _ s => visit s | Expr.app f a => visit f && visit a | Expr.lam _ d b _ => visit d && visit b | Expr.forallE _ d b _ => visit d && visit b | Expr.letE _ t v b _ => visit t && visit v && visit b | Expr.bvar .. => true | Expr.sort .. => true | Expr.const .. => true | Expr.lit .. => true | Expr.fvar fvarId .. => if mvarDecl.lctx.contains fvarId then true else match lctx.find? fvarId with | some (LocalDecl.ldecl ..) => false -- need expensive CheckAssignment.check | _ => if fvars.any fun x => x.fvarId! == fvarId then true else false -- We could throw an exception here, but we would have to use ExceptM. So, we let CheckAssignment.check do it | Expr.mvar mvarId' => match mctx.getExprAssignmentCore? mvarId' with | some _ => false -- use CheckAssignment.check to instantiate | none => if mvarId' == mvarId then false -- occurs check failed, use CheckAssignment.check to throw exception else match mctx.findDecl? mvarId' with | none => false | some mvarDecl' => if hasCtxLocals then false -- use CheckAssignment.check else if mvarDecl'.lctx.isSubPrefixOf mvarDecl.lctx fvars then true else false -- use CheckAssignment.check visit e end CheckAssignmentQuick /-- Auxiliary function for handling constraints of the form `?m a₁ ... aₙ =?= v`. It will check whether we can perform the assignment ``` ?m := fun fvars => v ``` The result is `none` if the assignment can't be performed. The result is `some newV` where `newV` is a possibly updated `v`. This method may need to unfold let-declarations. -/ def checkAssignment (mvarId : MVarId) (fvars : Array Expr) (v : Expr) : MetaM (Option Expr) := do /- Check whether `mvarId` occurs in the type of `fvars` or not. If it does, return `none` to prevent us from creating the cyclic assignment `?m := fun fvars => v` -/ for fvar in fvars do unless (← occursCheck mvarId (← inferType fvar)) do return none if !v.hasExprMVar && !v.hasFVar then pure (some v) else let mvarDecl ← mvarId.getDecl let hasCtxLocals := fvars.any fun fvar => mvarDecl.lctx.containsFVar fvar let ctx ← read let mctx ← getMCtx if CheckAssignmentQuick.check hasCtxLocals mctx ctx.lctx mvarDecl mvarId fvars v then pure (some v) else let v ← instantiateMVars v CheckAssignment.checkAssignmentAux mvarId fvars hasCtxLocals v private def processAssignmentFOApproxAux (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool := match v with | .mdata _ e => processAssignmentFOApproxAux mvar args e | Expr.app f a => if args.isEmpty then pure false else Meta.isExprDefEqAux args.back a <&&> Meta.isExprDefEqAux (mkAppRange mvar 0 (args.size - 1) args) f | _ => pure false /-- Auxiliary method for applying first-order unification. It is an approximation. Remark: this method is trying to solve the unification constraint: ?m a₁ ... aₙ =?= v It is uses processAssignmentFOApproxAux, if it fails, it tries to unfold `v`. We have added support for unfolding here because we want to be able to solve unification problems such as ?m Unit =?= ITactic where `ITactic` is defined as def ITactic := Tactic Unit -/ private partial def processAssignmentFOApprox (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool := let rec loop (v : Expr) := do let cfg ← getConfig if !cfg.foApprox then pure false else trace[Meta.isDefEq.foApprox] "{mvar} {args} := {v}" let v := v.headBeta if (← checkpointDefEq <| processAssignmentFOApproxAux mvar args v) then pure true else match (← unfoldDefinition? v) with | none => pure false | some v => loop v loop v private partial def simpAssignmentArgAux (e : Expr) : MetaM Expr := do match e with | .mdata _ e => simpAssignmentArgAux e | .fvar fvarId => let some value ← fvarId.getValue? | return e simpAssignmentArgAux value | _ => return e /-- Auxiliary procedure for processing `?m a₁ ... aₙ =?= v`. We apply it to each `aᵢ`. It instantiates assigned metavariables if `aᵢ` is of the form `f[?n] b₁ ... bₘ`, and then removes metadata, and zeta-expand let-decls. -/ private def simpAssignmentArg (arg : Expr) : MetaM Expr := do let arg ← if arg.getAppFn.hasExprMVar then instantiateMVars arg else pure arg simpAssignmentArgAux arg /-- Assign `mvar := fun a_1 ... a_{numArgs} => v`. We use it at `processConstApprox` and `isDefEqMVarSelf` -/ private def assignConst (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do let mvarDecl ← mvar.mvarId!.getDecl forallBoundedTelescope mvarDecl.type numArgs fun xs _ => do if xs.size != numArgs then pure false else let some v ← mkLambdaFVarsWithLetDeps xs v | pure false match (← checkAssignment mvar.mvarId! #[] v) with | none => pure false | some v => trace[Meta.isDefEq.constApprox] "{mvar} := {v}" checkTypesAndAssign mvar v /-- Auxiliary procedure for solving `?m args =?= v` when `args[:patternVarPrefix]` contains only pairwise distinct free variables. Let `args[:patternVarPrefix] = #[a₁, ..., aₙ]`, and `args[patternVarPrefix:] = #[b₁, ..., bᵢ]`, this procedure first reduces the constraint to ``` ?m a₁ ... aₙ =?= fun x₁ ... xᵢ => v ``` where the left-hand-side is a constant function. Then, it tries to find the longest prefix `#[a₁, ..., aⱼ]` of `#[a₁, ..., aₙ]` such that the following assignment is valid. ``` ?m := fun y₁ ... y‌ⱼ => (fun y_{j+1} ... yₙ x₁ ... xᵢ => v)[a₁/y₁, .., aⱼ/yⱼ] ``` That is, after the longest prefix is found, we solve the contraint as the lhs was a pattern. See the definition of "pattern" above. -/ private partial def processConstApprox (mvar : Expr) (args : Array Expr) (patternVarPrefix : Nat) (v : Expr) : MetaM Bool := do trace[Meta.isDefEq.constApprox] "{mvar} {args} := {v}" let rec defaultCase : MetaM Bool := assignConst mvar args.size v let cfg ← getConfig let mvarId := mvar.mvarId! let mvarDecl ← mvarId.getDecl let numArgs := args.size if mvarDecl.numScopeArgs != numArgs && !cfg.constApprox then return false else if patternVarPrefix == 0 then defaultCase else let argsPrefix : Array Expr := args[:patternVarPrefix] let type ← instantiateForall mvarDecl.type argsPrefix let suffixSize := numArgs - argsPrefix.size forallBoundedTelescope type suffixSize fun xs _ => do if xs.size != suffixSize then defaultCase else let some v ← mkLambdaFVarsWithLetDeps xs v | defaultCase let rec go (argsPrefix : Array Expr) (v : Expr) : MetaM Bool := do trace[Meta.isDefEq] "processConstApprox.go {mvar} {argsPrefix} := {v}" let rec cont : MetaM Bool := do if argsPrefix.isEmpty then defaultCase else let some v ← mkLambdaFVarsWithLetDeps #[argsPrefix.back] v | defaultCase go argsPrefix.pop v match (← checkAssignment mvarId argsPrefix v) with | none => cont | some vNew => let some vNew ← mkLambdaFVarsWithLetDeps argsPrefix vNew | cont if argsPrefix.any (fun arg => mvarDecl.lctx.containsFVar arg) then /- We need to type check `vNew` because abstraction using `mkLambdaFVars` may have produced a type incorrect term. See discussion at A2 -/ (isTypeCorrect vNew <&&> checkTypesAndAssign mvar vNew) <||> cont else checkTypesAndAssign mvar vNew <||> cont go argsPrefix v /-- Tries to solve `?m a₁ ... aₙ =?= v` by assigning `?m`. It assumes `?m` is unassigned. -/ private partial def processAssignment (mvarApp : Expr) (v : Expr) : MetaM Bool := withTraceNode `Meta.isDefEq.assign (return m!"{exceptBoolEmoji ·} {mvarApp} := {v}") do let mvar := mvarApp.getAppFn let mvarDecl ← mvar.mvarId!.getDecl let rec process (i : Nat) (args : Array Expr) (v : Expr) := do let cfg ← getConfig let useFOApprox (args : Array Expr) : MetaM Bool := processAssignmentFOApprox mvar args v <||> processConstApprox mvar args i v if h : i < args.size then let arg := args.get ⟨i, h⟩ let arg ← simpAssignmentArg arg let args := args.set ⟨i, h⟩ arg match arg with | Expr.fvar fvarId => if args[0:i].any fun prevArg => prevArg == arg then useFOApprox args else if mvarDecl.lctx.contains fvarId && !cfg.quasiPatternApprox then useFOApprox args else process (i+1) args v | _ => useFOApprox args else let v ← instantiateMVars v -- enforce A4 if v.getAppFn == mvar then -- using A6 useFOApprox args else let mvarId := mvar.mvarId! match (← checkAssignment mvarId args v) with | none => useFOApprox args | some v => do trace[Meta.isDefEq.assign.beforeMkLambda] "{mvar} {args} := {v}" let some v ← mkLambdaFVarsWithLetDeps args v | return false if args.any (fun arg => mvarDecl.lctx.containsFVar arg) then /- We need to type check `v` because abstraction using `mkLambdaFVars` may have produced a type incorrect term. See discussion at A2 -/ if (← isTypeCorrect v) then checkTypesAndAssign mvar v else trace[Meta.isDefEq.assign.typeError] "{mvar} := {v}" useFOApprox args else checkTypesAndAssign mvar v process 0 mvarApp.getAppArgs v /-- Similar to processAssignment, but if it fails, compute v's whnf and try again. This helps to solve constraints such as `?m =?= { α := ?m, ... }.α` Note this is not perfect solution since we still fail occurs check for constraints such as ```lean ?m =?= List { α := ?m, β := Nat }.β ``` -/ private def processAssignment' (mvarApp : Expr) (v : Expr) : MetaM Bool := do if (← processAssignment mvarApp v) then return true else let vNew ← whnf v if vNew != v then if mvarApp == vNew then return true else processAssignment mvarApp vNew else return false private def isDeltaCandidate? (t : Expr) : MetaM (Option ConstantInfo) := do match t.getAppFn with | Expr.const c _ => match (← getConst? c) with | r@(some info) => if info.hasValue then return r else return none | _ => return none | _ => pure none /-- Auxiliary method for isDefEqDelta -/ private def isListLevelDefEq (us vs : List Level) : MetaM LBool := toLBoolM <| isListLevelDefEqAux us vs /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeft (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldLeft] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqRight (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldRight] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeftRight (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldLeftRight] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Try to solve `f a₁ ... aₙ =?= f b₁ ... bₙ` by solving `a₁ =?= b₁, ..., aₙ =?= bₙ`. Auxiliary method for isDefEqDelta -/ private def tryHeuristic (t s : Expr) : MetaM Bool := do let mut t := t let mut s := s let tFn := t.getAppFn let sFn := s.getAppFn let info ← getConstInfo tFn.constName! /- We only use the heuristic when `f` is a regular definition or an auxiliary `match` application. That is, it is not marked an abbreviation (e.g., a user-facing projection) or as opaque (e.g., proof). We check whether terms contain metavariables to make sure we can solve constraints such as `S.proj ?x =?= S.proj t` without performing delta-reduction. That is, we are assuming the heuristic implemented by this method is seldom effective when `t` and `s` do not have metavariables, are not structurally equal, and `f` is an abbreviation. On the other hand, by unfolding `f`, we often produce smaller terms. Recall that auxiliary `match` definitions are marked as abbreviations, but we must use the heuristic on them since they will not be unfolded when smartUnfolding is turned on. The abbreviation annotation in this case is used to help the kernel type checker. -/ unless info.hints.isRegular || isMatcherCore (← getEnv) tFn.constName! do unless t.hasExprMVar || s.hasExprMVar do return false withTraceNode `Meta.isDefEq.delta (return m!"{exceptBoolEmoji ·} {t} =?= {s}") do /- We process arguments before universe levels to reduce a source of brittleness in the TC procedure. In the TC procedure, we can solve problems containing metavariables. If the TC procedure tries to assign one of these metavariables, it interrupts the search using a "stuck" exception. The elaborator catches it, and "interprets" it as "we should try again later". Now suppose we have a TC problem, and there are two "local" candidate instances we can try: "bad" and "good". The "bad" candidate is stuck because of a universe metavariable in the TC problem. If we try "bad" first, the TC procedure is interrupted. Moreover, if we have ignored the exception, "bad" would fail anyway trying to assign two different free variables `α =?= β`. Example: `Preorder.{?u} α =?= Preorder.{?v} β`, where `?u` and `?v` are universe metavariables that were not created by the TC procedure. The key issue here is that we have an `isDefEq t s` invocation that is interrupted by the "stuck" exception, but it would have failed anyway if we had continued processing it. By solving the arguments first, we make the example above fail without throwing the "stuck" exception. TODO: instead of throwing an exception as soon as we get stuck, we should just set a flag. Then the entry-point for `isDefEq` checks the flag before returning `true`. -/ checkpointDefEq do isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels! /-- Auxiliary method for isDefEqDelta -/ private abbrev unfold (e : Expr) (failK : MetaM α) (successK : Expr → MetaM α) : MetaM α := do match (← unfoldDefinition? e) with | some e => successK e | none => failK /-- Auxiliary method for isDefEqDelta -/ private def unfoldBothDefEq (fn : Name) (t s : Expr) : MetaM LBool := do match t, s with | Expr.const _ ls₁, Expr.const _ ls₂ => isListLevelDefEq ls₁ ls₂ | Expr.app _ _, Expr.app _ _ => if (← tryHeuristic t s) then pure LBool.true else unfold t (unfold s (pure LBool.undef) (fun s => isDefEqRight fn t s)) (fun t => unfold s (isDefEqLeft fn t s) (fun s => isDefEqLeftRight fn t s)) | _, _ => pure LBool.false private def sameHeadSymbol (t s : Expr) : Bool := match t.getAppFn, s.getAppFn with | Expr.const c₁ _, Expr.const c₂ _ => c₁ == c₂ | _, _ => false /-- - If headSymbol (unfold t) == headSymbol s, then unfold t - If headSymbol (unfold s) == headSymbol t, then unfold s - Otherwise unfold t and s if possible. Auxiliary method for isDefEqDelta -/ private def unfoldComparingHeadsDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := unfold t (unfold s (pure LBool.undef) -- `t` and `s` failed to be unfolded (fun s => isDefEqRight sInfo.name t s)) (fun tNew => if sameHeadSymbol tNew s then isDefEqLeft tInfo.name tNew s else unfold s (isDefEqLeft tInfo.name tNew s) (fun sNew => if sameHeadSymbol t sNew then isDefEqRight sInfo.name t sNew else isDefEqLeftRight tInfo.name tNew sNew)) /-- If `t` and `s` do not contain metavariables, then use kernel definitional equality heuristics. Otherwise, use `unfoldComparingHeadsDefEq`. Auxiliary method for isDefEqDelta -/ private def unfoldDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := if !t.hasExprMVar && !s.hasExprMVar then /- If `t` and `s` do not contain metavariables, we simulate strategy used in the kernel. -/ if tInfo.hints.lt sInfo.hints then unfold t (unfoldComparingHeadsDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s else if sInfo.hints.lt tInfo.hints then unfold s (unfoldComparingHeadsDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s else unfoldComparingHeadsDefEq tInfo sInfo t s else unfoldComparingHeadsDefEq tInfo sInfo t s /-- When `TransparencyMode` is set to `default` or `all`. If `t` is reducible and `s` is not ==> `isDefEqLeft (unfold t) s` If `s` is reducible and `t` is not ==> `isDefEqRight t (unfold s)` Otherwise, use `unfoldDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldReducibeDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do if (← shouldReduceReducibleOnly) then unfoldDefEq tInfo sInfo t s else let tReducible ← isReducible tInfo.name let sReducible ← isReducible sInfo.name if tReducible && !sReducible then unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s else if !tReducible && sReducible then unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s else unfoldDefEq tInfo sInfo t s /-- This is an auxiliary method for isDefEqDelta. If `t` is a (non-class) projection function application and `s` is not ==> `isDefEqRight t (unfold s)` If `s` is a (non-class) projection function application and `t` is not ==> `isDefEqRight (unfold t) s` Otherwise, use `unfoldReducibeDefEq` One motivation for the heuristic above is unification problems such as ``` id (?m.1) =?= (a, b).1 ``` We want to reduce the lhs instead of the rhs, and eventually assign `?m := (a, b)`. Another motivation for the heuristic above is unification problems such as ``` List.length (a :: as) =?= HAdd.hAdd (List.length as) 1 ``` However, for class projections, we also unpack them and check whether the result function is the one on the other side. This is relevant for unification problems such as ``` Foo.pow x 256 =?= Pow.pow x 256 ``` where the the `Pow` instance is wrapping `Foo.pow` See issue #1419 for the complete example. -/ private partial def unfoldNonProjFnDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do let tProjInfo? ← getProjectionFnInfo? tInfo.name let sProjInfo? ← getProjectionFnInfo? sInfo.name if let some tNew ← packedInstanceOf? tProjInfo? t sInfo.name then isDefEqLeft tInfo.name tNew s else if let some sNew ← packedInstanceOf? sProjInfo? s tInfo.name then isDefEqRight sInfo.name t sNew else match tProjInfo?, sProjInfo? with | some _, none => unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s | none, some _ => unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s | _, _ => unfoldReducibeDefEq tInfo sInfo t s where packedInstanceOf? (projInfo? : Option ProjectionFunctionInfo) (e : Expr) (declName : Name) : MetaM (Option Expr) := do let some { fromClass := true, .. } := projInfo? | return none -- It is not a class projection let some e ← unfoldDefinition? e | return none let e ← whnfCore e if e.isAppOf declName then return some e let .const name _ := e.getAppFn | return none -- Keep going if new `e` is also a class projection packedInstanceOf? (← getProjectionFnInfo? name) e declName /-- isDefEq by lazy delta reduction. This method implements many different heuristics: 1- If only `t` can be unfolded => then unfold `t` and continue 2- If only `s` can be unfolded => then unfold `s` and continue 3- If `t` and `s` can be unfolded and they have the same head symbol, then a) First try to solve unification by unifying arguments. b) If it fails, unfold both and continue. Implemented by `unfoldBothDefEq` 4- If `t` is a projection function application and `s` is not => then unfold `s` and continue. 5- If `s` is a projection function application and `t` is not => then unfold `t` and continue. Remark: 4&5 are implemented by `unfoldNonProjFnDefEq` 6- If `t` is reducible and `s` is not => then unfold `t` and continue. 7- If `s` is reducible and `t` is not => then unfold `s` and continue Remark: 6&7 are implemented by `unfoldReducibeDefEq` 8- If `t` and `s` do not contain metavariables, then use heuristic used in the Kernel. Implemented by `unfoldDefEq` 9- If `headSymbol (unfold t) == headSymbol s`, then unfold t and continue. 10- If `headSymbol (unfold s) == headSymbol t`, then unfold s 11- Otherwise, unfold `t` and `s` and continue. Remark: 9&10&11 are implemented by `unfoldComparingHeadsDefEq` -/ private def isDefEqDelta (t s : Expr) : MetaM LBool := do let tInfo? ← isDeltaCandidate? t let sInfo? ← isDeltaCandidate? s match tInfo?, sInfo? with | none, none => pure LBool.undef | some tInfo, none => unfold t (pure LBool.undef) fun t => isDefEqLeft tInfo.name t s | none, some sInfo => unfold s (pure LBool.undef) fun s => isDefEqRight sInfo.name t s | some tInfo, some sInfo => if tInfo.name == sInfo.name then unfoldBothDefEq tInfo.name t s else unfoldNonProjFnDefEq tInfo sInfo t s private def isAssigned : Expr → MetaM Bool | Expr.mvar mvarId => mvarId.isAssigned | _ => pure false private def expandDelayedAssigned? (t : Expr) : MetaM (Option Expr) := do let tFn := t.getAppFn if !tFn.isMVar then return none let some { fvars, mvarIdPending } ← getDelayedMVarAssignment? tFn.mvarId! | return none let tNew ← instantiateMVars t if tNew != t then return some tNew /- If `assignSyntheticOpaque` is true, we must follow the delayed assignment. Recall a delayed assignment `mvarId [xs] := mvarIdPending` is morally an assingment `mvarId := fun xs => mvarIdPending` where `xs` are free variables in the scope of `mvarIdPending`, but not in the scope of `mvarId`. We can only perform the abstraction when `mvarIdPending` has been fully synthesized. That is, `instantiateMVars (mkMVar mvarIdPending)` does not contain any expression metavariables. Here we just consume `fvar.size` arguments. That is, if `t` is of the form `mvarId as bs` where `as.size == fvars.size`, we return `mvarIdPending bs`. TODO: improve this transformation. Here is a possible improvement. Assume `t` is of the form `?m as` where `as` represent the arguments, and we are trying to solve `?m as =?= s[as]` where `s[as]` represents a term containing occurrences of `as`. We could try to compute the solution as usual `?m := fun ys => s[as/ys]` We also have the delayed assignment `?m [xs] := ?n`, where `xs` are variables in the scope of `?n`, and this delayed assignment is morally `?m := fun xs => ?n`. Thus, we can reduce `?m as =?= s[as]` to `?n =?= s[as/xs]`, and solve it using `?n`'s local context. This is more precise than simplying droping the arguments `as`. -/ unless (← getConfig).assignSyntheticOpaque do return none let tArgs := t.getAppArgs if tArgs.size < fvars.size then return none return some (mkAppRange (mkMVar mvarIdPending) fvars.size tArgs.size tArgs) private def isAssignable : Expr → MetaM Bool | Expr.mvar mvarId => do let b ← mvarId.isReadOnlyOrSyntheticOpaque; pure (!b) | _ => pure false private def etaEq (t s : Expr) : Bool := match t.etaExpanded? with | some t => t == s | none => false /-- Helper method for implementing `isDefEqProofIrrel`. Execute `k` with a transparency setting that is at least as strong as `.default`. This is important for modules that use the `.reducible` setting (e.g., `simp`, `rw`, etc). We added this feature to address issue #1302. ```lean @[simp] theorem get_cons_zero {as : List α} : (a :: as).get ⟨0, Nat.zero_lt_succ _⟩ = a := rfl example (a b c : α) : [a, b, c].get ⟨0, by simp⟩ = a := by simp ``` In the example above `simp` fails to use `get_cons_zero` because it fails to establish that the proof objects are definitionally equal using proof irrelevance. In this example, the propositions are ```lean 0 < Nat.succ (List.length [b, c]) =?= 0 < Nat.succ (Nat.succ (Nat.succ 0)) ``` So, unless we can unfold `List.length`, it fails. Remark: if this becomes a performance bottleneck, we should add a flag to control when it is used. Then, we can enable the flag only when applying `simp` and `rw` theorems. -/ private def withProofIrrelTransparency (k : MetaM α) : MetaM α := withAtLeastTransparency .default k private def isDefEqProofIrrel (t s : Expr) : MetaM LBool := do if (← getConfig).proofIrrelevance then match (← isProofQuick t) with | LBool.false => pure LBool.undef | LBool.true => let tType ← inferType t let sType ← inferType s toLBoolM <| withProofIrrelTransparency <| Meta.isExprDefEqAux tType sType | LBool.undef => let tType ← inferType t if (← isProp tType) then let sType ← inferType s toLBoolM <| withProofIrrelTransparency <| Meta.isExprDefEqAux tType sType else pure LBool.undef else pure LBool.undef /-- Try to solve constraint of the form `?m args₁ =?= ?m args₂`. - First try to unify `args₁` and `args₂`, and return true if successful - Otherwise, try to assign `?m` to a constant function of the form `fun x_1 ... x_n => ?n` where `?n` is a fresh metavariable. See `assignConst`. -/ private def isDefEqMVarSelf (mvar : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := do if args₁.size != args₂.size then pure false else if (← isDefEqArgs mvar args₁ args₂) then pure true else if !(← isAssignable mvar) then pure false else let cfg ← getConfig let mvarId := mvar.mvarId! let mvarDecl ← mvarId.getDecl if mvarDecl.numScopeArgs == args₁.size || cfg.constApprox then let type ← inferType (mkAppN mvar args₁) let auxMVar ← mkAuxMVar mvarDecl.lctx mvarDecl.localInstances type assignConst mvar args₁.size auxMVar else pure false /-- Remove unnecessary let-decls -/ private def consumeLet : Expr → Expr | e@(Expr.letE _ _ _ b _) => if b.hasLooseBVars then e else consumeLet b | e => e mutual private partial def isDefEqQuick (t s : Expr) : MetaM LBool := let t := consumeLet t let s := consumeLet s match t, s with | .lit l₁, .lit l₂ => return (l₁ == l₂).toLBool | .sort u, .sort v => toLBoolM <| isLevelDefEqAux u v | .lam .., .lam .. => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s | .forallE .., .forallE .. => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s -- | Expr.mdata _ t _, s => isDefEqQuick t s -- | t, Expr.mdata _ s _ => isDefEqQuick t s | .fvar fvarId₁, .fvar fvarId₂ => do if (← fvarId₁.isLetVar <||> fvarId₂.isLetVar) then return LBool.undef else if fvarId₁ == fvarId₂ then return LBool.true else isDefEqProofIrrel t s | t, s => isDefEqQuickOther t s private partial def isDefEqQuickOther (t s : Expr) : MetaM LBool := do /- We used to eagerly consume all metadata (see commented lines at `isDefEqQuick`), but it was unnecessarily removing helpful annotations for the pretty-printer. For example, consider the following example. ``` constant p : Nat → Prop constant q : Nat → Prop theorem p_of_q : q x → p x := sorry theorem pletfun : p (let_fun x := 0; x + 1) := by -- ⊢ p (let_fun x := 0; x + 1) apply p_of_q -- If we eagerly consume all metadata, the let_fun annotation is lost during `isDefEq` -- ⊢ q ((fun x => x + 1) 0) sorry ``` However, pattern annotations (`inaccessible?` and `patternWithRef?`) must be consumed. The frontend relies on the fact that is must not be propagated by `isDefEq`. Thus, we consume it here. This is a bit hackish since it is very adhoc. We might other annotations in the future that we should not preserve. Perhaps, we should mark the annotation we do want to preserve ones (e.g., hints for the pretty printer), and consume all other -/ if let some t := patternAnnotation? t then isDefEqQuick t s else if let some s := patternAnnotation? s then isDefEqQuick t s else if t == s then return LBool.true else if etaEq t s || etaEq s t then return LBool.true -- t =?= (fun xs => t xs) else let tFn := t.getAppFn let sFn := s.getAppFn if !tFn.isMVar && !sFn.isMVar then return LBool.undef else if (← isAssigned tFn) then let t ← instantiateMVars t isDefEqQuick t s else if (← isAssigned sFn) then let s ← instantiateMVars s isDefEqQuick t s else if let some t ← expandDelayedAssigned? t then isDefEqQuick t s else if let some s ← expandDelayedAssigned? s then isDefEqQuick t s /- Remark: we do not eagerly synthesize synthetic metavariables when the constraint is not stuck. Reason: we may fail to solve a constraint of the form `?x =?= A` when the synthesized instance is not definitionally equal to `A`. We left the code here as a remainder of this issue. -/ -- else if (← isSynthetic tFn <&&> trySynthPending tFn) then -- let t ← instantiateMVars t -- isDefEqQuick t s -- else if (← isSynthetic sFn <&&> trySynthPending sFn) then -- let s ← instantiateMVars s -- isDefEqQuick t s else if tFn.isMVar && sFn.isMVar && tFn == sFn then Bool.toLBool <$> isDefEqMVarSelf tFn t.getAppArgs s.getAppArgs else let tAssign? ← isAssignable tFn let sAssign? ← isAssignable sFn let assignableMsg (b : Bool) := if b then "[assignable]" else "[nonassignable]" trace[Meta.isDefEq] "{t} {assignableMsg tAssign?} =?= {s} {assignableMsg sAssign?}" if tAssign? && !sAssign? then toLBoolM <| processAssignment' t s else if !tAssign? && sAssign? then toLBoolM <| processAssignment' s t else if !tAssign? && !sAssign? then /- Trying to unify `?m ... =?= ?n ...` where both `?m` and `?n` cannot be assigned. This can happen when both of them are `syntheticOpaque` (e.g., metavars associated with tactics), or a metavariables from previous levels. If their types are propositions and are defeq, we can solve the constraint by proof irrelevance. This test is important for fixing a performance problem exposed by test `isDefEqPerfIssue.lean`. Without the proof irrelevance check, this example timeouts. Recall that: 1- The elaborator has a pending list of things to do: Tactics, TC, etc. 2- The elaborator only tries tactics after it tried to solve pending TC problems, delayed elaboratio, etc. The motivation: avoid unassigned metavariables in goals. 3- Each pending tactic goal is represented as a metavariable. It is marked as `synthethicOpaque` to make it clear that it should not be assigned by unification. 4- When we abstract a term containing metavariables, we often create new metavariables. Example: when abstracting `x` at `f ?m`, we obtain `fun x => f (?m' x)`. If `x` is in the scope of `?m`. If `?m` is `syntheticOpaque`, so is `?m'`, and we also have the delayed assignment `?m' x := ?m` 5- When checking a metavariable assignment, `?m := v` we check whether the type of `?m` is defeq to type of `v` with default reducibility setting. Now consider the following fragment ``` let a' := g 100 a ⟨i, h⟩ ⟨i - Nat.zero.succ, by exact Nat.lt_of_le_of_lt (Nat.pred_le i) h⟩ have : a'.size - i >= 0 := sorry f (i+1) a' ``` The elaborator tries to synthesize the instance `OfNat Nat 1` before we generate the tactic proof for `by exact ...` (remark 2). The solution `instOfNatNat 1` is synthesized. Let `m? a i h a' this` be the "hole" associated with the pending instance. Then, `isDefEq` tries to assign `m? a i h a' this := instOfNatNat 1` which is reduced to `m? := mkLambdaFVars #[a, i, h, a', this] (instOfNatNat 1)`. Note that, this is an abstraction step (remark 4), and the type contains the `syntheticOpaque` metavariable for the pending tactic proof (remark 3). Thus, a new `syntheticOpaque` opaque is created (remark 4). Then, `isDefEq` must check whether the type of `?m` is defeq to `mkLambdaFVars #[a, i, h, a', this] (instOfNatNat 1)` (remark 5). The two types are almost identical, but they contain different `syntheticOpaque` in the subterm corresponding to the `by exact ...` tactic proof. Without the following proof irrelevance test, the check will fail, and `isDefEq` timeouts unfolding `g` and its dependencies. Note that this test does not prevent a similar performance problem in a usecase where the tactic is used to synthesize a term that is not a proof. TODO: add better support for checking the delayed assignments. This is not high priority because tactics are usually only used for synthesizing proofs. -/ match (← isDefEqProofIrrel t s) with | LBool.true => return LBool.true | LBool.false => return LBool.false | _ => if tFn.isMVar || sFn.isMVar then let ctx ← read if ctx.config.isDefEqStuckEx then do trace[Meta.isDefEq.stuck] "{t} =?= {s}" Meta.throwIsDefEqStuck else return LBool.false else return LBool.undef else isDefEqQuickMVarMVar t s /-- Both `t` and `s` are terms of the form `?m ...` -/ private partial def isDefEqQuickMVarMVar (t s : Expr) : MetaM LBool := do if s.isMVar && !t.isMVar then /- Solve `?m t =?= ?n` by trying first `?n := ?m t`. Reason: this assignment is precise. -/ if (← checkpointDefEq (processAssignment s t)) then return LBool.true else toLBoolM <| processAssignment t s else if (← checkpointDefEq (processAssignment t s)) then return LBool.true else toLBoolM <| processAssignment s t end @[inline] def whenUndefDo (x : MetaM LBool) (k : MetaM Bool) : MetaM Bool := do let status ← x match status with | LBool.true => pure true | LBool.false => pure false | LBool.undef => k @[specialize] private def unstuckMVar (e : Expr) (successK : Expr → MetaM Bool) (failK : MetaM Bool): MetaM Bool := do match (← getStuckMVar? e) with | some mvarId => trace[Meta.isDefEq.stuckMVar] "found stuck MVar {mkMVar mvarId} : {← inferType (mkMVar mvarId)}" if (← Meta.synthPending mvarId) then let e ← instantiateMVars e successK e else failK | none => failK private def isDefEqOnFailure (t s : Expr) : MetaM Bool := do trace[Meta.isDefEq.onFailure] "{t} =?= {s}" unstuckMVar t (fun t => Meta.isExprDefEqAux t s) <| unstuckMVar s (fun s => Meta.isExprDefEqAux t s) <| tryUnificationHints t s <||> tryUnificationHints s t private def isDefEqProj : Expr → Expr → MetaM Bool | Expr.proj _ i t, Expr.proj _ j s => pure (i == j) <&&> Meta.isExprDefEqAux t s | Expr.proj structName 0 s, v => isDefEqSingleton structName s v | v, Expr.proj structName 0 s => isDefEqSingleton structName s v | _, _ => pure false where /-- If `structName` is a structure with a single field and `(?m ...).1 =?= v`, then solve contraint as `?m ... =?= ⟨v⟩` -/ isDefEqSingleton (structName : Name) (s : Expr) (v : Expr) : MetaM Bool := do let ctorVal := getStructureCtor (← getEnv) structName if ctorVal.numFields != 1 then return false -- It is not a structure with a single field. let sType ← whnf (← inferType s) let sTypeFn := sType.getAppFn if !sTypeFn.isConstOf structName then return false let s ← whnf s let sFn := s.getAppFn if !sFn.isMVar then return false if (← isAssignable sFn) then let ctorApp := mkApp (mkAppN (mkConst ctorVal.name sTypeFn.constLevels!) sType.getAppArgs) v processAssignment' s ctorApp else return false /-- Given applications `t` and `s` that are in WHNF (modulo the current transparency setting), check whether they are definitionally equal or not. -/ private def isDefEqApp (t s : Expr) : MetaM Bool := do let tFn := t.getAppFn let sFn := s.getAppFn if tFn.isConst && sFn.isConst && tFn.constName! == sFn.constName! then /- See comment at `tryHeuristic` explaining why we processe arguments before universe levels. -/ if (← checkpointDefEq (isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels!)) then return true else isDefEqOnFailure t s else if (← checkpointDefEq (Meta.isExprDefEqAux tFn s.getAppFn <&&> isDefEqArgs tFn t.getAppArgs s.getAppArgs)) then return true else isDefEqOnFailure t s /-- Return `true` if the types of the given expressions is an inductive datatype with an inductive datatype with a single constructor with no fields. -/ private def isDefEqUnitLike (t : Expr) (s : Expr) : MetaM Bool := do let tType ← whnf (← inferType t) matchConstStruct tType.getAppFn (fun _ => return false) fun _ _ ctorVal => do if ctorVal.numFields != 0 then return false else if (← useEtaStruct ctorVal.induct) then Meta.isExprDefEqAux tType (← inferType s) else return false /-- The `whnf` procedure has support for unfolding class projections when the transparency mode is set to `.instances`. This method ensures the behavior of `whnf` and `isDefEq` is consistent in this transparency mode. -/ private def isDefEqProjInst (t : Expr) (s : Expr) : MetaM LBool := do if (← getTransparency) != .instances then return .undef let t? ← unfoldProjInstWhenIntances? t let s? ← unfoldProjInstWhenIntances? s if t?.isSome || s?.isSome then toLBoolM <| Meta.isExprDefEqAux (t?.getD t) (s?.getD s) else return .undef private def isExprDefEqExpensive (t : Expr) (s : Expr) : MetaM Bool := do if (← (isDefEqEta t s <||> isDefEqEta s t)) then return true -- TODO: investigate whether this is the place for putting this check if (← (isDefEqEtaStruct t s <||> isDefEqEtaStruct s t)) then return true if (← isDefEqProj t s) then return true let t' ← whnfCore t let s' ← whnfCore s if t != t' || s != s' then Meta.isExprDefEqAux t' s' else whenUndefDo (isDefEqNative t s) do whenUndefDo (isDefEqNat t s) do whenUndefDo (isDefEqOffset t s) do whenUndefDo (isDefEqDelta t s) do if t.isConst && s.isConst then if t.constName! == s.constName! then isListLevelDefEqAux t.constLevels! s.constLevels! else return false else if (← pure t.isApp <&&> pure s.isApp <&&> isDefEqApp t s) then return true else whenUndefDo (isDefEqProjInst t s) do whenUndefDo (isDefEqStringLit t s) do if (← isDefEqUnitLike t s) then return true else isDefEqOnFailure t s private def mkCacheKey (t : Expr) (s : Expr) : Expr × Expr := if Expr.quickLt t s then (t, s) else (s, t) private def getCachedResult (key : Expr × Expr) : MetaM LBool := do match (← get).cache.defEq.find? key with | some val => return val.toLBool | none => return .undef private def cacheResult (key : Expr × Expr) (result : Bool) : MetaM Unit := do modifyDefEqCache fun c => c.insert key result @[export lean_is_expr_def_eq] partial def isExprDefEqAuxImpl (t : Expr) (s : Expr) : MetaM Bool := withIncRecDepth do withTraceNode `Meta.isDefEq (return m!"{exceptBoolEmoji ·} {t} =?= {s}") do checkMaxHeartbeats "isDefEq" whenUndefDo (isDefEqQuick t s) do whenUndefDo (isDefEqProofIrrel t s) do -- We perform `whnfCore` again with `deltaAtProj := true` at `isExprDefEqExpensive` after `isDefEqProj` let t' ← whnfCore t (deltaAtProj := false) let s' ← whnfCore s (deltaAtProj := false) if t != t' || s != s' then isExprDefEqAuxImpl t' s' else /- TODO: check whether the following `instantiateMVar`s are expensive or not in practice. Lean 3 does not use them, and may miss caching opportunities since it is not safe to cache when `t` and `s` may contain mvars. The unit test `tryHeuristicPerfIssue2.lean` cannot be solved without these two `instantiateMVar`s. If it becomes a problem, we may use store a flag in the context indicating whether we have already used `instantiateMVar` in outer invocations or not. It is not perfect (we may assign mvars in nested calls), but it should work well enough in practice, and prevent repeated traversals in nested calls. -/ let t ← instantiateMVars t let s ← instantiateMVars s let numPostponed ← getNumPostponed let k := mkCacheKey t s match (← getCachedResult k) with | .true => trace[Meta.isDefEq.cache] "cache hit 'true' for {t} =?= {s}" return true | .false => trace[Meta.isDefEq.cache] "cache hit 'false' for {t} =?= {s}" return false | .undef => let result ← isExprDefEqExpensive t s if numPostponed == (← getNumPostponed) then trace[Meta.isDefEq.cache] "cache {result} for {t} =?= {s}" cacheResult k result return result builtin_initialize registerTraceClass `Meta.isDefEq registerTraceClass `Meta.isDefEq.foApprox registerTraceClass `Meta.isDefEq.constApprox registerTraceClass `Meta.isDefEq.delta (inherited := true) registerTraceClass `Meta.isDefEq.assign registerTraceClass `Meta.isDefEq.assign.checkTypes (inherited := true) registerTraceClass `Meta.isDefEq.eta.struct end Lean.Meta
4fba9a64e692ce566ef44f10c5dcac9fa2029666
b392eb79fb36952401156496daa60628ccb07438
/Lib4/PostPort.lean
3008c53149241791f2a60ed27eda7d2db63f9a68
[ "Apache-2.0" ]
permissive
AurelienSaue/mathportsource
d9eabe74e3ab7774baa6a10a6dc8d4855ff92266
1a164e4fff7204c522c1f4ecc5024fd909be3b0b
refs/heads/master
1,685,214,377,305
1,623,621,223,000
1,623,621,223,000
364,191,042
0
0
null
null
null
null
UTF-8
Lean
false
false
207
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ import PostPort.Coe import PostPort.Pow
ea3a675e9f3662edb823785af6fdfadd4a70d4ab
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/number_theory/bernoulli_polynomials.lean
4138f46586aeffda955636e38a29d4c0a53a9def
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,118
lean
/- Copyright (c) 2021 Ashvni Narayanan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ashvni Narayanan -/ import data.nat.choose.cast import number_theory.bernoulli /-! # Bernoulli polynomials The Bernoulli polynomials (defined here : https://en.wikipedia.org/wiki/Bernoulli_polynomials) are an important tool obtained from Bernoulli numbers. ## Mathematical overview The $n$-th Bernoulli polynomial is defined as $$ B_n(X) = ∑_{k = 0}^n {n \choose k} (-1)^k * B_k * X^{n - k} $$ where $B_k$ is the $k$-th Bernoulli number. The Bernoulli polynomials are generating functions, $$ t * e^{tX} / (e^t - 1) = ∑_{n = 0}^{\infty} B_n(X) * \frac{t^n}{n!} $$ ## Implementation detail Bernoulli polynomials are defined using `bernoulli`, the Bernoulli numbers. ## Main theorems - `sum_bernoulli_poly`: The sum of the $k^\mathrm{th}$ Bernoulli polynomial with binomial coefficients up to n is `(n + 1) * X^n`. - `exp_bernoulli_poly`: The Bernoulli polynomials act as generating functions for the exponential. ## TODO - `bernoulli_poly_eval_one_neg` : $$ B_n(1 - x) = (-1)^n*B_n(x) $$ - ``bernoulli_poly_eval_one` : Follows as a consequence of `bernoulli_poly_eval_one_neg`. -/ noncomputable theory open_locale big_operators open_locale nat open nat finset /-- The Bernoulli polynomials are defined in terms of the negative Bernoulli numbers. -/ def bernoulli_poly (n : ℕ) : polynomial ℚ := ∑ i in range (n + 1), polynomial.monomial (n - i) ((bernoulli i) * (choose n i)) lemma bernoulli_poly_def (n : ℕ) : bernoulli_poly n = ∑ i in range (n + 1), polynomial.monomial i ((bernoulli (n - i)) * (choose n i)) := begin rw [←sum_range_reflect, add_succ_sub_one, add_zero, bernoulli_poly], apply sum_congr rfl, rintros x hx, rw mem_range_succ_iff at hx, rw [choose_symm hx, nat.sub_sub_self hx], end namespace bernoulli_poly /- ### examples -/ section examples @[simp] lemma bernoulli_poly_zero : bernoulli_poly 0 = 1 := by simp [bernoulli_poly] @[simp] lemma bernoulli_poly_eval_zero (n : ℕ) : (bernoulli_poly n).eval 0 = bernoulli n := begin rw [bernoulli_poly, polynomial.eval_finset_sum, sum_range_succ], have : ∑ (x : ℕ) in range n, bernoulli x * (n.choose x) * 0 ^ (n - x) = 0, { apply sum_eq_zero (λ x hx, _), have h : 0 < n - x := nat.sub_pos_of_lt (mem_range.1 hx), simp [h] }, simp [this], end @[simp] lemma bernoulli_poly_eval_one (n : ℕ) : (bernoulli_poly n).eval 1 = bernoulli' n := begin simp only [bernoulli_poly, polynomial.eval_finset_sum], simp only [←succ_eq_add_one, sum_range_succ, mul_one, cast_one, choose_self, (bernoulli _).mul_comm, sum_bernoulli, one_pow, mul_one, polynomial.eval_C, polynomial.eval_monomial], by_cases h : n = 1, { norm_num [h], }, { simp [h], exact bernoulli_eq_bernoulli'_of_ne_one h, } end end examples @[simp] theorem sum_bernoulli_poly (n : ℕ) : ∑ k in range (n + 1), ((n + 1).choose k : ℚ) • bernoulli_poly k = polynomial.monomial n (n + 1 : ℚ) := begin simp_rw [bernoulli_poly_def, finset.smul_sum, finset.range_eq_Ico, ←finset.sum_Ico_Ico_comm, finset.sum_Ico_eq_sum_range], simp only [cast_succ, nat.add_sub_cancel_left, nat.sub_zero, zero_add, linear_map.map_add], simp_rw [polynomial.smul_monomial, mul_comm (bernoulli _) _, smul_eq_mul, ←mul_assoc], conv_lhs { apply_congr, skip, conv { apply_congr, skip, rw [← nat.cast_mul, choose_mul ((nat.le_sub_left_iff_add_le $ mem_range_le H).1 $ mem_range_le H_1) (le.intro rfl), nat.cast_mul, add_comm x x_1, nat.add_sub_cancel, mul_assoc, mul_comm, ←smul_eq_mul, ←polynomial.smul_monomial] }, rw [←sum_smul], }, rw [sum_range_succ_comm], simp only [add_right_eq_self, cast_succ, mul_one, cast_one, cast_add, nat.add_sub_cancel_left, choose_succ_self_right, one_smul, bernoulli_zero, sum_singleton, zero_add, linear_map.map_add, range_one], apply sum_eq_zero (λ x hx, _), have f : ∀ x ∈ range n, ¬ n + 1 - x = 1, { rintros x H, rw [mem_range] at H, rw [eq_comm], exact ne_of_lt (nat.lt_of_lt_of_le one_lt_two (nat.le_sub_left_of_add_le (succ_le_succ H))) }, rw [sum_bernoulli], have g : (ite (n + 1 - x = 1) (1 : ℚ) 0) = 0, { simp only [ite_eq_right_iff, one_ne_zero], intro h₁, exact (f x hx) h₁, }, rw [g, zero_smul], end open power_series open polynomial (aeval) variables {A : Type*} [comm_ring A] [algebra ℚ A] -- TODO: define exponential generating functions, and use them here -- This name should probably be updated afterwards /-- The theorem that `∑ Bₙ(t)X^n/n!)(e^X-1)=Xe^{tX}` -/ theorem exp_bernoulli_poly' (t : A) : mk (λ n, aeval t ((1 / n! : ℚ) • bernoulli_poly n)) * (exp A - 1) = X * rescale t (exp A) := begin -- check equality of power series by checking coefficients of X^n ext n, -- n = 0 case solved by `simp` cases n, { simp }, -- n ≥ 1, the coefficients is a sum to n+2, so use `sum_range_succ` to write as -- last term plus sum to n+1 rw [coeff_succ_X_mul, coeff_rescale, coeff_exp, coeff_mul, nat.sum_antidiagonal_eq_sum_range_succ_mk, sum_range_succ], -- last term is zero so kill with `add_zero` simp only [ring_hom.map_sub, nat.sub_self, constant_coeff_one, constant_coeff_exp, coeff_zero_eq_constant_coeff, mul_zero, sub_self, add_zero], -- Let's multiply both sides by (n+1)! (OK because it's a unit) set u : units ℚ := ⟨(n+1)!, (n+1)!⁻¹, mul_inv_cancel (by exact_mod_cast factorial_ne_zero (n+1)), inv_mul_cancel (by exact_mod_cast factorial_ne_zero (n+1))⟩ with hu, rw ←units.mul_right_inj (units.map (algebra_map ℚ A).to_monoid_hom u), -- now tidy up unit mess and generally do trivial rearrangements -- to make RHS (n+1)*t^n rw [units.coe_map, mul_left_comm, ring_hom.to_monoid_hom_eq_coe, ring_hom.coe_monoid_hom, ←ring_hom.map_mul, hu, units.coe_mk], change _ = t^n * algebra_map ℚ A (((n+1)*n! : ℕ)*(1/n!)), rw [cast_mul, mul_assoc, mul_one_div_cancel (show (n! : ℚ) ≠ 0, from cast_ne_zero.2 (factorial_ne_zero n)), mul_one, mul_comm (t^n), ← polynomial.aeval_monomial, cast_add, cast_one], -- But this is the RHS of `sum_bernoulli_poly` rw [← sum_bernoulli_poly, finset.mul_sum, alg_hom.map_sum], -- and now we have to prove a sum is a sum, but all the terms are equal. apply finset.sum_congr rfl, -- The rest is just trivialities, hampered by the fact that we're coercing -- factorials and binomial coefficients between ℕ and ℚ and A. intros i hi, -- deal with coefficients of e^X-1 simp only [nat.cast_choose ℚ (mem_range_le hi), coeff_mk, if_neg (mem_range_sub_ne_zero hi), one_div, alg_hom.map_smul, coeff_one, units.coe_mk, coeff_exp, sub_zero, linear_map.map_sub, algebra.smul_mul_assoc, algebra.smul_def, mul_right_comm _ ((aeval t) _), ←mul_assoc, ← ring_hom.map_mul, succ_eq_add_one], -- finally cancel the Bernoulli polynomial and the algebra_map congr', apply congr_arg, rw [mul_assoc, div_eq_mul_inv, ← mul_inv₀], end end bernoulli_poly
fe7278edcdbb6bab8b0d8029192a494d1188265f
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/section3.lean
771a6565ce78f9702f58d9d76753090eb230ccba
[ "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
110
lean
section parameter (A : Type) definition foo := A definition bar {X : Type} {A : X} : foo := sorry end
7db8e6823a082779f057c339a3cf1f9cac063032
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/number_theory/dioph.lean
758029d21859cc987d9e2db7b1b42b4cb2f55acf
[ "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
36,071
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import number_theory.pell data.pfun universe u open nat function namespace int lemma eq_nat_abs_iff_mul (x n) : nat_abs x = n ↔ (x - n) * (x + n) = 0 := begin refine iff.trans _ mul_eq_zero.symm, refine iff.trans _ (or_congr sub_eq_zero add_eq_zero_iff_eq_neg).symm, exact ⟨λe, by rw ← e; apply nat_abs_eq, λo, by cases o; subst x; simp [nat_abs_of_nat]⟩ end end int /-- An alternate definition of `fin n` defined as an inductive type instead of a subtype of `nat`. This is useful for its induction principle and different definitional equalities. -/ inductive fin2 : ℕ → Type | fz {n} : fin2 (succ n) | fs {n} : fin2 n → fin2 (succ n) namespace fin2 @[elab_as_eliminator] protected def cases' {n} {C : fin2 (succ n) → Sort u} (H1 : C fz) (H2 : Π n, C (fs n)) : Π (i : fin2 (succ n)), C i | fz := H1 | (fs n) := H2 n def elim0 {C : fin2 0 → Sort u} : Π (i : fin2 0), C i. /-- convert a `fin2` into a `nat` -/ def to_nat : Π {n}, fin2 n → ℕ | ._ (@fz n) := 0 | ._ (@fs n i) := succ (to_nat i) /-- convert a `nat` into a `fin2` if it is in range -/ def opt_of_nat : Π {n} (k : ℕ), option (fin2 n) | 0 _ := none | (succ n) 0 := some fz | (succ n) (succ k) := fs <$> @opt_of_nat n k /-- `i + k : fin2 (n + k)` when `i : fin2 n` and `k : ℕ` -/ def add {n} (i : fin2 n) : Π k, fin2 (n + k) | 0 := i | (succ k) := fs (add k) /-- `left k` is the embedding `fin2 n → fin2 (k + n)` -/ def left (k) : Π {n}, fin2 n → fin2 (k + n) | ._ (@fz n) := fz | ._ (@fs n i) := fs (left i) /-- `insert_perm a` is a permutation of `fin2 n` with the following properties: * `insert_perm a i = i+1` if `i < a` * `insert_perm a a = 0` * `insert_perm a i = i` if `i > a` -/ def insert_perm : Π {n}, fin2 n → fin2 n → fin2 n | ._ (@fz n) (@fz ._) := fz | ._ (@fz n) (@fs ._ j) := fs j | ._ (@fs (succ n) i) (@fz ._) := fs fz | ._ (@fs (succ n) i) (@fs ._ j) := match insert_perm i j with fz := fz | fs k := fs (fs k) end /-- `remap_left f k : fin2 (m + k) → fin2 (n + k)` applies the function `f : fin2 m → fin2 n` to inputs less than `m`, and leaves the right part on the right (that is, `remap_left f k (m + i) = n + i`). -/ def remap_left {m n} (f : fin2 m → fin2 n) : Π k, fin2 (m + k) → fin2 (n + k) | 0 i := f i | (succ k) (@fz ._) := fz | (succ k) (@fs ._ i) := fs (remap_left _ i) /-- This is a simple type class inference prover for proof obligations of the form `m < n` where `m n : ℕ`. -/ class is_lt (m n : ℕ) := (h : m < n) instance is_lt.zero (n) : is_lt 0 (succ n) := ⟨succ_pos _⟩ instance is_lt.succ (m n) [l : is_lt m n] : is_lt (succ m) (succ n) := ⟨succ_lt_succ l.h⟩ /-- Use type class inference to infer the boundedness proof, so that we can directly convert a `nat` into a `fin2 n`. This supports notation like `&1 : fin 3`. -/ def of_nat' : Π {n} m [is_lt m n], fin2 n | 0 m ⟨h⟩ := absurd h (not_lt_zero _) | (succ n) 0 ⟨h⟩ := fz | (succ n) (succ m) ⟨h⟩ := fs (@of_nat' n m ⟨lt_of_succ_lt_succ h⟩) local prefix `&`:max := of_nat' end fin2 open fin2 /-- Alternate definition of `vector` based on `fin2`. -/ def vector3 (α : Type u) (n : ℕ) : Type u := fin2 n → α namespace vector3 /-- The empty vector -/ @[pattern] def nil {α} : vector3 α 0. /-- The vector cons operation -/ @[pattern] def cons {α} {n} (a : α) (v : vector3 α n) : vector3 α (succ n) := λi, by {refine i.cases' _ _, exact a, exact v} notation a :: b := cons a b notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l @[simp] theorem cons_fz {α} {n} (a : α) (v : vector3 α n) : (a :: v) fz = a := rfl @[simp] theorem cons_fs {α} {n} (a : α) (v : vector3 α n) (i) : (a :: v) (fs i) = v i := rfl /-- Get the `i`th element of a vector -/ @[reducible] def nth {α} {n} (i : fin2 n) (v : vector3 α n) : α := v i /-- Construct a vector from a function on `fin2`. -/ @[reducible] def of_fn {α} {n} (f : fin2 n → α) : vector3 α n := f /-- Get the head of a nonempty vector. -/ def head {α} {n} (v : vector3 α (succ n)) : α := v fz /-- Get the tail of a nonempty vector. -/ def tail {α} {n} (v : vector3 α (succ n)) : vector3 α n := λi, v (fs i) theorem eq_nil {α} (v : vector3 α 0) : v = [] := funext $ λi, match i with end theorem cons_head_tail {α} {n} (v : vector3 α (succ n)) : head v :: tail v = v := funext $ λi, fin2.cases' rfl (λ_, rfl) i def nil_elim {α} {C : vector3 α 0 → Sort u} (H : C []) (v : vector3 α 0) : C v := by rw eq_nil v; apply H def cons_elim {α n} {C : vector3 α (succ n) → Sort u} (H : Π (a : α) (t : vector3 α n), C (a :: t)) (v : vector3 α (succ n)) : C v := by rw ← (cons_head_tail v); apply H @[simp] theorem cons_elim_cons {α n C H a t} : @cons_elim α n C H (a :: t) = H a t := rfl @[elab_as_eliminator] protected def rec_on {α} {C : Π {n}, vector3 α n → Sort u} {n} (v : vector3 α n) (H0 : C []) (Hs : Π {n} (a) (w : vector3 α n), C w → C (a :: w)) : C v := nat.rec_on n (λv, v.nil_elim H0) (λn IH v, v.cons_elim (λa t, Hs _ _ (IH _))) v @[simp] theorem rec_on_nil {α C H0 Hs} : @vector3.rec_on α @C 0 [] H0 @Hs = H0 := rfl @[simp] theorem rec_on_cons {α C H0 Hs n a v} : @vector3.rec_on α @C (succ n) (a :: v) H0 @Hs = Hs a v (@vector3.rec_on α @C n v H0 @Hs) := rfl /-- Append two vectors -/ def append {α} {m} (v : vector3 α m) {n} (w : vector3 α n) : vector3 α (n+m) := nat.rec_on m (λ_, w) (λm IH v, v.cons_elim $ λa t, @fin2.cases' (n+m) (λ_, α) a (IH t)) v infix ` +-+ `:65 := append @[simp] theorem append_nil {α} {n} (w : vector3 α n) : [] +-+ w = w := rfl @[simp] theorem append_cons {α} (a : α) {m} (v : vector3 α m) {n} (w : vector3 α n) : (a::v) +-+ w = a :: (v +-+ w) := rfl @[simp] theorem append_left {α} : ∀ {m} (i : fin2 m) (v : vector3 α m) {n} (w : vector3 α n), (v +-+ w) (left n i) = v i | ._ (@fz m) v n w := v.cons_elim (λa t, by simp [*, left]) | ._ (@fs m i) v n w := v.cons_elim (λa t, by simp [*, left]) @[simp] theorem append_add {α} : ∀ {m} (v : vector3 α m) {n} (w : vector3 α n) (i : fin2 n), (v +-+ w) (add i m) = w i | 0 v n w i := rfl | (succ m) v n w i := v.cons_elim (λa t, by simp [*, add]) /-- Insert `a` into `v` at index `i`. -/ def insert {α} (a : α) {n} (v : vector3 α n) (i : fin2 (succ n)) : vector3 α (succ n) := λj, (a :: v) (insert_perm i j) @[simp] theorem insert_fz {α} (a : α) {n} (v : vector3 α n) : insert a v fz = a :: v := by refine funext (λj, j.cases' _ _); intros; refl @[simp] theorem insert_fs {α} (a : α) {n} (b : α) (v : vector3 α n) (i : fin2 (succ n)) : insert a (b :: v) (fs i) = b :: insert a v i := funext $ λj, by { refine j.cases' _ (λj, _); simp [insert, insert_perm], refine fin2.cases' _ _ (insert_perm i j); simp [insert_perm] } theorem append_insert {α} (a : α) {k} (t : vector3 α k) {n} (v : vector3 α n) (i : fin2 (succ n)) (e : succ n + k = succ (n + k)) : insert a (t +-+ v) (eq.rec_on e (i.add k)) = eq.rec_on e (t +-+ insert a v i) := begin refine vector3.rec_on t (λe, _) (λk b t IH e, _) e, refl, have e' := succ_add n k, change insert a (b :: (t +-+ v)) (eq.rec_on (congr_arg succ e') (fs (add i k))) = eq.rec_on (congr_arg succ e') (b :: (t +-+ insert a v i)), rw ← (eq.drec_on e' rfl : fs (eq.rec_on e' (i.add k) : fin2 (succ (n + k))) = eq.rec_on (congr_arg succ e') (fs (i.add k))), simp, rw IH, exact eq.drec_on e' rfl end end vector3 open vector3 /-- "Curried" exists, i.e. ∃ x1 ... xn, f [x1, ..., xn] -/ def vector_ex {α} : Π k, (vector3 α k → Prop) → Prop | 0 f := f [] | (succ k) f := ∃x : α, vector_ex k (λv, f (x :: v)) /-- "Curried" forall, i.e. ∀ x1 ... xn, f [x1, ..., xn] -/ def vector_all {α} : Π k, (vector3 α k → Prop) → Prop | 0 f := f [] | (succ k) f := ∀x : α, vector_all k (λv, f (x :: v)) theorem exists_vector_zero {α} (f : vector3 α 0 → Prop) : Exists f ↔ f [] := ⟨λ⟨v, fv⟩, by rw ← (eq_nil v); exact fv, λf0, ⟨[], f0⟩⟩ theorem exists_vector_succ {α n} (f : vector3 α (succ n) → Prop) : Exists f ↔ ∃x v, f (x :: v) := ⟨λ⟨v, fv⟩, ⟨_, _, by rw cons_head_tail v; exact fv⟩, λ⟨x, v, fxv⟩, ⟨_, fxv⟩⟩ theorem vector_ex_iff_exists {α} : ∀ {n} (f : vector3 α n → Prop), vector_ex n f ↔ Exists f | 0 f := (exists_vector_zero f).symm | (succ n) f := iff.trans (exists_congr (λx, vector_ex_iff_exists _)) (exists_vector_succ f).symm theorem vector_all_iff_forall {α} : ∀ {n} (f : vector3 α n → Prop), vector_all n f ↔ ∀ v, f v | 0 f := ⟨λf0 v, v.nil_elim f0, λal, al []⟩ | (succ n) f := (forall_congr (λx, vector_all_iff_forall (λv, f (x :: v)))).trans ⟨λal v, v.cons_elim al, λal x v, al (x::v)⟩ /-- `vector_allp p v` is equivalent to `∀ i, p (v i)`, but unfolds directly to a conjunction, i.e. `vector_allp p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/ def vector_allp {α} (p : α → Prop) {n} (v : vector3 α n) : Prop := vector3.rec_on v true (λn a v IH, @vector3.rec_on _ (λn v, Prop) _ v (p a) (λn b v' _, p a ∧ IH)) @[simp] theorem vector_allp_nil {α} (p : α → Prop) : vector_allp p [] = true := rfl @[simp] theorem vector_allp_singleton {α} (p : α → Prop) (x : α) : vector_allp p [x] = p x := rfl @[simp] theorem vector_allp_cons {α} (p : α → Prop) {n} (x : α) (v : vector3 α n) : vector_allp p (x :: v) ↔ p x ∧ vector_allp p v := vector3.rec_on v (and_true _).symm (λn a v IH, iff.rfl) theorem vector_allp_iff_forall {α} (p : α → Prop) {n} (v : vector3 α n) : vector_allp p v ↔ ∀ i, p (v i) := begin refine v.rec_on _ _, { exact ⟨λ_, fin2.elim0, λ_, trivial⟩ }, { simp, refine λn a v IH, (and_congr_right (λ_, IH)).trans ⟨λ⟨pa, h⟩ i, by {refine i.cases' _ _, exacts [pa, h]}, λh, ⟨_, λi, _⟩⟩, { have h0 := h fz, simp at h0, exact h0 }, { have hs := h (fs i), simp at hs, exact hs } } end theorem vector_allp.imp {α} {p q : α → Prop} (h : ∀ x, p x → q x) {n} {v : vector3 α n} (al : vector_allp p v) : vector_allp q v := (vector_allp_iff_forall _ _).2 (λi, h _ $ (vector_allp_iff_forall _ _).1 al _) /-- `list_all p l` is equivalent to `∀ a ∈ l, p a`, but unfolds directly to a conjunction, i.e. `list_all p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/ @[simp] def list_all {α} (p : α → Prop) : list α → Prop | [] := true | (x :: []) := p x | (x :: l) := p x ∧ list_all l @[simp] theorem list_all_cons {α} (p : α → Prop) (x : α) : ∀ (l : list α), list_all p (x :: l) ↔ p x ∧ list_all p l | [] := (and_true _).symm | (x :: l) := iff.rfl theorem list_all_iff_forall {α} (p : α → Prop) : ∀ (l : list α), list_all p l ↔ ∀ x ∈ l, p x | [] := (iff_true_intro $ list.ball_nil _).symm | (x :: l) := by rw [list.ball_cons, ← list_all_iff_forall l]; simp theorem list_all.imp {α} {p q : α → Prop} (h : ∀ x, p x → q x) : ∀ {l : list α}, list_all p l → list_all q l | [] := id | (x :: l) := by simpa using and.imp (h x) list_all.imp @[simp] theorem list_all_map {α β} {p : β → Prop} (f : α → β) {l : list α} : list_all p (l.map f) ↔ list_all (p ∘ f) l := by induction l; simp * theorem list_all_congr {α} {p q : α → Prop} (h : ∀ x, p x ↔ q x) {l : list α} : list_all p l ↔ list_all q l := ⟨list_all.imp (λx, (h x).1), list_all.imp (λx, (h x).2)⟩ instance decidable_list_all {α} (p : α → Prop) [decidable_pred p] (l : list α) : decidable (list_all p l) := decidable_of_decidable_of_iff (by apply_instance) (list_all_iff_forall _ _).symm /- poly -/ /-- A predicate asserting that a function is a multivariate integer polynomial. (We are being a bit lazy here by allowing many representations for multiplication, rather than only allowing monomials and addition, but the definition is equivalent and this is easier to use.) -/ inductive is_poly {α} : ((α → ℕ) → ℤ) → Prop | proj : ∀ i, is_poly (λx : α → ℕ, x i) | const : Π (n : ℤ), is_poly (λx : α → ℕ, n) | sub : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λx, f x - g x) | mul : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λx, f x * g x) /-- The type of multivariate integer polynomials -/ def poly (α : Type u) := {f : (α → ℕ) → ℤ // is_poly f} namespace poly section parameter {α : Type u} instance : has_coe_to_fun (poly α) := ⟨_, λ f, f.1⟩ /-- The underlying function of a `poly` is a polynomial -/ def isp (f : poly α) : is_poly f := f.2 /-- Extensionality for `poly α` -/ def ext {f g : poly α} (e : ∀x, f x = g x) : f = g := subtype.eq (funext e) /-- Construct a `poly` given an extensionally equivalent `poly`. -/ def subst (f : poly α) (g : (α → ℕ) → ℤ) (e : ∀x, f x = g x) : poly α := ⟨g, by rw ← (funext e : coe_fn f = g); exact f.isp⟩ @[simp] theorem subst_eval (f g e x) : subst f g e x = g x := rfl /-- The `i`th projection function, `x_i`. -/ def proj (i) : poly α := ⟨_, is_poly.proj i⟩ @[simp] theorem proj_eval (i x) : proj i x = x i := rfl /-- The constant function with value `n : ℤ`. -/ def const (n) : poly α := ⟨_, is_poly.const n⟩ @[simp] theorem const_eval (n x) : const n x = n := rfl /-- The zero polynomial -/ def zero : poly α := const 0 instance : has_zero (poly α) := ⟨poly.zero⟩ @[simp] theorem zero_eval (x) : (0 : poly α) x = 0 := rfl /-- The zero polynomial -/ def one : poly α := const 1 instance : has_one (poly α) := ⟨poly.one⟩ @[simp] theorem one_eval (x) : (1 : poly α) x = 1 := rfl /-- Subtraction of polynomials -/ def sub : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := ⟨_, is_poly.sub pf pg⟩ instance : has_sub (poly α) := ⟨poly.sub⟩ @[simp] theorem sub_eval : Π (f g x), (f - g : poly α) x = f x - g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl /-- Negation of a polynomial -/ def neg (f : poly α) : poly α := 0 - f instance : has_neg (poly α) := ⟨poly.neg⟩ @[simp] theorem neg_eval (f x) : (-f : poly α) x = -f x := show (0-f) x = _, by simp /-- Addition of polynomials -/ def add : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := subst (⟨f, pf⟩ - -⟨g, pg⟩) _ (λx, show f x - (0 - g x) = f x + g x, by simp) instance : has_add (poly α) := ⟨poly.add⟩ @[simp] theorem add_eval : Π (f g x), (f + g : poly α) x = f x + g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl /-- Multiplication of polynomials -/ def mul : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := ⟨_, is_poly.mul pf pg⟩ instance : has_mul (poly α) := ⟨poly.mul⟩ @[simp] theorem mul_eval : Π (f g x), (f * g : poly α) x = f x * g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl instance : comm_ring (poly α) := by refine { add := (+), zero := 0, neg := has_neg.neg, mul := (*), one := 1, .. }; {intros, exact ext (λx, by simp [mul_add, mul_left_comm, mul_comm])} def induction {C : poly α → Prop} (H1 : ∀i, C (proj i)) (H2 : ∀n, C (const n)) (H3 : ∀f g, C f → C g → C (f - g)) (H4 : ∀f g, C f → C g → C (f * g)) (f : poly α) : C f := begin cases f with f pf, induction pf with i n f g pf pg ihf ihg f g pf pg ihf ihg, apply H1, apply H2, apply H3 _ _ ihf ihg, apply H4 _ _ ihf ihg end /-- The sum of squares of a list of polynomials. This is relevant for Diophantine equations, because it means that a list of equations can be encoded as a single equation: `x = 0 ∧ y = 0 ∧ z = 0` is equivalent to `x^2 + y^2 + z^2 = 0`. -/ def sumsq : list (poly α) → poly α | [] := 0 | (p::ps) := p*p + sumsq ps theorem sumsq_nonneg (x) : ∀ l, 0 ≤ sumsq l x | [] := le_refl 0 | (p::ps) := by rw sumsq; simp [-add_comm]; exact add_nonneg (mul_self_nonneg _) (sumsq_nonneg ps) theorem sumsq_eq_zero (x) : ∀ l, sumsq l x = 0 ↔ list_all (λa : poly α, a x = 0) l | [] := eq_self_iff_true _ | (p::ps) := by rw [list_all_cons, ← sumsq_eq_zero ps]; rw sumsq; simp [-add_comm]; exact ⟨λ(h : p x * p x + sumsq ps x = 0), have p x = 0, from eq_zero_of_mul_self_eq_zero $ le_antisymm (by rw ← h; have t := add_le_add_left (sumsq_nonneg x ps) (p x * p x); rwa [add_zero] at t) (mul_self_nonneg _), ⟨this, by simp [this] at h; exact h⟩, λ⟨h1, h2⟩, by rw [h1, h2]; refl⟩ end /-- Map the index set of variables, replacing `x_i` with `x_(f i)`. -/ def remap {α β} (f : α → β) (g : poly α) : poly β := ⟨λv, g $ v ∘ f, g.induction (λi, by simp; apply is_poly.proj) (λn, by simp; apply is_poly.const) (λf g pf pg, by simp; apply is_poly.sub pf pg) (λf g pf pg, by simp; apply is_poly.mul pf pg)⟩ @[simp] theorem remap_eval {α β} (f : α → β) (g : poly α) (v) : remap f g v = g (v ∘ f) := rfl end poly namespace sum /-- combine two functions into a function on the disjoint union -/ def join {α β γ} (f : α → γ) (g : β → γ) : α ⊕ β → γ := by {refine sum.rec _ _, exacts [f, g]} end sum local infixr ` ⊗ `:65 := sum.join open sum namespace option /-- Functions from `option` can be combined similarly to `vector.cons` -/ def cons {α β} (a : β) (v : α → β) : option α → β := by {refine option.rec _ _, exacts [a, v]} notation a :: b := cons a b @[simp] theorem cons_head_tail {α β} (v : option α → β) : v none :: v ∘ some = v := funext $ λo, by cases o; refl end option /- dioph -/ /-- A set `S ⊆ ℕ^α` is diophantine if there exists a polynomial on `α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. -/ def dioph {α : Type u} (S : set (α → ℕ)) : Prop := ∃ {β : Type u} (p : poly (α ⊕ β)), ∀ (v : α → ℕ), S v ↔ ∃t, p (v ⊗ t) = 0 namespace dioph section variables {α β γ : Type u} theorem ext {S S' : set (α → ℕ)} (d : dioph S) (H : ∀v, S v ↔ S' v) : dioph S' := eq.rec d $ show S = S', from set.ext H theorem of_no_dummies (S : set (α → ℕ)) (p : poly α) (h : ∀ (v : α → ℕ), S v ↔ p v = 0) : dioph S := ⟨ulift empty, p.remap inl, λv, (h v).trans ⟨λh, ⟨λt, empty.rec _ t.down, by simp; rw [ show (v ⊗ λt:ulift empty, empty.rec _ t.down) ∘ inl = v, from rfl, h]⟩, λ⟨t, ht⟩, by simp at ht; rwa [show (v ⊗ t) ∘ inl = v, from rfl] at ht⟩⟩ lemma inject_dummies_lem (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x) (p : poly (α ⊕ β)) (v : α → ℕ) : (∃t, p (v ⊗ t) = 0) ↔ (∃t, p.remap (inl ⊗ (inr ∘ f)) (v ⊗ t) = 0) := begin simp, refine ⟨λt, _, λt, _⟩; cases t with t ht, { have : (v ⊗ (0 :: t) ∘ g) ∘ (inl ⊗ inr ∘ f) = v ⊗ t := funext (λs, by cases s with a b; dsimp [join, (∘)]; try {rw inv}; refl), exact ⟨(0 :: t) ∘ g, by rwa this⟩ }, { have : v ⊗ t ∘ f = (v ⊗ t) ∘ (inl ⊗ inr ∘ f) := funext (λs, by cases s with a b; refl), exact ⟨t ∘ f, by rwa this⟩ } end theorem inject_dummies {S : set (α → ℕ)} (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x) (p : poly (α ⊕ β)) (h : ∀ (v : α → ℕ), S v ↔ ∃t, p (v ⊗ t) = 0) : ∃ q : poly (α ⊕ γ), ∀ (v : α → ℕ), S v ↔ ∃t, q (v ⊗ t) = 0 := ⟨p.remap (inl ⊗ (inr ∘ f)), λv, (h v).trans $ inject_dummies_lem f g inv _ _⟩ theorem reindex_dioph {S : set (α → ℕ)} : Π (d : dioph S) (f : α → β), dioph (λv, S (v ∘ f)) | ⟨γ, p, pe⟩ f := ⟨γ, p.remap ((inl ∘ f) ⊗ inr), λv, (pe _).trans $ exists_congr $ λt, suffices v ∘ f ⊗ t = (v ⊗ t) ∘ (inl ∘ f ⊗ inr), by simp [this], funext $ λs, by cases s with a b; refl⟩ theorem dioph_list_all (l) (d : list_all dioph l) : dioph (λv, list_all (λS : set (α → ℕ), S v) l) := suffices ∃ β (pl : list (poly (α ⊕ β))), ∀ v, list_all (λS : set _, S v) l ↔ ∃t, list_all (λp : poly (α ⊕ β), p (v ⊗ t) = 0) pl, from let ⟨β, pl, h⟩ := this in ⟨β, poly.sumsq pl, λv, (h v).trans $ exists_congr $ λt, (poly.sumsq_eq_zero _ _).symm⟩, begin induction l with S l IH, exact ⟨ulift empty, [], λv, by simp; exact ⟨λ⟨t⟩, empty.rec _ t, trivial⟩⟩, simp at d, exact let ⟨⟨β, p, pe⟩, dl⟩ := d, ⟨γ, pl, ple⟩ := IH dl in ⟨β ⊕ γ, p.remap (inl ⊗ inr ∘ inl) :: pl.map (λq, q.remap (inl ⊗ (inr ∘ inr))), λv, by simp; exact iff.trans (and_congr (pe v) (ple v)) ⟨λ⟨⟨m, hm⟩, ⟨n, hn⟩⟩, ⟨m ⊗ n, by rw [ show (v ⊗ m ⊗ n) ∘ (inl ⊗ inr ∘ inl) = v ⊗ m, from funext $ λs, by cases s with a b; refl]; exact hm, by { refine list_all.imp (λq hq, _) hn, dsimp [(∘)], rw [show (λ (x : α ⊕ γ), (v ⊗ m ⊗ n) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ n, from funext $ λs, by cases s with a b; refl]; exact hq }⟩, λ⟨t, hl, hr⟩, ⟨⟨t ∘ inl, by rwa [ show (v ⊗ t) ∘ (inl ⊗ inr ∘ inl) = v ⊗ t ∘ inl, from funext $ λs, by cases s with a b; refl] at hl⟩, ⟨t ∘ inr, by { refine list_all.imp (λq hq, _) hr, dsimp [(∘)] at hq, rwa [show (λ (x : α ⊕ γ), (v ⊗ t) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ t ∘ inr, from funext $ λs, by cases s with a b; refl] at hq }⟩⟩⟩⟩ end theorem and_dioph {S S' : set (α → ℕ)} (d : dioph S) (d' : dioph S') : dioph (λv, S v ∧ S' v) := dioph_list_all [S, S'] ⟨d, d'⟩ theorem or_dioph {S S' : set (α → ℕ)} : ∀ (d : dioph S) (d' : dioph S'), dioph (λv, S v ∨ S' v) | ⟨β, p, pe⟩ ⟨γ, q, qe⟩ := ⟨β ⊕ γ, p.remap (inl ⊗ inr ∘ inl) * q.remap (inl ⊗ inr ∘ inr), λv, begin refine iff.trans (or_congr ((pe v).trans _) ((qe v).trans _)) (exists_or_distrib.symm.trans (exists_congr $ λt, (@mul_eq_zero_iff_eq_zero_or_eq_zero _ _ (p ((v ⊗ t) ∘ (inl ⊗ inr ∘ inl))) (q ((v ⊗ t) ∘ (inl ⊗ inr ∘ inr)))).symm)), exact inject_dummies_lem _ (some ⊗ (λ_, none)) (λx, rfl) _ _, exact inject_dummies_lem _ ((λ_, none) ⊗ some) (λx, rfl) _ _, end⟩ /-- A partial function is Diophantine if its graph is Diophantine. -/ def dioph_pfun (f : (α → ℕ) →. ℕ) := dioph (λv : option α → ℕ, f.graph (v ∘ some, v none)) /-- A function is Diophantine if its graph is Diophantine. -/ def dioph_fn (f : (α → ℕ) → ℕ) := dioph (λv : option α → ℕ, f (v ∘ some) = v none) theorem reindex_dioph_fn {f : (α → ℕ) → ℕ} (d : dioph_fn f) (g : α → β) : dioph_fn (λv, f (v ∘ g)) := reindex_dioph d (functor.map g) theorem ex_dioph {S : set (α ⊕ β → ℕ)} : dioph S → dioph (λv, ∃x, S (v ⊗ x)) | ⟨γ, p, pe⟩ := ⟨β ⊕ γ, p.remap ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr), λv, ⟨λ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x ⊗ t, by simp; rw [ show (v ⊗ x ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ x) ⊗ t, from funext $ λs, by cases s with a b; try {cases a}; refl]; exact ht⟩, λ⟨t, ht⟩, ⟨t ∘ inl, (pe _).2 ⟨t ∘ inr, by simp at ht; rwa [ show (v ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ t ∘ inl) ⊗ t ∘ inr, from funext $ λs, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩ theorem ex1_dioph {S : set (option α → ℕ)} : dioph S → dioph (λv, ∃x, S (x :: v)) | ⟨β, p, pe⟩ := ⟨option β, p.remap (inr none :: inl ⊗ inr ∘ some), λv, ⟨λ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x :: t, by simp; rw [ show (v ⊗ x :: t) ∘ (inr none :: inl ⊗ inr ∘ some) = x :: v ⊗ t, from funext $ λs, by cases s with a b; try {cases a}; refl]; exact ht⟩, λ⟨t, ht⟩, ⟨t none, (pe _).2 ⟨t ∘ some, by simp at ht; rwa [ show (v ⊗ t) ∘ (inr none :: inl ⊗ inr ∘ some) = t none :: v ⊗ t ∘ some, from funext $ λs, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩ theorem dom_dioph {f : (α → ℕ) →. ℕ} (d : dioph_pfun f) : dioph f.dom := cast (congr_arg dioph $ set.ext $ λv, (pfun.dom_iff_graph _ _).symm) (ex1_dioph d) theorem dioph_fn_iff_pfun (f : (α → ℕ) → ℕ) : dioph_fn f = @dioph_pfun α f := by refine congr_arg dioph (set.ext $ λv, _); exact pfun.lift_graph.symm theorem abs_poly_dioph (p : poly α) : dioph_fn (λv, (p v).nat_abs) := by refine of_no_dummies _ ((p.remap some - poly.proj none) * (p.remap some + poly.proj none)) (λv, _); apply int.eq_nat_abs_iff_mul theorem proj_dioph (i : α) : dioph_fn (λv, v i) := abs_poly_dioph (poly.proj i) theorem dioph_pfun_comp1 {S : set (option α → ℕ)} (d : dioph S) {f} (df : dioph_pfun f) : dioph (λv : α → ℕ, ∃ h : f.dom v, S (f.fn v h :: v)) := ext (ex1_dioph (and_dioph d df)) $ λv, ⟨λ⟨x, hS, (h: Exists _)⟩, by rw [show (x :: v) ∘ some = v, from funext $ λs, rfl] at h; cases h with hf h; refine ⟨hf, _⟩; rw [pfun.fn, h]; exact hS, λ⟨x, hS⟩, ⟨f.fn v x, hS, show Exists _, by rw [show (f.fn v x :: v) ∘ some = v, from funext $ λs, rfl]; exact ⟨x, rfl⟩⟩⟩ theorem dioph_fn_comp1 {S : set (option α → ℕ)} (d : dioph S) {f : (α → ℕ) → ℕ} (df : dioph_fn f) : dioph (λv : α → ℕ, S (f v :: v)) := ext (dioph_pfun_comp1 d (cast (dioph_fn_iff_pfun f) df)) $ λv, ⟨λ⟨_, h⟩, h, λh, ⟨trivial, h⟩⟩ end section variables {α β γ : Type} theorem dioph_fn_vec_comp1 {n} {S : set (vector3 ℕ (succ n))} (d : dioph S) {f : (vector3 ℕ n) → ℕ} (df : dioph_fn f) : dioph (λv : vector3 ℕ n, S (cons (f v) v)) := ext (dioph_fn_comp1 (reindex_dioph d (none :: some)) df) $ λv, by rw [ show option.cons (f v) v ∘ (cons none some) = f v :: v, from funext $ λs, by cases s with a b; refl] theorem vec_ex1_dioph (n) {S : set (vector3 ℕ (succ n))} (d : dioph S) : dioph (λv : vector3 ℕ n, ∃x, S (x :: v)) := ext (ex1_dioph $ reindex_dioph d (none :: some)) $ λv, exists_congr $ λx, by rw [ show (option.cons x v) ∘ (cons none some) = x :: v, from funext $ λs, by cases s with a b; refl] theorem dioph_fn_vec {n} (f : vector3 ℕ n → ℕ) : dioph_fn f ↔ dioph (λv : vector3 ℕ (succ n), f (v ∘ fs) = v fz) := ⟨λh, reindex_dioph h (fz :: fs), λh, reindex_dioph h (none :: some)⟩ theorem dioph_pfun_vec {n} (f : vector3 ℕ n →. ℕ) : dioph_pfun f ↔ dioph (λv : vector3 ℕ (succ n), f.graph (v ∘ fs, v fz)) := ⟨λh, reindex_dioph h (fz :: fs), λh, reindex_dioph h (none :: some)⟩ theorem dioph_fn_compn {α : Type} : ∀ {n} {S : set (α ⊕ fin2 n → ℕ)} (d : dioph S) {f : vector3 ((α → ℕ) → ℕ) n} (df : vector_allp dioph_fn f), dioph (λv : α → ℕ, S (v ⊗ λi, f i v)) | 0 S d f := λdf, ext (reindex_dioph d (id ⊗ fin2.elim0)) $ λv, by refine eq.to_iff (congr_arg S $ funext $ λs, _); {cases s with a b, refl, cases b} | (succ n) S d f := f.cons_elim $ λf fl, by simp; exact λ df dfl, have dioph (λv, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)), from ext (dioph_fn_comp1 (reindex_dioph d (some ∘ inl ⊗ none :: some ∘ inr)) (reindex_dioph_fn df inl)) $ λv, by {refine eq.to_iff (congr_arg S $ funext $ λs, _); cases s with a b, refl, cases b; refl}, have dioph (λv, S (v ⊗ f v :: λ (i : fin2 n), fl i v)), from @dioph_fn_compn n (λv, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)) this _ dfl, ext this $ λv, by rw [ show cons (f v) (λ (i : fin2 n), fl i v) = λ (i : fin2 (succ n)), (f :: fl) i v, from funext $ λs, by cases s with a b; refl] theorem dioph_comp {n} {S : set (vector3 ℕ n)} (d : dioph S) (f : vector3 ((α → ℕ) → ℕ) n) (df : vector_allp dioph_fn f) : dioph (λv, S (λi, f i v)) := dioph_fn_compn (reindex_dioph d inr) df theorem dioph_fn_comp {n} {f : vector3 ℕ n → ℕ} (df : dioph_fn f) (g : vector3 ((α → ℕ) → ℕ) n) (dg : vector_allp dioph_fn g) : dioph_fn (λv, f (λi, g i v)) := dioph_comp ((dioph_fn_vec _).1 df) ((λv, v none) :: λi v, g i (v ∘ some)) $ by simp; exact ⟨proj_dioph none, (vector_allp_iff_forall _ _).2 $ λi, reindex_dioph_fn ((vector_allp_iff_forall _ _).1 dg _) _⟩ local notation x ` D∧ `:35 y := and_dioph x y local notation x ` D∨ `:35 y := or_dioph x y local notation `D∃`:30 := vec_ex1_dioph local prefix `&`:max := of_nat' theorem proj_dioph_of_nat {n : ℕ} (m : ℕ) [is_lt m n] : dioph_fn (λv : vector3 ℕ n, v &m) := proj_dioph &m local prefix `D&`:100 := proj_dioph_of_nat theorem const_dioph (n : ℕ) : dioph_fn (const (α → ℕ) n) := abs_poly_dioph (poly.const n) local prefix `D.`:100 := const_dioph variables {f g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) include df dg theorem dioph_comp2 {S : ℕ → ℕ → Prop} (d : dioph (λv:vector3 ℕ 2, S (v &0) (v &1))) : dioph (λv, S (f v) (g v)) := dioph_comp d [f, g] (by exact ⟨df, dg⟩) theorem dioph_fn_comp2 {h : ℕ → ℕ → ℕ} (d : dioph_fn (λv:vector3 ℕ 2, h (v &0) (v &1))) : dioph_fn (λv, h (f v) (g v)) := dioph_fn_comp d [f, g] (by exact ⟨df, dg⟩) theorem eq_dioph : dioph (λv, f v = g v) := dioph_comp2 df dg $ of_no_dummies _ (poly.proj &0 - poly.proj &1) (λv, (int.coe_nat_eq_coe_nat_iff _ _).symm.trans ⟨@sub_eq_zero_of_eq ℤ _ (v &0) (v &1), eq_of_sub_eq_zero⟩) local infix ` D= `:50 := eq_dioph theorem add_dioph : dioph_fn (λv, f v + g v) := dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 + poly.proj &1) local infix ` D+ `:80 := add_dioph theorem mul_dioph : dioph_fn (λv, f v * g v) := dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 * poly.proj &1) local infix ` D* `:90 := mul_dioph theorem le_dioph : dioph (λv, f v ≤ g v) := dioph_comp2 df dg $ ext (D∃2 $ D&1 D+ D&0 D= D&2) (λv, ⟨λ⟨x, hx⟩, le.intro hx, le.dest⟩) local infix ` D≤ `:50 := le_dioph theorem lt_dioph : dioph (λv, f v < g v) := df D+ (D. 1) D≤ dg local infix ` D< `:50 := lt_dioph theorem ne_dioph : dioph (λv, f v ≠ g v) := ext (df D< dg D∨ dg D< df) $ λv, ne_iff_lt_or_gt.symm local infix ` D≠ `:50 := ne_dioph theorem sub_dioph : dioph_fn (λv, f v - g v) := dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext (D&1 D= D&0 D+ D&2 D∨ D&1 D≤ D&2 D∧ D&0 D= D.0) $ (vector_all_iff_forall _).1 $ λx y z, show (y = x + z ∨ y ≤ z ∧ x = 0) ↔ y - z = x, from ⟨λo, begin rcases o with ae | ⟨yz, x0⟩, { rw [ae, nat.add_sub_cancel] }, { rw [x0, nat.sub_eq_zero_of_le yz] } end, λh, begin subst x, cases le_total y z with yz zy, { exact or.inr ⟨yz, nat.sub_eq_zero_of_le yz⟩ }, { exact or.inl (nat.sub_add_cancel zy).symm }, end⟩ local infix ` D- `:80 := sub_dioph theorem dvd_dioph : dioph (λv, f v ∣ g v) := dioph_comp (D∃2 $ D&2 D= D&1 D* D&0) [f, g] (by exact ⟨df, dg⟩) local infix ` D∣ `:50 := dvd_dioph theorem mod_dioph : dioph_fn (λv, f v % g v) := have dioph (λv : vector3 ℕ 3, (v &2 = 0 ∨ v &0 < v &2) ∧ ∃ (x : ℕ), v &0 + v &2 * x = v &1), from (D&2 D= D.0 D∨ D&0 D< D&2) D∧ (D∃3 $ D&1 D+ D&3 D* D&0 D= D&2), dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λz x y, show ((y = 0 ∨ z < y) ∧ ∃ c, z + y * c = x) ↔ x % y = z, from ⟨λ⟨h, c, hc⟩, begin rw ← hc; simp; cases h with x0 hl, rw [x0, mod_zero], exact mod_eq_of_lt hl end, λe, by rw ← e; exact ⟨or_iff_not_imp_left.2 $ λh, mod_lt _ (nat.pos_of_ne_zero h), x / y, mod_add_div _ _⟩⟩ local infix ` D% `:80 := mod_dioph theorem modeq_dioph {h : (α → ℕ) → ℕ} (dh : dioph_fn h) : dioph (λv, f v ≡ g v [MOD h v]) := df D% dh D= dg D% dh local notation `D≡` := modeq_dioph theorem div_dioph : dioph_fn (λv, f v / g v) := have dioph (λv : vector3 ℕ 3, v &2 = 0 ∧ v &0 = 0 ∨ v &0 * v &2 ≤ v &1 ∧ v &1 < (v &0 + 1) * v &2), from (D&2 D= D.0 D∧ D&0 D= D.0) D∨ D&0 D* D&2 D≤ D&1 D∧ D&1 D< (D&0 D+ D.1) D* D&2, dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λz x y, show y = 0 ∧ z = 0 ∨ z * y ≤ x ∧ x < (z + 1) * y ↔ x / y = z, by refine iff.trans _ eq_comm; exact y.eq_zero_or_pos.elim (λy0, by rw [y0, nat.div_zero]; exact ⟨λo, (o.resolve_right $ λ⟨_, h2⟩, not_lt_zero _ h2).right, λz0, or.inl ⟨rfl, z0⟩⟩) (λypos, iff.trans ⟨λo, o.resolve_left $ λ⟨h1, _⟩, ne_of_gt ypos h1, or.inr⟩ (le_antisymm_iff.trans $ and_congr (nat.le_div_iff_mul_le _ _ ypos) $ iff.trans ⟨lt_succ_of_le, le_of_lt_succ⟩ (div_lt_iff_lt_mul _ _ ypos)).symm) local infix ` D/ `:80 := div_dioph omit df dg open pell theorem pell_dioph : dioph (λv:vector3 ℕ 4, ∃ h : v &0 > 1, xn h (v &1) = v &2 ∧ yn h (v &1) = v &3) := have dioph {v : vector3 ℕ 4 | v &0 > 1 ∧ v &1 ≤ v &3 ∧ (v &2 = 1 ∧ v &3 = 0 ∨ ∃ (u w s t b : ℕ), v &2 * v &2 - (v &0 * v &0 - 1) * v &3 * v &3 = 1 ∧ u * u - (v &0 * v &0 - 1) * w * w = 1 ∧ s * s - (b * b - 1) * t * t = 1 ∧ b > 1 ∧ (b ≡ 1 [MOD 4 * v &3]) ∧ (b ≡ v &0 [MOD u]) ∧ w > 0 ∧ v &3 * v &3 ∣ w ∧ (s ≡ v &2 [MOD u]) ∧ (t ≡ v &1 [MOD 4 * v &3]))}, from D.1 D< D&0 D∧ D&1 D≤ D&3 D∧ ((D&2 D= D.1 D∧ D&3 D= D.0) D∨ (D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D&7 D* D&7 D- (D&5 D* D&5 D- D.1) D* D&8 D* D&8 D= D.1 D∧ D&4 D* D&4 D- (D&5 D* D&5 D- D.1) D* D&3 D* D&3 D= D.1 D∧ D&2 D* D&2 D- (D&0 D* D&0 D- D.1) D* D&1 D* D&1 D= D.1 D∧ D.1 D< D&0 D∧ (D≡ (D&0) (D.1) (D.4 D* D&8)) D∧ (D≡ (D&0) (D&5) D&4) D∧ D.0 D< D&3 D∧ D&8 D* D&8 D∣ D&3 D∧ (D≡ (D&2) (D&7) D&4) D∧ (D≡ (D&1) (D&6) (D.4 D* D&8)))), dioph.ext this $ λv, matiyasevic.symm theorem xn_dioph : dioph_pfun (λv:vector3 ℕ 2, ⟨v &0 > 1, λh, xn h (v &1)⟩) := have dioph (λv:vector3 ℕ 3, ∃ y, ∃ h : v &1 > 1, xn h (v &2) = v &0 ∧ yn h (v &2) = y), from let D_pell := @reindex_dioph _ (fin2 4) _ pell_dioph [&2, &3, &1, &0] in D∃3 D_pell, (dioph_pfun_vec _).2 $ dioph.ext this $ λv, ⟨λ⟨y, h, xe, ye⟩, ⟨h, xe⟩, λ⟨h, xe⟩, ⟨_, h, xe, rfl⟩⟩ include df dg theorem pow_dioph : dioph_fn (λv, f v ^ g v) := have dioph {v : vector3 ℕ 3 | v &2 = 0 ∧ v &0 = 1 ∨ v &2 > 0 ∧ (v &1 = 0 ∧ v &0 = 0 ∨ v &1 > 0 ∧ ∃ (w a t z x y : ℕ), (∃ (a1 : a > 1), xn a1 (v &2) = x ∧ yn a1 (v &2) = y) ∧ (x ≡ y * (a - v &1) + v &0 [MOD t]) ∧ 2 * a * v &1 = t + (v &1 * v &1 + 1) ∧ v &0 < t ∧ v &1 ≤ w ∧ v &2 ≤ w ∧ a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)}, from let D_pell := @reindex_dioph _ (fin2 9) _ pell_dioph [&4, &8, &1, &0] in (D&2 D= D.0 D∧ D&0 D= D.1) D∨ (D.0 D< D&2 D∧ ((D&1 D= D.0 D∧ D&0 D= D.0) D∨ (D.0 D< D&1 D∧ (D∃3 $ D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D_pell D∧ (D≡ (D&1) (D&0 D* (D&4 D- D&7) D+ D&6) (D&3)) D∧ D.2 D* D&4 D* D&7 D= D&3 D+ (D&7 D* D&7 D+ D.1) D∧ D&6 D< D&3 D∧ D&7 D≤ D&5 D∧ D&8 D≤ D&5 D∧ D&4 D* D&4 D- ((D&5 D+ D.1) D* (D&5 D+ D.1) D- D.1) D* (D&5 D* D&2) D* (D&5 D* D&2) D= D.1)))), dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ dioph.ext this $ λv, iff.symm $ eq_pow_of_pell.trans $ or_congr iff.rfl $ and_congr iff.rfl $ or_congr iff.rfl $ and_congr iff.rfl $ ⟨λ⟨w, a, t, z, a1, h⟩, ⟨w, a, t, z, _, _, ⟨a1, rfl, rfl⟩, h⟩, λ⟨w, a, t, z, ._, ._, ⟨a1, rfl, rfl⟩, h⟩, ⟨w, a, t, z, a1, h⟩⟩ end end dioph
8be7abf1015d1cd508b339a37b26cd39a639ffcd
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/direct_sum/ring.lean
aae4829ac4f87e4bbecc0a2923421ab694a93096
[ "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
22,801
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import group_theory.subgroup.basic import algebra.graded_monoid import algebra.direct_sum.basic import algebra.big_operators.pi /-! # Additively-graded multiplicative structures on `⨁ i, A i` This module provides a set of heterogeneous typeclasses for defining a multiplicative structure over `⨁ i, A i` such that `(*) : A i → A j → A (i + j)`; that is to say, `A` forms an additively-graded ring. The typeclasses are: * `direct_sum.gnon_unital_non_assoc_semiring A` * `direct_sum.gsemiring A` * `direct_sum.gring A` * `direct_sum.gcomm_semiring A` * `direct_sum.gcomm_ring A` Respectively, these imbue the external direct sum `⨁ i, A i` with: * `direct_sum.non_unital_non_assoc_semiring`, `direct_sum.non_unital_non_assoc_ring` * `direct_sum.semiring` * `direct_sum.ring` * `direct_sum.comm_semiring` * `direct_sum.comm_ring` the base ring `A 0` with: * `direct_sum.grade_zero.non_unital_non_assoc_semiring`, `direct_sum.grade_zero.non_unital_non_assoc_ring` * `direct_sum.grade_zero.semiring` * `direct_sum.grade_zero.ring` * `direct_sum.grade_zero.comm_semiring` * `direct_sum.grade_zero.comm_ring` and the `i`th grade `A i` with `A 0`-actions (`•`) defined as left-multiplication: * `direct_sum.grade_zero.has_smul (A 0)`, `direct_sum.grade_zero.smul_with_zero (A 0)` * `direct_sum.grade_zero.module (A 0)` * (nothing) * (nothing) * (nothing) Note that in the presence of these instances, `⨁ i, A i` itself inherits an `A 0`-action. `direct_sum.of_zero_ring_hom : A 0 →+* ⨁ i, A i` provides `direct_sum.of A 0` as a ring homomorphism. `direct_sum.to_semiring` extends `direct_sum.to_add_monoid` to produce a `ring_hom`. ## Direct sums of subobjects Additionally, this module provides helper functions to construct `gsemiring` and `gcomm_semiring` instances for: * `A : ι → submonoid S`: `direct_sum.gsemiring.of_add_submonoids`, `direct_sum.gcomm_semiring.of_add_submonoids`. * `A : ι → subgroup S`: `direct_sum.gsemiring.of_add_subgroups`, `direct_sum.gcomm_semiring.of_add_subgroups`. * `A : ι → submodule S`: `direct_sum.gsemiring.of_submodules`, `direct_sum.gcomm_semiring.of_submodules`. If `complete_lattice.independent (set.range A)`, these provide a gradation of `⨆ i, A i`, and the mapping `⨁ i, A i →+ ⨆ i, A i` can be obtained as `direct_sum.to_monoid (λ i, add_submonoid.inclusion $ le_supr A i)`. ## tags graded ring, filtered ring, direct sum, add_submonoid -/ set_option old_structure_cmd true variables {ι : Type*} [decidable_eq ι] namespace direct_sum open_locale direct_sum /-! ### Typeclasses -/ section defs variables (A : ι → Type*) /-- A graded version of `non_unital_non_assoc_semiring`. -/ class gnon_unital_non_assoc_semiring [has_add ι] [Π i, add_comm_monoid (A i)] extends graded_monoid.ghas_mul A := (mul_zero : ∀ {i j} (a : A i), mul a (0 : A j) = 0) (zero_mul : ∀ {i j} (b : A j), mul (0 : A i) b = 0) (mul_add : ∀ {i j} (a : A i) (b c : A j), mul a (b + c) = mul a b + mul a c) (add_mul : ∀ {i j} (a b : A i) (c : A j), mul (a + b) c = mul a c + mul b c) end defs section defs variables (A : ι → Type*) /-- A graded version of `semiring`. -/ class gsemiring [add_monoid ι] [Π i, add_comm_monoid (A i)] extends gnon_unital_non_assoc_semiring A, graded_monoid.gmonoid A := (nat_cast : ℕ → A 0) (nat_cast_zero : nat_cast 0 = 0) (nat_cast_succ : ∀ n : ℕ, nat_cast (n + 1) = nat_cast n + graded_monoid.ghas_one.one) /-- A graded version of `comm_semiring`. -/ class gcomm_semiring [add_comm_monoid ι] [Π i, add_comm_monoid (A i)] extends gsemiring A, graded_monoid.gcomm_monoid A /-- A graded version of `ring`. -/ class gring [add_monoid ι] [Π i, add_comm_group (A i)] extends gsemiring A := (int_cast : ℤ → A 0) (int_cast_of_nat : ∀ n : ℕ, int_cast n = nat_cast n) (int_cast_neg_succ_of_nat : ∀ n : ℕ, int_cast (-(n+1 : ℕ)) = -nat_cast (n+1 : ℕ)) /-- A graded version of `comm_ring`. -/ class gcomm_ring [add_comm_monoid ι] [Π i, add_comm_group (A i)] extends gring A, gcomm_semiring A end defs lemma of_eq_of_graded_monoid_eq {A : ι → Type*} [Π (i : ι), add_comm_monoid (A i)] {i j : ι} {a : A i} {b : A j} (h : graded_monoid.mk i a = graded_monoid.mk j b) : direct_sum.of A i a = direct_sum.of A j b := dfinsupp.single_eq_of_sigma_eq h variables (A : ι → Type*) /-! ### Instances for `⨁ i, A i` -/ section one variables [has_zero ι] [graded_monoid.ghas_one A] [Π i, add_comm_monoid (A i)] instance : has_one (⨁ i, A i) := { one := direct_sum.of (λ i, A i) 0 graded_monoid.ghas_one.one } end one section mul variables [has_add ι] [Π i, add_comm_monoid (A i)] [gnon_unital_non_assoc_semiring A] open add_monoid_hom (flip_apply coe_comp comp_hom_apply_apply) /-- The piecewise multiplication from the `has_mul` instance, as a bundled homomorphism. -/ @[simps] def gmul_hom {i j} : A i →+ A j →+ A (i + j) := { to_fun := λ a, { to_fun := λ b, graded_monoid.ghas_mul.mul a b, map_zero' := gnon_unital_non_assoc_semiring.mul_zero _, map_add' := gnon_unital_non_assoc_semiring.mul_add _ }, map_zero' := add_monoid_hom.ext $ λ a, gnon_unital_non_assoc_semiring.zero_mul a, map_add' := λ a₁ a₂, add_monoid_hom.ext $ λ b, gnon_unital_non_assoc_semiring.add_mul _ _ _} /-- The multiplication from the `has_mul` instance, as a bundled homomorphism. -/ def mul_hom : (⨁ i, A i) →+ (⨁ i, A i) →+ ⨁ i, A i := direct_sum.to_add_monoid $ λ i, add_monoid_hom.flip $ direct_sum.to_add_monoid $ λ j, add_monoid_hom.flip $ (direct_sum.of A _).comp_hom.comp $ gmul_hom A instance : non_unital_non_assoc_semiring (⨁ i, A i) := { mul := λ a b, mul_hom A a b, zero := 0, add := (+), zero_mul := λ a, by simp only [add_monoid_hom.map_zero, add_monoid_hom.zero_apply], mul_zero := λ a, by simp only [add_monoid_hom.map_zero], left_distrib := λ a b c, by simp only [add_monoid_hom.map_add], right_distrib := λ a b c, by simp only [add_monoid_hom.map_add, add_monoid_hom.add_apply], .. direct_sum.add_comm_monoid _ _} variables {A} lemma mul_hom_of_of {i j} (a : A i) (b : A j) : mul_hom A (of _ i a) (of _ j b) = of _ (i + j) (graded_monoid.ghas_mul.mul a b) := begin unfold mul_hom, rw [to_add_monoid_of, flip_apply, to_add_monoid_of, flip_apply, coe_comp, function.comp_app, comp_hom_apply_apply, coe_comp, function.comp_app, gmul_hom_apply_apply], end lemma of_mul_of {i j} (a : A i) (b : A j) : of _ i a * of _ j b = of _ (i + j) (graded_monoid.ghas_mul.mul a b) := mul_hom_of_of a b end mul section semiring variables [Π i, add_comm_monoid (A i)] [add_monoid ι] [gsemiring A] open add_monoid_hom (flip_hom coe_comp comp_hom_apply_apply flip_apply flip_hom_apply) private lemma one_mul (x : ⨁ i, A i) : 1 * x = x := suffices mul_hom A 1 = add_monoid_hom.id (⨁ i, A i), from add_monoid_hom.congr_fun this x, begin apply add_hom_ext, intros i xi, unfold has_one.one, rw mul_hom_of_of, exact of_eq_of_graded_monoid_eq (one_mul $ graded_monoid.mk i xi), end private lemma mul_one (x : ⨁ i, A i) : x * 1 = x := suffices (mul_hom A).flip 1 = add_monoid_hom.id (⨁ i, A i), from add_monoid_hom.congr_fun this x, begin apply add_hom_ext, intros i xi, unfold has_one.one, rw [flip_apply, mul_hom_of_of], exact of_eq_of_graded_monoid_eq (mul_one $ graded_monoid.mk i xi), end private lemma mul_assoc (a b c : ⨁ i, A i) : a * b * c = a * (b * c) := suffices (mul_hom A).comp_hom.comp (mul_hom A) -- `λ a b c, a * b * c` as a bundled hom = (add_monoid_hom.comp_hom flip_hom $ -- `λ a b c, a * (b * c)` as a bundled hom (mul_hom A).flip.comp_hom.comp (mul_hom A)).flip, from add_monoid_hom.congr_fun (add_monoid_hom.congr_fun (add_monoid_hom.congr_fun this a) b) c, begin ext ai ax bi bx ci cx : 6, dsimp only [coe_comp, function.comp_app, comp_hom_apply_apply, flip_apply, flip_hom_apply], rw [mul_hom_of_of, mul_hom_of_of, mul_hom_of_of, mul_hom_of_of], exact of_eq_of_graded_monoid_eq (mul_assoc (graded_monoid.mk ai ax) ⟨bi, bx⟩ ⟨ci, cx⟩), end /-- The `semiring` structure derived from `gsemiring A`. -/ instance semiring : semiring (⨁ i, A i) := { one := 1, mul := (*), zero := 0, add := (+), one_mul := one_mul A, mul_one := mul_one A, mul_assoc := mul_assoc A, nat_cast := λ n, of _ _ (gsemiring.nat_cast n), nat_cast_zero := by rw [gsemiring.nat_cast_zero, map_zero], nat_cast_succ := λ n, by { rw [gsemiring.nat_cast_succ, map_add], refl }, ..direct_sum.non_unital_non_assoc_semiring _, } lemma of_pow {i} (a : A i) (n : ℕ) : of _ i a ^ n = of _ (n • i) (graded_monoid.gmonoid.gnpow _ a) := begin induction n with n, { exact of_eq_of_graded_monoid_eq (pow_zero $ graded_monoid.mk _ a).symm, }, { rw [pow_succ, n_ih, of_mul_of], exact of_eq_of_graded_monoid_eq (pow_succ (graded_monoid.mk _ a) n).symm, }, end lemma of_list_dprod {α} (l : list α) (fι : α → ι) (fA : Π a, A (fι a)) : of A _ (l.dprod fι fA) = (l.map $ λ a, of A (fι a) (fA a)).prod := begin induction l, { simp only [list.map_nil, list.prod_nil, list.dprod_nil], refl }, { simp only [list.map_cons, list.prod_cons, list.dprod_cons, ←l_ih, direct_sum.of_mul_of], refl }, end lemma list_prod_of_fn_of_eq_dprod (n : ℕ) (fι : fin n → ι) (fA : Π a, A (fι a)) : (list.of_fn $ λ a, of A (fι a) (fA a)).prod = of A _ ((list.fin_range n).dprod fι fA) := by rw [list.of_fn_eq_map, of_list_dprod] open_locale big_operators /-- A heavily unfolded version of the definition of multiplication -/ lemma mul_eq_sum_support_ghas_mul [Π (i : ι) (x : A i), decidable (x ≠ 0)] (a a' : ⨁ i, A i) : a * a' = ∑ (ij : ι × ι) in (dfinsupp.support a).product (dfinsupp.support a'), direct_sum.of _ _ (graded_monoid.ghas_mul.mul (a ij.fst) (a' ij.snd)) := begin change direct_sum.mul_hom _ a a' = _, dsimp [direct_sum.mul_hom, direct_sum.to_add_monoid, dfinsupp.lift_add_hom_apply], simp only [dfinsupp.sum_add_hom_apply, dfinsupp.sum, dfinsupp.finset_sum_apply, add_monoid_hom.coe_finset_sum, finset.sum_apply, add_monoid_hom.flip_apply, add_monoid_hom.comp_hom_apply_apply, add_monoid_hom.comp_apply, direct_sum.gmul_hom_apply_apply], rw finset.sum_product, end end semiring section comm_semiring variables [Π i, add_comm_monoid (A i)] [add_comm_monoid ι] [gcomm_semiring A] private lemma mul_comm (a b : ⨁ i, A i) : a * b = b * a := suffices mul_hom A = (mul_hom A).flip, from add_monoid_hom.congr_fun (add_monoid_hom.congr_fun this a) b, begin apply add_hom_ext, intros ai ax, apply add_hom_ext, intros bi bx, rw [add_monoid_hom.flip_apply, mul_hom_of_of, mul_hom_of_of], exact of_eq_of_graded_monoid_eq (gcomm_semiring.mul_comm ⟨ai, ax⟩ ⟨bi, bx⟩), end /-- The `comm_semiring` structure derived from `gcomm_semiring A`. -/ instance comm_semiring : comm_semiring (⨁ i, A i) := { one := 1, mul := (*), zero := 0, add := (+), mul_comm := mul_comm A, ..direct_sum.semiring _, } end comm_semiring section non_unital_non_assoc_ring variables [Π i, add_comm_group (A i)] [has_add ι] [gnon_unital_non_assoc_semiring A] /-- The `ring` derived from `gsemiring A`. -/ instance non_assoc_ring : non_unital_non_assoc_ring (⨁ i, A i) := { mul := (*), zero := 0, add := (+), neg := has_neg.neg, ..(direct_sum.non_unital_non_assoc_semiring _), ..(direct_sum.add_comm_group _), } end non_unital_non_assoc_ring section ring variables [Π i, add_comm_group (A i)] [add_monoid ι] [gring A] /-- The `ring` derived from `gsemiring A`. -/ instance ring : ring (⨁ i, A i) := { one := 1, mul := (*), zero := 0, add := (+), neg := has_neg.neg, int_cast := λ z, of _ _ (gring.int_cast z), int_cast_of_nat := λ z, congr_arg _ $ gring.int_cast_of_nat _, int_cast_neg_succ_of_nat := λ z, (congr_arg _ $ gring.int_cast_neg_succ_of_nat _).trans (map_neg _ _), ..(direct_sum.semiring _), ..(direct_sum.add_comm_group _), } end ring section comm_ring variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gcomm_ring A] /-- The `comm_ring` derived from `gcomm_semiring A`. -/ instance comm_ring : comm_ring (⨁ i, A i) := { one := 1, mul := (*), zero := 0, add := (+), neg := has_neg.neg, ..(direct_sum.ring _), ..(direct_sum.comm_semiring _), } end comm_ring /-! ### 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 section one variables [has_zero ι] [graded_monoid.ghas_one A] [Π i, add_comm_monoid (A i)] @[simp] lemma of_zero_one : of _ 0 (1 : A 0) = 1 := rfl end one section mul variables [add_zero_class ι] [Π i, add_comm_monoid (A i)] [gnon_unital_non_assoc_semiring A] @[simp] lemma of_zero_smul {i} (a : A 0) (b : A i) : of _ _ (a • b) = of _ _ a * of _ _ b := (of_eq_of_graded_monoid_eq (graded_monoid.mk_zero_smul a b)).trans (of_mul_of _ _).symm @[simp] lemma of_zero_mul (a b : A 0) : of _ 0 (a * b) = of _ 0 a * of _ 0 b:= of_zero_smul A a b instance grade_zero.non_unital_non_assoc_semiring : non_unital_non_assoc_semiring (A 0) := function.injective.non_unital_non_assoc_semiring (of A 0) dfinsupp.single_injective (of A 0).map_zero (of A 0).map_add (of_zero_mul A) (λ x n, dfinsupp.single_smul n x) instance grade_zero.smul_with_zero (i : ι) : smul_with_zero (A 0) (A i) := begin letI := smul_with_zero.comp_hom (⨁ i, A i) (of A 0).to_zero_hom, refine dfinsupp.single_injective.smul_with_zero (of A i).to_zero_hom (of_zero_smul A), end end mul section semiring variables [Π i, add_comm_monoid (A i)] [add_monoid ι] [gsemiring A] @[simp] lemma of_zero_pow (a : A 0) : ∀ n : ℕ, of _ 0 (a ^ n) = of _ 0 a ^ n | 0 := by rw [pow_zero, pow_zero, direct_sum.of_zero_one] | (n + 1) := by rw [pow_succ, pow_succ, of_zero_mul, of_zero_pow] instance : has_nat_cast (A 0) := ⟨gsemiring.nat_cast⟩ @[simp] lemma of_nat_cast (n : ℕ) : of A 0 n = n := rfl /-- The `semiring` structure derived from `gsemiring A`. -/ instance grade_zero.semiring : semiring (A 0) := function.injective.semiring (of A 0) dfinsupp.single_injective (of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A) (of A 0).map_nsmul (λ x n, of_zero_pow _ _ _) (of_nat_cast A) /-- `of A 0` is a `ring_hom`, using the `direct_sum.grade_zero.semiring` structure. -/ def of_zero_ring_hom : A 0 →+* (⨁ i, A i) := { map_one' := of_zero_one A, map_mul' := of_zero_mul A, ..(of _ 0) } /-- Each grade `A i` derives a `A 0`-module structure from `gsemiring A`. Note that this results in an overall `module (A 0) (⨁ i, A i)` structure via `direct_sum.module`. -/ instance grade_zero.module {i} : module (A 0) (A i) := begin letI := module.comp_hom (⨁ i, A i) (of_zero_ring_hom A), exact dfinsupp.single_injective.module (A 0) (of A i) (λ a, of_zero_smul A a), end end semiring section comm_semiring variables [Π i, add_comm_monoid (A i)] [add_comm_monoid ι] [gcomm_semiring A] /-- The `comm_semiring` structure derived from `gcomm_semiring A`. -/ instance grade_zero.comm_semiring : comm_semiring (A 0) := function.injective.comm_semiring (of A 0) dfinsupp.single_injective (of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A) (λ x n, dfinsupp.single_smul n x) (λ x n, of_zero_pow _ _ _) (of_nat_cast A) end comm_semiring section ring variables [Π i, add_comm_group (A i)] [add_zero_class ι] [gnon_unital_non_assoc_semiring A] /-- The `non_unital_non_assoc_ring` derived from `gnon_unital_non_assoc_semiring A`. -/ instance grade_zero.non_unital_non_assoc_ring : non_unital_non_assoc_ring (A 0) := function.injective.non_unital_non_assoc_ring (of A 0) dfinsupp.single_injective (of A 0).map_zero (of A 0).map_add (of_zero_mul A) (of A 0).map_neg (of A 0).map_sub (λ x n, begin letI : Π i, distrib_mul_action ℕ (A i) := λ i, infer_instance, exact dfinsupp.single_smul n x end) (λ x n, begin letI : Π i, distrib_mul_action ℤ (A i) := λ i, infer_instance, exact dfinsupp.single_smul n x end) end ring section ring variables [Π i, add_comm_group (A i)] [add_monoid ι] [gring A] instance : has_int_cast (A 0) := ⟨gring.int_cast⟩ @[simp] lemma of_int_cast (n : ℤ) : of A 0 n = n := rfl /-- The `ring` derived from `gsemiring A`. -/ instance grade_zero.ring : ring (A 0) := function.injective.ring (of A 0) dfinsupp.single_injective (of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A) (of A 0).map_neg (of A 0).map_sub (λ x n, begin letI : Π i, distrib_mul_action ℕ (A i) := λ i, infer_instance, exact dfinsupp.single_smul n x end) (λ x n, begin letI : Π i, distrib_mul_action ℤ (A i) := λ i, infer_instance, exact dfinsupp.single_smul n x end) (λ x n, of_zero_pow _ _ _) (of_nat_cast A) (of_int_cast A) end ring section comm_ring variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gcomm_ring A] /-- The `comm_ring` derived from `gcomm_semiring A`. -/ instance grade_zero.comm_ring : comm_ring (A 0) := function.injective.comm_ring (of A 0) dfinsupp.single_injective (of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A) (of A 0).map_neg (of A 0).map_sub (λ x n, begin letI : Π i, distrib_mul_action ℕ (A i) := λ i, infer_instance, exact dfinsupp.single_smul n x end) (λ x n, begin letI : Π i, distrib_mul_action ℤ (A i) := λ i, infer_instance, exact dfinsupp.single_smul n x end) (λ x n, of_zero_pow _ _ _) (of_nat_cast A) (of_int_cast A) end comm_ring end grade_zero section to_semiring variables {R : Type*} [Π i, add_comm_monoid (A i)] [add_monoid ι] [gsemiring A] [semiring R] variables {A} /-- If two ring homomorphisms from `⨁ i, A i` are equal on each `of A i y`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext' ⦃F G : (⨁ i, A i) →+* R⦄ (h : ∀ i, (↑F : _ →+ R).comp (of A i) = (↑G : _ →+ R).comp (of A i)) : F = G := ring_hom.coe_add_monoid_hom_injective $ direct_sum.add_hom_ext' h /-- Two `ring_hom`s out of a direct sum are equal if they agree on the generators. -/ lemma ring_hom_ext ⦃f g : (⨁ i, A i) →+* R⦄ (h : ∀ i x, f (of A i x) = g (of A i x)) : f = g := ring_hom_ext' $ λ i, add_monoid_hom.ext $ h i /-- A family of `add_monoid_hom`s preserving `direct_sum.ghas_one.one` and `direct_sum.ghas_mul.mul` describes a `ring_hom`s on `⨁ i, A i`. This is a stronger version of `direct_sum.to_monoid`. Of particular interest is the case when `A i` are bundled subojects, `f` is the family of coercions such as `add_submonoid.subtype (A i)`, and the `[gsemiring A]` structure originates from `direct_sum.gsemiring.of_add_submonoids`, in which case the proofs about `ghas_one` and `ghas_mul` can be discharged by `rfl`. -/ @[simps] def to_semiring (f : Π i, A i →+ R) (hone : f _ (graded_monoid.ghas_one.one) = 1) (hmul : ∀ {i j} (ai : A i) (aj : A j), f _ (graded_monoid.ghas_mul.mul ai aj) = f _ ai * f _ aj) : (⨁ i, A i) →+* R := { to_fun := to_add_monoid f, map_one' := begin change (to_add_monoid f) (of _ 0 _) = 1, rw to_add_monoid_of, exact hone end, map_mul' := begin rw (to_add_monoid f).map_mul_iff, ext xi xv yi yv : 4, show to_add_monoid f (of A xi xv * of A yi yv) = to_add_monoid f (of A xi xv) * to_add_monoid f (of A yi yv), rw [of_mul_of, to_add_monoid_of, to_add_monoid_of, to_add_monoid_of], exact hmul _ _, end, .. to_add_monoid f} @[simp] lemma to_semiring_of (f : Π i, A i →+ R) (hone hmul) (i : ι) (x : A i) : to_semiring f hone hmul (of _ i x) = f _ x := to_add_monoid_of f i x @[simp] lemma to_semiring_coe_add_monoid_hom (f : Π i, A i →+ R) (hone hmul): (to_semiring f hone hmul : (⨁ i, A i) →+ R) = to_add_monoid f := rfl /-- Families of `add_monoid_hom`s preserving `direct_sum.ghas_one.one` and `direct_sum.ghas_mul.mul` are isomorphic to `ring_hom`s on `⨁ i, A i`. This is a stronger version of `dfinsupp.lift_add_hom`. -/ @[simps] def lift_ring_hom : {f : Π {i}, A i →+ R // f (graded_monoid.ghas_one.one) = 1 ∧ ∀ {i j} (ai : A i) (aj : A j), f (graded_monoid.ghas_mul.mul ai aj) = f ai * f aj} ≃ ((⨁ i, A i) →+* R) := { to_fun := λ f, to_semiring f.1 f.2.1 f.2.2, inv_fun := λ F, ⟨λ i, (F : (⨁ i, A i) →+ R).comp (of _ i), begin simp only [add_monoid_hom.comp_apply, ring_hom.coe_add_monoid_hom], rw ←F.map_one, refl end, λ i j ai aj, begin simp only [add_monoid_hom.comp_apply, ring_hom.coe_add_monoid_hom], rw [←F.map_mul, of_mul_of], end⟩, left_inv := λ f, begin ext xi xv, exact to_add_monoid_of f.1 xi xv, end, right_inv := λ F, begin apply ring_hom.coe_add_monoid_hom_injective, ext xi xv, simp only [ring_hom.coe_add_monoid_hom_mk, direct_sum.to_add_monoid_of, add_monoid_hom.mk_coe, add_monoid_hom.comp_apply, to_semiring_coe_add_monoid_hom], end} end to_semiring end direct_sum /-! ### Concrete instances -/ section uniform variables (ι) /-- A direct sum of copies of a `semiring` inherits the multiplication structure. -/ instance non_unital_non_assoc_semiring.direct_sum_gnon_unital_non_assoc_semiring {R : Type*} [add_monoid ι] [non_unital_non_assoc_semiring R] : direct_sum.gnon_unital_non_assoc_semiring (λ i : ι, R) := { mul_zero := λ i j, mul_zero, zero_mul := λ i j, zero_mul, mul_add := λ i j, mul_add, add_mul := λ i j, add_mul, ..has_mul.ghas_mul ι } /-- A direct sum of copies of a `semiring` inherits the multiplication structure. -/ instance semiring.direct_sum_gsemiring {R : Type*} [add_monoid ι] [semiring R] : direct_sum.gsemiring (λ i : ι, R) := { nat_cast := λ n, n, nat_cast_zero := nat.cast_zero, nat_cast_succ := nat.cast_succ, ..non_unital_non_assoc_semiring.direct_sum_gnon_unital_non_assoc_semiring ι, ..monoid.gmonoid ι } open_locale direct_sum -- To check `has_mul.ghas_mul_mul` matches example {R : Type*} [add_monoid ι] [semiring R] (i j : ι) (a b : R) : (direct_sum.of _ i a * direct_sum.of _ j b : ⨁ i, R) = direct_sum.of _ (i + j) (by exact a * b) := by rw [direct_sum.of_mul_of, has_mul.ghas_mul_mul] /-- A direct sum of copies of a `comm_semiring` inherits the commutative multiplication structure. -/ instance comm_semiring.direct_sum_gcomm_semiring {R : Type*} [add_comm_monoid ι] [comm_semiring R] : direct_sum.gcomm_semiring (λ i : ι, R) := { ..comm_monoid.gcomm_monoid ι, ..semiring.direct_sum_gsemiring ι } end uniform
9c4c1e2091275d14e311672ec3771f51fe8729a9
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/polynomial/cancel_leads.lean
a75bac5dacfabf57b30c3e2487c82fb7f6c3b602
[ "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
2,760
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import data.polynomial.degree.definitions import tactic.compute_degree /-! # Cancel the leading terms of two polynomials ## Definition * `cancel_leads p q`: the polynomial formed by multiplying `p` and `q` by monomials so that they have the same leading term, and then subtracting. ## Main Results The degree of `cancel_leads` is less than that of the larger of the two polynomials being cancelled. Thus it is useful for induction or minimal-degree arguments. -/ namespace polynomial noncomputable theory open_locale polynomial variables {R : Type*} section ring variables [ring R] (p q : R[X]) /-- `cancel_leads p q` is formed by multiplying `p` and `q` by monomials so that they have the same leading term, and then subtracting. -/ def cancel_leads : R[X] := C p.leading_coeff * X ^ (p.nat_degree - q.nat_degree) * q - C q.leading_coeff * X ^ (q.nat_degree - p.nat_degree) * p variables {p q} @[simp] lemma neg_cancel_leads : - p.cancel_leads q = q.cancel_leads p := neg_sub _ _ lemma nat_degree_cancel_leads_lt_of_nat_degree_le_nat_degree_of_comm (comm : p.leading_coeff * q.leading_coeff = q.leading_coeff * p.leading_coeff) (h : p.nat_degree ≤ q.nat_degree) (hq : 0 < q.nat_degree) : (p.cancel_leads q).nat_degree < q.nat_degree := begin by_cases hp : p = 0, { convert hq, simp [hp, cancel_leads], }, rw [cancel_leads, sub_eq_add_neg, tsub_eq_zero_iff_le.mpr h, pow_zero, mul_one], by_cases h0 : C p.leading_coeff * q + -(C q.leading_coeff * X ^ (q.nat_degree - p.nat_degree) * p) = 0, { exact (le_of_eq (by simp only [h0, nat_degree_zero])).trans_lt hq }, apply lt_of_le_of_ne, { compute_degree_le, repeat { rwa nat.sub_add_cancel } }, { contrapose! h0, rw [← leading_coeff_eq_zero, leading_coeff, h0, mul_assoc, X_pow_mul, ← tsub_add_cancel_of_le h, add_comm _ p.nat_degree], simp only [coeff_mul_X_pow, coeff_neg, coeff_C_mul, add_tsub_cancel_left, coeff_add], rw [add_comm p.nat_degree, tsub_add_cancel_of_le h, ← leading_coeff, ← leading_coeff, comm, add_right_neg] } end end ring section comm_ring variables [comm_ring R] {p q : R[X]} lemma dvd_cancel_leads_of_dvd_of_dvd {r : R[X]} (pq : p ∣ q) (pr : p ∣ r) : p ∣ q.cancel_leads r := dvd_sub (pr.trans (dvd.intro_left _ rfl)) (pq.trans (dvd.intro_left _ rfl)) lemma nat_degree_cancel_leads_lt_of_nat_degree_le_nat_degree (h : p.nat_degree ≤ q.nat_degree) (hq : 0 < q.nat_degree) : (p.cancel_leads q).nat_degree < q.nat_degree := nat_degree_cancel_leads_lt_of_nat_degree_le_nat_degree_of_comm (mul_comm _ _) h hq end comm_ring end polynomial
544531e61e89d6db6a25d158d7d6843208da3087
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF/PullLetDecls.lean
b80174336c7c8ce41ddf124cc467b5197236c3da
[ "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
4,018
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.LCNF.CompilerM import Lean.Compiler.LCNF.DependsOn import Lean.Compiler.LCNF.Types import Lean.Compiler.LCNF.PassManager namespace Lean.Compiler.LCNF namespace PullLetDecls structure Context where isCandidateFn : LetDecl → FVarIdSet → CompilerM Bool included : FVarIdSet := {} structure State where toPull : Array LetDecl := #[] abbrev PullM := ReaderT Context $ StateRefT State CompilerM @[inline] def withFVar (fvarId : FVarId) (x : PullM α) : PullM α := withReader (fun ctx => { ctx with included := ctx.included.insert fvarId }) x @[inline] def withParams (ps : Array Param) (x : PullM α) : PullM α := withReader (fun ctx => { ctx with included := ps.foldl (init := ctx.included) fun s p => s.insert p.fvarId }) x @[inline] def withNewScope (x : PullM α) : PullM α := withReader (fun ctx => { ctx with included := {} }) x partial def withCheckpoint (x : PullM Code) : PullM Code := do let toPullSizeSaved := (← get).toPull.size let c ← withNewScope x let toPull := (← get).toPull let rec go (i : Nat) (included : FVarIdSet) : StateM (Array LetDecl) Code := do if h : i < toPull.size then let letDecl := toPull[i] if letDecl.dependsOn included then let c ← go (i+1) (included.insert letDecl.fvarId) return .let letDecl c else modify (·.push letDecl) go (i+1) included else return c let (c, keep) := go toPullSizeSaved (← read).included |>.run #[] modify fun s => { s with toPull := s.toPull.shrink toPullSizeSaved ++ keep } return c def attachToPull (c : Code) : PullM Code := do let toPull := (← get).toPull return toPull.foldr (init := c) fun decl c => .let decl c def shouldPull (decl : LetDecl) : PullM Bool := do unless decl.dependsOn (← read).included do if (← (← read).isCandidateFn decl (← read).included) then modify fun s => { s with toPull := s.toPull.push decl } return true return false mutual partial def pullAlt (alt : Alt) : PullM Alt := match alt with | .default k => return alt.updateCode (← withNewScope <| pullDecls k) | .alt _ params k => return alt.updateCode (← withNewScope <| withParams params <| pullDecls k) partial def pullDecls (code : Code) : PullM Code := do match code with | .cases c => withCheckpoint do let alts ← c.alts.mapMonoM pullAlt return code.updateAlts! alts | .let decl k => if (← shouldPull decl) then pullDecls k else withFVar decl.fvarId do return code.updateCont! (← pullDecls k) | .fun decl k | .jp decl k => withCheckpoint do let value ← withParams decl.params <| pullDecls decl.value let decl ← decl.updateValue value withFVar decl.fvarId do return code.updateFun! decl (← pullDecls k) | _ => return code end def PullM.run (x : PullM α) (isCandidateFn : LetDecl → FVarIdSet → CompilerM Bool) : CompilerM α := x { isCandidateFn } |>.run' {} end PullLetDecls open PullLetDecls def Decl.pullLetDecls (decl : Decl) (isCandidateFn : LetDecl → FVarIdSet → CompilerM Bool) : CompilerM Decl := do PullM.run (isCandidateFn := isCandidateFn) do withParams decl.params do let value ← pullDecls decl.value let value ← attachToPull value return { decl with value } def Decl.pullInstances (decl : Decl) : CompilerM Decl := decl.pullLetDecls fun letDecl candidates => do if (← isClass? letDecl.type).isSome then return true else if let .proj _ _ fvarId := letDecl.value then return candidates.contains fvarId else return false def pullInstances : Pass := .mkPerDeclaration `pullInstances Decl.pullInstances .base builtin_initialize registerTraceClass `Compiler.pullInstances (inherited := true) end Lean.Compiler.LCNF
273b5c9dfb74b45b466ac932585cd69b6326346f
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/coprime/basic.lean
2eb406bc1b075e6224fe60831c4d8412f5bf235b
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
12,383
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Ken Lee, Chris Hughes -/ import tactic.ring import algebra.ring.basic import group_theory.group_action.units /-! # Coprime elements of a ring ## Main definitions * `is_coprime x y`: that `x` and `y` are coprime, defined to be the existence of `a` and `b` such that `a * x + b * y = 1`. Note that elements with no common divisors are not necessarily coprime, e.g., the multivariate polynomials `x₁` and `x₂` are not coprime. See also `ring_theory.coprime.lemmas` for further development of coprime elements. -/ open_locale classical universes u v section comm_semiring variables {R : Type u} [comm_semiring R] (x y z : R) /-- The proposition that `x` and `y` are coprime, defined to be the existence of `a` and `b` such that `a * x + b * y = 1`. Note that elements with no common divisors are not necessarily coprime, e.g., the multivariate polynomials `x₁` and `x₂` are not coprime. -/ @[simp] def is_coprime : Prop := ∃ a b, a * x + b * y = 1 variables {x y z} theorem is_coprime.symm (H : is_coprime x y) : is_coprime y x := let ⟨a, b, H⟩ := H in ⟨b, a, by rw [add_comm, H]⟩ theorem is_coprime_comm : is_coprime x y ↔ is_coprime y x := ⟨is_coprime.symm, is_coprime.symm⟩ theorem is_coprime_self : is_coprime x x ↔ is_unit x := ⟨λ ⟨a, b, h⟩, is_unit_of_mul_eq_one x (a + b) $ by rwa [mul_comm, add_mul], λ h, let ⟨b, hb⟩ := is_unit_iff_exists_inv'.1 h in ⟨b, 0, by rwa [zero_mul, add_zero]⟩⟩ theorem is_coprime_zero_left : is_coprime 0 x ↔ is_unit x := ⟨λ ⟨a, b, H⟩, is_unit_of_mul_eq_one x b $ by rwa [mul_zero, zero_add, mul_comm] at H, λ H, let ⟨b, hb⟩ := is_unit_iff_exists_inv'.1 H in ⟨1, b, by rwa [one_mul, zero_add]⟩⟩ theorem is_coprime_zero_right : is_coprime x 0 ↔ is_unit x := is_coprime_comm.trans is_coprime_zero_left lemma not_coprime_zero_zero [nontrivial R] : ¬ is_coprime (0 : R) 0 := mt is_coprime_zero_right.mp not_is_unit_zero /-- If a 2-vector `p` satisfies `is_coprime (p 0) (p 1)`, then `p ≠ 0`. -/ lemma is_coprime.ne_zero [nontrivial R] {p : fin 2 → R} (h : is_coprime (p 0) (p 1)) : p ≠ 0 := by { rintro rfl, exact not_coprime_zero_zero h } theorem is_coprime_one_left : is_coprime 1 x := ⟨1, 0, by rw [one_mul, zero_mul, add_zero]⟩ theorem is_coprime_one_right : is_coprime x 1 := ⟨0, 1, by rw [one_mul, zero_mul, zero_add]⟩ theorem is_coprime.dvd_of_dvd_mul_right (H1 : is_coprime x z) (H2 : x ∣ y * z) : x ∣ y := let ⟨a, b, H⟩ := H1 in by { rw [← mul_one y, ← H, mul_add, ← mul_assoc, mul_left_comm], exact dvd_add (dvd_mul_left _ _) (H2.mul_left _) } theorem is_coprime.dvd_of_dvd_mul_left (H1 : is_coprime x y) (H2 : x ∣ y * z) : x ∣ z := let ⟨a, b, H⟩ := H1 in by { rw [← one_mul z, ← H, add_mul, mul_right_comm, mul_assoc b], exact dvd_add (dvd_mul_left _ _) (H2.mul_left _) } theorem is_coprime.mul_left (H1 : is_coprime x z) (H2 : is_coprime y z) : is_coprime (x * y) z := let ⟨a, b, h1⟩ := H1, ⟨c, d, h2⟩ := H2 in ⟨a * c, a * x * d + b * c * y + b * d * z, calc a * c * (x * y) + (a * x * d + b * c * y + b * d * z) * z = (a * x + b * z) * (c * y + d * z) : by ring ... = 1 : by rw [h1, h2, mul_one]⟩ theorem is_coprime.mul_right (H1 : is_coprime x y) (H2 : is_coprime x z) : is_coprime x (y * z) := by { rw is_coprime_comm at H1 H2 ⊢, exact H1.mul_left H2 } theorem is_coprime.mul_dvd (H : is_coprime x y) (H1 : x ∣ z) (H2 : y ∣ z) : x * y ∣ z := begin obtain ⟨a, b, h⟩ := H, rw [← mul_one z, ← h, mul_add], apply dvd_add, { rw [mul_comm z, mul_assoc], exact (mul_dvd_mul_left _ H2).mul_left _ }, { rw [mul_comm b, ← mul_assoc], exact (mul_dvd_mul_right H1 _).mul_right _ } end theorem is_coprime.of_mul_left_left (H : is_coprime (x * y) z) : is_coprime x z := let ⟨a, b, h⟩ := H in ⟨a * y, b, by rwa [mul_right_comm, mul_assoc]⟩ theorem is_coprime.of_mul_left_right (H : is_coprime (x * y) z) : is_coprime y z := by { rw mul_comm at H, exact H.of_mul_left_left } theorem is_coprime.of_mul_right_left (H : is_coprime x (y * z)) : is_coprime x y := by { rw is_coprime_comm at H ⊢, exact H.of_mul_left_left } theorem is_coprime.of_mul_right_right (H : is_coprime x (y * z)) : is_coprime x z := by { rw mul_comm at H, exact H.of_mul_right_left } theorem is_coprime.mul_left_iff : is_coprime (x * y) z ↔ is_coprime x z ∧ is_coprime y z := ⟨λ H, ⟨H.of_mul_left_left, H.of_mul_left_right⟩, λ ⟨H1, H2⟩, H1.mul_left H2⟩ theorem is_coprime.mul_right_iff : is_coprime x (y * z) ↔ is_coprime x y ∧ is_coprime x z := by rw [is_coprime_comm, is_coprime.mul_left_iff, is_coprime_comm, @is_coprime_comm _ _ z] theorem is_coprime.of_coprime_of_dvd_left (h : is_coprime y z) (hdvd : x ∣ y) : is_coprime x z := begin obtain ⟨d, rfl⟩ := hdvd, exact is_coprime.of_mul_left_left h end theorem is_coprime.of_coprime_of_dvd_right (h : is_coprime z y) (hdvd : x ∣ y) : is_coprime z x := (h.symm.of_coprime_of_dvd_left hdvd).symm theorem is_coprime.is_unit_of_dvd (H : is_coprime x y) (d : x ∣ y) : is_unit x := let ⟨k, hk⟩ := d in is_coprime_self.1 $ is_coprime.of_mul_right_left $ show is_coprime x (x * k), from hk ▸ H theorem is_coprime.is_unit_of_dvd' {a b x : R} (h : is_coprime a b) (ha : x ∣ a) (hb : x ∣ b) : is_unit x := (h.of_coprime_of_dvd_left ha).is_unit_of_dvd hb theorem is_coprime.map (H : is_coprime x y) {S : Type v} [comm_semiring S] (f : R →+* S) : is_coprime (f x) (f y) := let ⟨a, b, h⟩ := H in ⟨f a, f b, by rw [← f.map_mul, ← f.map_mul, ← f.map_add, h, f.map_one]⟩ variables {x y z} lemma is_coprime.of_add_mul_left_left (h : is_coprime (x + y * z) y) : is_coprime x y := let ⟨a, b, H⟩ := h in ⟨a, a * z + b, by simpa only [add_mul, mul_add, add_assoc, add_comm, add_left_comm, mul_assoc, mul_comm, mul_left_comm] using H⟩ lemma is_coprime.of_add_mul_right_left (h : is_coprime (x + z * y) y) : is_coprime x y := by { rw mul_comm at h, exact h.of_add_mul_left_left } lemma is_coprime.of_add_mul_left_right (h : is_coprime x (y + x * z)) : is_coprime x y := by { rw is_coprime_comm at h ⊢, exact h.of_add_mul_left_left } lemma is_coprime.of_add_mul_right_right (h : is_coprime x (y + z * x)) : is_coprime x y := by { rw mul_comm at h, exact h.of_add_mul_left_right } lemma is_coprime.of_mul_add_left_left (h : is_coprime (y * z + x) y) : is_coprime x y := by { rw add_comm at h, exact h.of_add_mul_left_left } lemma is_coprime.of_mul_add_right_left (h : is_coprime (z * y + x) y) : is_coprime x y := by { rw add_comm at h, exact h.of_add_mul_right_left } lemma is_coprime.of_mul_add_left_right (h : is_coprime x (x * z + y)) : is_coprime x y := by { rw add_comm at h, exact h.of_add_mul_left_right } lemma is_coprime.of_mul_add_right_right (h : is_coprime x (z * x + y)) : is_coprime x y := by { rw add_comm at h, exact h.of_add_mul_right_right } end comm_semiring section scalar_tower variables {R G : Type*} [comm_semiring R] [group G] [mul_action G R] [smul_comm_class G R R] [is_scalar_tower G R R] (x : G) (y z : R) lemma is_coprime_group_smul_left : is_coprime (x • y) z ↔ is_coprime y z := ⟨λ ⟨a, b, h⟩, ⟨x • a, b, by rwa [smul_mul_assoc, ←mul_smul_comm]⟩, λ ⟨a, b, h⟩, ⟨x⁻¹ • a, b, by rwa [smul_mul_smul, inv_mul_self, one_smul]⟩⟩ lemma is_coprime_group_smul_right : is_coprime y (x • z) ↔ is_coprime y z := is_coprime_comm.trans $ (is_coprime_group_smul_left x z y).trans is_coprime_comm lemma is_coprime_group_smul : is_coprime (x • y) (x • z) ↔ is_coprime y z := (is_coprime_group_smul_left x y (x • z)).trans (is_coprime_group_smul_right x y z) end scalar_tower section comm_semiring_unit variables {R : Type*} [comm_semiring R] {x : R} (hu : is_unit x) (y z : R) lemma is_coprime_mul_unit_left_left : is_coprime (x * y) z ↔ is_coprime y z := let ⟨u, hu⟩ := hu in hu ▸ is_coprime_group_smul_left u y z lemma is_coprime_mul_unit_left_right : is_coprime y (x * z) ↔ is_coprime y z := let ⟨u, hu⟩ := hu in hu ▸ is_coprime_group_smul_right u y z lemma is_coprime_mul_unit_left : is_coprime (x * y) (x * z) ↔ is_coprime y z := (is_coprime_mul_unit_left_left hu y (x * z)).trans (is_coprime_mul_unit_left_right hu y z) lemma is_coprime_mul_unit_right_left : is_coprime (y * x) z ↔ is_coprime y z := mul_comm x y ▸ is_coprime_mul_unit_left_left hu y z lemma is_coprime_mul_unit_right_right : is_coprime y (z * x) ↔ is_coprime y z := mul_comm x z ▸ is_coprime_mul_unit_left_right hu y z lemma is_coprime_mul_unit_right : is_coprime (y * x) (z * x) ↔ is_coprime y z := (is_coprime_mul_unit_right_left hu y (z * x)).trans (is_coprime_mul_unit_right_right hu y z) end comm_semiring_unit namespace is_coprime section comm_ring variables {R : Type u} [comm_ring R] lemma add_mul_left_left {x y : R} (h : is_coprime x y) (z : R) : is_coprime (x + y * z) y := @of_add_mul_left_left R _ _ _ (-z) $ by simpa only [mul_neg, add_neg_cancel_right] using h lemma add_mul_right_left {x y : R} (h : is_coprime x y) (z : R) : is_coprime (x + z * y) y := by { rw mul_comm, exact h.add_mul_left_left z } lemma add_mul_left_right {x y : R} (h : is_coprime x y) (z : R) : is_coprime x (y + x * z) := by { rw is_coprime_comm, exact h.symm.add_mul_left_left z } lemma add_mul_right_right {x y : R} (h : is_coprime x y) (z : R) : is_coprime x (y + z * x) := by { rw is_coprime_comm, exact h.symm.add_mul_right_left z } lemma mul_add_left_left {x y : R} (h : is_coprime x y) (z : R) : is_coprime (y * z + x) y := by { rw add_comm, exact h.add_mul_left_left z } lemma mul_add_right_left {x y : R} (h : is_coprime x y) (z : R) : is_coprime (z * y + x) y := by { rw add_comm, exact h.add_mul_right_left z } lemma mul_add_left_right {x y : R} (h : is_coprime x y) (z : R) : is_coprime x (x * z + y) := by { rw add_comm, exact h.add_mul_left_right z } lemma mul_add_right_right {x y : R} (h : is_coprime x y) (z : R) : is_coprime x (z * x + y) := by { rw add_comm, exact h.add_mul_right_right z } lemma add_mul_left_left_iff {x y z : R} : is_coprime (x + y * z) y ↔ is_coprime x y := ⟨of_add_mul_left_left, λ h, h.add_mul_left_left z⟩ lemma add_mul_right_left_iff {x y z : R} : is_coprime (x + z * y) y ↔ is_coprime x y := ⟨of_add_mul_right_left, λ h, h.add_mul_right_left z⟩ lemma add_mul_left_right_iff {x y z : R} : is_coprime x (y + x * z) ↔ is_coprime x y := ⟨of_add_mul_left_right, λ h, h.add_mul_left_right z⟩ lemma add_mul_right_right_iff {x y z : R} : is_coprime x (y + z * x) ↔ is_coprime x y := ⟨of_add_mul_right_right, λ h, h.add_mul_right_right z⟩ lemma mul_add_left_left_iff {x y z : R} : is_coprime (y * z + x) y ↔ is_coprime x y := ⟨of_mul_add_left_left, λ h, h.mul_add_left_left z⟩ lemma mul_add_right_left_iff {x y z : R} : is_coprime (z * y + x) y ↔ is_coprime x y := ⟨of_mul_add_right_left, λ h, h.mul_add_right_left z⟩ lemma mul_add_left_right_iff {x y z : R} : is_coprime x (x * z + y) ↔ is_coprime x y := ⟨of_mul_add_left_right, λ h, h.mul_add_left_right z⟩ lemma mul_add_right_right_iff {x y z : R} : is_coprime x (z * x + y) ↔ is_coprime x y := ⟨of_mul_add_right_right, λ h, h.mul_add_right_right z⟩ lemma neg_left {x y : R} (h : is_coprime x y) : is_coprime (-x) y := begin obtain ⟨a, b, h⟩ := h, use [-a, b], rwa neg_mul_neg, end lemma neg_left_iff (x y : R) : is_coprime (-x) y ↔ is_coprime x y := ⟨λ h, neg_neg x ▸ h.neg_left, neg_left⟩ lemma neg_right {x y : R} (h : is_coprime x y) : is_coprime x (-y) := h.symm.neg_left.symm lemma neg_right_iff (x y : R) : is_coprime x (-y) ↔ is_coprime x y := ⟨λ h, neg_neg y ▸ h.neg_right, neg_right⟩ lemma neg_neg {x y : R} (h : is_coprime x y) : is_coprime (-x) (-y) := h.neg_left.neg_right lemma neg_neg_iff (x y : R) : is_coprime (-x) (-y) ↔ is_coprime x y := (neg_left_iff _ _).trans (neg_right_iff _ _) end comm_ring lemma sq_add_sq_ne_zero {R : Type*} [linear_ordered_comm_ring R] {a b : R} (h : is_coprime a b) : a ^ 2 + b ^ 2 ≠ 0 := begin intros h', obtain ⟨ha, hb⟩ := (add_eq_zero_iff' (sq_nonneg a) (sq_nonneg b)).mp h', obtain rfl := pow_eq_zero ha, obtain rfl := pow_eq_zero hb, exact not_coprime_zero_zero h end end is_coprime
1d9f1c989ad0851a053c6878c013c5cda7491011
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/order/archimedean.lean
bf4cdcc97a2ec37f7e075330549c15f19216ca6a
[ "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
14,543
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 data.int.least_greatest import data.rat.floor /-! # Archimedean groups and fields. This file defines the archimedean property for ordered groups and proves several results connected to this notion. Being archimedean means that for all elements `x` and `y>0` there exists a natural number `n` such that `x ≤ n • y`. ## Main definitions * `archimedean` is a typeclass for an ordered additive commutative monoid to have the archimedean property. * `archimedean.floor_ring` defines a floor function on an archimedean linearly ordered ring making it into a `floor_ring`. ## Main statements * `ℕ`, `ℤ`, and `ℚ` are archimedean. -/ open int set variables {α : Type*} /-- An ordered additive commutative monoid is called `archimedean` if for any two elements `x`, `y` such that `0 < y` there exists a natural number `n` such that `x ≤ n • y`. -/ class archimedean (α) [ordered_add_comm_monoid α] : Prop := (arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y) instance order_dual.archimedean [ordered_add_comm_group α] [archimedean α] : archimedean αᵒᵈ := ⟨λ x y hy, let ⟨n, hn⟩ := archimedean.arch (-x : α) (neg_pos.2 hy) in ⟨n, by rwa [neg_nsmul, neg_le_neg_iff] at hn⟩⟩ section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] [archimedean α] /-- An archimedean decidable linearly ordered `add_comm_group` has a version of the floor: for `a > 0`, any `g` in the group lies between some two consecutive multiples of `a`. -/ lemma exists_unique_zsmul_near_of_pos {a : α} (ha : 0 < a) (g : α) : ∃! k : ℤ, k • a ≤ g ∧ g < (k + 1) • a := begin let s : set ℤ := {n : ℤ | n • a ≤ g}, obtain ⟨k, hk : -g ≤ k • a⟩ := archimedean.arch (-g) ha, have h_ne : s.nonempty := ⟨-k, by simpa using neg_le_neg hk⟩, obtain ⟨k, hk⟩ := archimedean.arch g ha, have h_bdd : ∀ n ∈ s, n ≤ (k : ℤ), { assume n hn, apply (zsmul_le_zsmul_iff ha).mp, rw ← coe_nat_zsmul at hk, exact le_trans hn hk }, obtain ⟨m, hm, hm'⟩ := int.exists_greatest_of_bdd ⟨k, h_bdd⟩ h_ne, have hm'' : g < (m + 1) • a, { contrapose! hm', exact ⟨m + 1, hm', lt_add_one _⟩, }, refine ⟨m, ⟨hm, hm''⟩, λ n hn, (hm' n hn.1).antisymm $ int.le_of_lt_add_one _⟩, rw ← zsmul_lt_zsmul_iff ha, exact lt_of_le_of_lt hm hn.2 end lemma exists_unique_zsmul_near_of_pos' {a : α} (ha : 0 < a) (g : α) : ∃! k : ℤ, 0 ≤ g - k • a ∧ g - k • a < a := by simpa only [sub_nonneg, add_zsmul, one_zsmul, sub_lt_iff_lt_add'] using exists_unique_zsmul_near_of_pos ha g lemma exists_unique_add_zsmul_mem_Ico {a : α} (ha : 0 < a) (b c : α) : ∃! m : ℤ, b + m • a ∈ set.Ico c (c + a) := (equiv.neg ℤ).bijective.exists_unique_iff.2 $ by simpa only [equiv.neg_apply, mem_Ico, neg_zsmul, ← sub_eq_add_neg, le_sub_iff_add_le, zero_add, add_comm c, sub_lt_iff_lt_add', add_assoc] using exists_unique_zsmul_near_of_pos' ha (b - c) lemma exists_unique_add_zsmul_mem_Ioc {a : α} (ha : 0 < a) (b c : α) : ∃! m : ℤ, b + m • a ∈ set.Ioc c (c + a) := (equiv.add_right (1 : ℤ)).bijective.exists_unique_iff.2 $ by simpa only [add_zsmul, sub_lt_iff_lt_add', le_sub_iff_add_le', ← add_assoc, and.comm, mem_Ioc, equiv.coe_add_right, one_zsmul, add_le_add_iff_right] using exists_unique_zsmul_near_of_pos ha (c - b) end linear_ordered_add_comm_group theorem exists_nat_gt [strict_ordered_semiring α] [archimedean α] (x : α) : ∃ n : ℕ, x < n := let ⟨n, h⟩ := archimedean.arch x zero_lt_one in ⟨n+1, lt_of_le_of_lt (by rwa ← nsmul_one) (nat.cast_lt.2 (nat.lt_succ_self _))⟩ theorem exists_nat_ge [strict_ordered_semiring α] [archimedean α] (x : α) : ∃ n : ℕ, x ≤ n := begin nontriviality α, exact (exists_nat_gt x).imp (λ n, le_of_lt) end lemma add_one_pow_unbounded_of_pos [strict_ordered_semiring α] [archimedean α] (x : α) {y : α} (hy : 0 < y) : ∃ n : ℕ, x < (y + 1) ^ n := have 0 ≤ 1 + y, from add_nonneg zero_le_one hy.le, let ⟨n, h⟩ := archimedean.arch x hy in ⟨n, calc x ≤ n • y : h ... = n * y : nsmul_eq_mul _ _ ... < 1 + n * y : lt_one_add _ ... ≤ (1 + y) ^ n : one_add_mul_le_pow' (mul_nonneg hy.le hy.le) (mul_nonneg this this) (add_nonneg zero_le_two hy.le) _ ... = (y + 1) ^ n : by rw [add_comm]⟩ section strict_ordered_ring variables [strict_ordered_ring α] [archimedean α] lemma pow_unbounded_of_one_lt (x : α) {y : α} (hy1 : 1 < y) : ∃ n : ℕ, x < y ^ n := sub_add_cancel y 1 ▸ add_one_pow_unbounded_of_pos _ (sub_pos.2 hy1) theorem exists_int_gt (x : α) : ∃ n : ℤ, x < n := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa int.cast_coe_nat⟩ theorem exists_int_lt (x : α) : ∃ n : ℤ, (n : α) < x := let ⟨n, h⟩ := exists_int_gt (-x) in ⟨-n, by rw int.cast_neg; exact neg_lt.1 h⟩ theorem exists_floor (x : α) : ∃ (fl : ℤ), ∀ (z : ℤ), z ≤ fl ↔ (z : α) ≤ x := begin haveI := classical.prop_decidable, have : ∃ (ub : ℤ), (ub:α) ≤ x ∧ ∀ (z : ℤ), (z:α) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩), refine this.imp (λ fl h z, _), cases h with h₁ h₂, exact ⟨λ h, le_trans (int.cast_le.2 h) h₁, h₂ z⟩, end end strict_ordered_ring section linear_ordered_ring variables [linear_ordered_ring α] [archimedean α] /-- Every x greater than or equal to 1 is between two successive natural-number powers of every y greater than one. -/ lemma exists_nat_pow_near {x : α} {y : α} (hx : 1 ≤ x) (hy : 1 < y) : ∃ n : ℕ, y ^ n ≤ x ∧ x < y ^ (n + 1) := have h : ∃ n : ℕ, x < y ^ n, from pow_unbounded_of_one_lt _ hy, by classical; exact let n := nat.find h in have hn : x < y ^ n, from nat.find_spec h, have hnp : 0 < n, from pos_iff_ne_zero.2 (λ hn0, by rw [hn0, pow_zero] at hn; exact (not_le_of_gt hn hx)), have hnsp : nat.pred n + 1 = n, from nat.succ_pred_eq_of_pos hnp, have hltn : nat.pred n < n, from nat.pred_lt (ne_of_gt hnp), ⟨nat.pred n, le_of_not_lt (nat.find_min h hltn), by rwa hnsp⟩ end linear_ordered_ring section linear_ordered_field variables [linear_ordered_field α] [archimedean α] {x y ε : α} /-- Every positive `x` is between two successive integer powers of another `y` greater than one. This is the same as `exists_mem_Ioc_zpow`, but with ≤ and < the other way around. -/ lemma exists_mem_Ico_zpow (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, x ∈ Ico (y ^ n) (y ^ (n + 1)) := by classical; exact let ⟨N, hN⟩ := pow_unbounded_of_one_lt x⁻¹ hy in have he: ∃ m : ℤ, y ^ m ≤ x, from ⟨-N, le_of_lt (by { rw [zpow_neg y (↑N), zpow_coe_nat], exact (inv_lt hx (lt_trans (inv_pos.2 hx) hN)).1 hN })⟩, let ⟨M, hM⟩ := pow_unbounded_of_one_lt x hy in have hb: ∃ b : ℤ, ∀ m, y ^ m ≤ x → m ≤ b, from ⟨M, λ m hm, le_of_not_lt (λ hlt, not_lt_of_ge (zpow_le_of_le hy.le hlt.le) (lt_of_le_of_lt hm (by rwa ← zpow_coe_nat at hM)))⟩, let ⟨n, hn₁, hn₂⟩ := int.exists_greatest_of_bdd hb he in ⟨n, hn₁, lt_of_not_ge (λ hge, not_le_of_gt (int.lt_succ _) (hn₂ _ hge))⟩ /-- Every positive `x` is between two successive integer powers of another `y` greater than one. This is the same as `exists_mem_Ico_zpow`, but with ≤ and < the other way around. -/ lemma exists_mem_Ioc_zpow (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, x ∈ Ioc (y ^ n) (y ^ (n + 1)) := let ⟨m, hle, hlt⟩ := exists_mem_Ico_zpow (inv_pos.2 hx) hy in have hyp : 0 < y, from lt_trans zero_lt_one hy, ⟨-(m+1), by rwa [zpow_neg, inv_lt (zpow_pos_of_pos hyp _) hx], by rwa [neg_add, neg_add_cancel_right, zpow_neg, le_inv hx (zpow_pos_of_pos hyp _)]⟩ /-- For any `y < 1` and any positive `x`, there exists `n : ℕ` with `y ^ n < x`. -/ lemma exists_pow_lt_of_lt_one (hx : 0 < x) (hy : y < 1) : ∃ n : ℕ, y ^ n < x := begin by_cases y_pos : y ≤ 0, { use 1, simp only [pow_one], linarith, }, rw [not_le] at y_pos, rcases pow_unbounded_of_one_lt (x⁻¹) (one_lt_inv y_pos hy) with ⟨q, hq⟩, exact ⟨q, by rwa [inv_pow, inv_lt_inv hx (pow_pos y_pos _)] at hq⟩ end /-- Given `x` and `y` between `0` and `1`, `x` is between two successive powers of `y`. This is the same as `exists_nat_pow_near`, but for elements between `0` and `1` -/ lemma exists_nat_pow_near_of_lt_one (xpos : 0 < x) (hx : x ≤ 1) (ypos : 0 < y) (hy : y < 1) : ∃ n : ℕ, y ^ (n + 1) < x ∧ x ≤ y ^ n := begin rcases exists_nat_pow_near (one_le_inv_iff.2 ⟨xpos, hx⟩) (one_lt_inv_iff.2 ⟨ypos, hy⟩) with ⟨n, hn, h'n⟩, refine ⟨n, _, _⟩, { rwa [inv_pow, inv_lt_inv xpos (pow_pos ypos _)] at h'n }, { rwa [inv_pow, inv_le_inv (pow_pos ypos _) xpos] at hn } end lemma exists_rat_gt (x : α) : ∃ q : ℚ, x < q := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa rat.cast_coe_nat⟩ theorem exists_rat_lt (x : α) : ∃ q : ℚ, (q : α) < x := let ⟨n, h⟩ := exists_int_lt x in ⟨n, by rwa rat.cast_coe_int⟩ theorem exists_rat_btwn {x y : α} (h : x < y) : ∃ q : ℚ, x < q ∧ (q:α) < y := begin cases exists_nat_gt (y - x)⁻¹ with n nh, cases exists_floor (x * n) with z zh, refine ⟨(z + 1 : ℤ) / n, _⟩, have n0' := (inv_pos.2 (sub_pos.2 h)).trans nh, have n0 := nat.cast_pos.1 n0', rw [rat.cast_div_of_ne_zero, rat.cast_coe_nat, rat.cast_coe_int, div_lt_iff n0'], refine ⟨(lt_div_iff n0').2 $ (lt_iff_lt_of_le_iff_le (zh _)).1 (lt_add_one _), _⟩, rw [int.cast_add, int.cast_one], refine lt_of_le_of_lt (add_le_add_right ((zh _).1 le_rfl) _) _, rwa [← lt_sub_iff_add_lt', ← sub_mul, ← div_lt_iff' (sub_pos.2 h), one_div], { rw [rat.coe_int_denom, nat.cast_one], exact one_ne_zero }, { intro H, rw [rat.coe_nat_num, int.cast_coe_nat, nat.cast_eq_zero] at H, subst H, cases n0 }, { rw [rat.coe_nat_denom, nat.cast_one], exact one_ne_zero } end lemma le_of_forall_rat_lt_imp_le (h : ∀ q : ℚ, (q : α) < x → (q : α) ≤ y) : x ≤ y := le_of_not_lt $ λ hyx, let ⟨q, hy, hx⟩ := exists_rat_btwn hyx in hy.not_le $ h _ hx lemma le_of_forall_lt_rat_imp_le (h : ∀ q : ℚ, y < q → x ≤ q) : x ≤ y := le_of_not_lt $ λ hyx, let ⟨q, hy, hx⟩ := exists_rat_btwn hyx in hx.not_le $ h _ hy lemma eq_of_forall_rat_lt_iff_lt (h : ∀ q : ℚ, (q : α) < x ↔ (q : α) < y) : x = y := (le_of_forall_rat_lt_imp_le $ λ q hq, ((h q).1 hq).le).antisymm $ le_of_forall_rat_lt_imp_le $ λ q hq, ((h q).2 hq).le lemma eq_of_forall_lt_rat_iff_lt (h : ∀ q : ℚ, x < q ↔ y < q) : x = y := (le_of_forall_lt_rat_imp_le $ λ q hq, ((h q).2 hq).le).antisymm $ le_of_forall_lt_rat_imp_le $ λ q hq, ((h q).1 hq).le theorem exists_nat_one_div_lt {ε : α} (hε : 0 < ε) : ∃ n : ℕ, 1 / (n + 1: α) < ε := begin cases exists_nat_gt (1/ε) with n hn, use n, rw [div_lt_iff, ← div_lt_iff' hε], { apply hn.trans, simp [zero_lt_one] }, { exact n.cast_add_one_pos } end theorem exists_pos_rat_lt {x : α} (x0 : 0 < x) : ∃ q : ℚ, 0 < q ∧ (q : α) < x := by simpa only [rat.cast_pos] using exists_rat_btwn x0 lemma exists_rat_near (x : α) (ε0 : 0 < ε) : ∃ q : ℚ, |x - q| < ε := let ⟨q, h₁, h₂⟩ := exists_rat_btwn $ ((sub_lt_self_iff x).2 ε0).trans ((lt_add_iff_pos_left x).2 ε0) in ⟨q, abs_sub_lt_iff.2 ⟨sub_lt_comm.1 h₁, sub_lt_iff_lt_add.2 h₂⟩⟩ end linear_ordered_field section linear_ordered_field variables [linear_ordered_field α] lemma archimedean_iff_nat_lt : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x < n := ⟨@exists_nat_gt α _, λ H, ⟨λ x y y0, (H (x / y)).imp $ λ n h, le_of_lt $ by rwa [div_lt_iff y0, ← nsmul_eq_mul] at h⟩⟩ lemma archimedean_iff_nat_le : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x ≤ n := archimedean_iff_nat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (nat.cast_lt.2 (lt_add_one _))⟩⟩ lemma archimedean_iff_int_lt : archimedean α ↔ ∀ x : α, ∃ n : ℤ, x < n := ⟨@exists_int_gt α _, begin rw archimedean_iff_nat_lt, intros h x, obtain ⟨n, h⟩ := h x, refine ⟨n.to_nat, h.trans_le _⟩, exact_mod_cast int.le_to_nat _, end⟩ lemma archimedean_iff_int_le : archimedean α ↔ ∀ x : α, ∃ n : ℤ, x ≤ n := archimedean_iff_int_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (int.cast_lt.2 (lt_add_one _))⟩⟩ lemma archimedean_iff_rat_lt : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x < q := ⟨@exists_rat_gt α _, λ H, archimedean_iff_nat_lt.2 $ λ x, let ⟨q, h⟩ := H x in ⟨⌈q⌉₊, lt_of_lt_of_le h $ by simpa only [rat.cast_coe_nat] using (@rat.cast_le α _ _ _).2 (nat.le_ceil _)⟩⟩ lemma archimedean_iff_rat_le : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x ≤ q := archimedean_iff_rat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (rat.cast_lt.2 (lt_add_one _))⟩⟩ end linear_ordered_field instance : archimedean ℕ := ⟨λ n m m0, ⟨n, by simpa only [mul_one, nat.nsmul_eq_mul] using nat.mul_le_mul_left n m0⟩⟩ instance : archimedean ℤ := ⟨λ n m m0, ⟨n.to_nat, le_trans (int.le_to_nat _) $ by simpa only [nsmul_eq_mul, zero_add, mul_one] using mul_le_mul_of_nonneg_left (int.add_one_le_iff.2 m0) (int.coe_zero_le n.to_nat)⟩⟩ instance : archimedean ℚ := archimedean_iff_rat_le.2 $ λ q, ⟨q, by rw rat.cast_id⟩ /-- A linear ordered archimedean ring is a floor ring. This is not an `instance` because in some cases we have a computable `floor` function. -/ noncomputable def archimedean.floor_ring (α) [linear_ordered_ring α] [archimedean α] : floor_ring α := floor_ring.of_floor α (λ a, classical.some (exists_floor a)) (λ z a, (classical.some_spec (exists_floor a) z).symm) /-- A linear ordered field that is a floor ring is archimedean. -/ @[priority 100] -- see Note [lower instance priority] instance floor_ring.archimedean (α) [linear_ordered_field α] [floor_ring α] : archimedean α := begin rw archimedean_iff_int_le, exact λ x, ⟨⌈x⌉, int.le_ceil x⟩ end
1950c06a2b54f5e05814a126e796509c75400e8b
80746c6dba6a866de5431094bf9f8f841b043d77
/src/category_theory/natural_isomorphism.lean
fd94b2030fd52d445c1d34d6b0f4baf725f9b8d5
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
5,408
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.isomorphism import category_theory.functor_category open category_theory namespace category_theory.nat_iso universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒞 𝒟 def app {F G : C ⥤ D} (α : F ≅ G) (X : C) : F.obj X ≅ G.obj X := { hom := α.hom.app X, inv := α.inv.app X, hom_inv_id' := begin rw [← functor.category.comp_app, iso.hom_inv_id], refl, end, inv_hom_id' := begin rw [← functor.category.comp_app, iso.inv_hom_id], refl, end } @[simp] lemma comp_app {F G H : C ⥤ D} (α : F ≅ G) (β : G ≅ H) (X : C) : app (α ≪≫ β) X = app α X ≪≫ app β X := rfl @[simp] lemma app_hom {F G : C ⥤ D} (α : F ≅ G) (X : C) : (app α X).hom = α.hom.app X := rfl @[simp] lemma app_inv {F G : C ⥤ D} (α : F ≅ G) (X : C) : (app α X).inv = α.inv.app X := rfl variables {F G : C ⥤ D} instance hom_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.hom.app X) := { inv := α.inv.app X, hom_inv_id' := begin rw [←functor.category.comp_app, iso.hom_inv_id, ←functor.category.id_app] end, inv_hom_id' := begin rw [←functor.category.comp_app, iso.inv_hom_id, ←functor.category.id_app] end } instance inv_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.inv.app X) := { inv := α.hom.app X, hom_inv_id' := begin rw [←functor.category.comp_app, iso.inv_hom_id, ←functor.category.id_app] end, inv_hom_id' := begin rw [←functor.category.comp_app, iso.hom_inv_id, ←functor.category.id_app] end } @[simp] lemma hom_vcomp_inv (α : F ≅ G) : (α.hom ⊟ α.inv) = nat_trans.id _ := begin have h : (α.hom ⊟ α.inv) = α.hom ≫ α.inv := rfl, rw h, rw iso.hom_inv_id, refl end @[simp] lemma inv_vcomp_hom (α : F ≅ G) : (α.inv ⊟ α.hom) = nat_trans.id _ := begin have h : (α.inv ⊟ α.hom) = α.inv ≫ α.hom := rfl, rw h, rw iso.inv_hom_id, refl end @[simp] lemma hom_app_inv_app_id (α : F ≅ G) (X : C) : α.hom.app X ≫ α.inv.app X = 𝟙 _ := begin rw ←nat_trans.vcomp_app, simp, end @[simp] lemma inv_app_hom_app_id (α : F ≅ G) (X : C) : α.inv.app X ≫ α.hom.app X = 𝟙 _ := begin rw ←nat_trans.vcomp_app, simp, end variables {X Y : C} @[simp] lemma naturality_1 (α : F ≅ G) (f : X ⟶ Y) : (α.inv.app X) ≫ (F.map f) ≫ (α.hom.app Y) = G.map f := begin erw [nat_trans.naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end @[simp] lemma naturality_2 (α : F ≅ G) (f : X ⟶ Y) : (α.hom.app X) ≫ (G.map f) ≫ (α.inv.app Y) = F.map f := begin erw [nat_trans.naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end def of_components (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality : ∀ {X Y : C} (f : X ⟶ Y), (F.map f) ≫ ((app Y).hom) = ((app X).hom) ≫ (G.map f)) : F ≅ G := { hom := { app := λ X, ((app X).hom), }, inv := { app := λ X, ((app X).inv), naturality' := λ X Y f, by simpa using congr_arg (λ f, (app X).inv ≫ (f ≫ (app Y).inv)) (naturality f).symm } } @[simp] def of_components.app (app' : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : app (of_components app' naturality) X = app' X := by tidy @[simp] def of_components.hom_app (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : (of_components app naturality).hom.app X = (app X).hom := rfl @[simp] def of_components.inv_app (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : (of_components app naturality).inv.app X = (app X).inv := rfl end category_theory.nat_iso namespace category_theory.functor universes u₁ u₂ v₁ v₂ section variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒞 𝒟 @[simp] protected def id_comp (F : C ⥤ D) : functor.id C ⋙ F ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } @[simp] protected def comp_id (F : C ⥤ D) : F ⋙ functor.id D ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } universes u₃ v₃ u₄ v₄ variables {A : Type u₃} [𝒜 : category.{v₃} A] {B : Type u₄} [ℬ : category.{v₄} B] include 𝒜 ℬ variables (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) @[simp] protected def assoc : (F ⋙ G) ⋙ H ≅ F ⋙ (G ⋙ H ):= { hom := { app := λ X, 𝟙 (H.obj (G.obj (F.obj X))) }, inv := { app := λ X, 𝟙 (H.obj (G.obj (F.obj X))) } } -- When it's time to define monoidal categories and 2-categories, -- we'll need to add lemmas relating these natural isomorphisms, -- in particular the pentagon for the associator. end section variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 def ulift_down_up : ulift_down.{v₁} C ⋙ ulift_up C ≅ functor.id (ulift.{u₂} C) := { hom := { app := λ X, @category.id (ulift.{u₂} C) _ X }, inv := { app := λ X, @category.id (ulift.{u₂} C) _ X } } def ulift_up_down : ulift_up.{v₁} C ⋙ ulift_down C ≅ functor.id C := { hom := { app := λ X, 𝟙 X }, inv := { app := λ X, 𝟙 X } } end end category_theory.functor
7550f975b7724de6fbc9869f71c31f08b54734e4
947b78d97130d56365ae2ec264df196ce769371a
/tests/playground/cmdparsertest1.lean
7293984425596066e4a1ab4d41b2d5efc997a453
[ "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,192
lean
import Lean.Parser.Command open Lean open Lean.Parser def testParser (input : String) : IO Unit := do env ← mkEmptyEnvironment; cmdPTables ← builtinCommandParsingTable.get; stx ← IO.ofExcept $ runParser env cmdPTables input "<input>" "command"; IO.println stx def test (is : List String) : IO Unit := is.mfor $ fun input => do IO.println input; testParser input def main (xs : List String) : IO Unit := do IO.println Command.declaration.info.firstTokens; test [ "@[inline] def x := 2", "protected def length.{u} {α : Type u} : List α → Nat | [] := 0 | (a::as) := 1 + length as", "/-- doc string test -/ private theorem bla (x : Nat) : x = x := Eq.refl x", "class Alternative (f : Type u → Type v) extends Applicative f : Type (max (u+1) v) := (failure : ∀ {α : Type u}, f α) (orelse : ∀ {α : Type u}, f α → f α → f α) ", "local attribute [instance] foo bla", "attribute [inline] test", "open Lean (hiding Name)", "reserve infixr ` ∨ `:30", "reserve prefix `¬`:40", "infixr ` ^ ` := HasPow.pow", "notation f ` $ `:1 a:0 := f a", "notation `Prop` := Sort 0", "notation `∅` := HasEmptyc.emptyc _", "notation `⟦`:max a `⟧`:0 := Quotient.mk a" ]
d30b67399fbc95dc3c1ea6922b1cf94aef4022a1
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/noncomputable_bug.lean
f09f5032ba6b6d54b8ce0d4fd0cf6b5154adcbf1
[ "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
116
lean
new_frontend axiom f : ∀ (A : Type), A → Type def ex5b (α : Type) (a : α) : ∀ (A : Type), A → Type := f
6437219d36945792dc8f3e688008e9e19590cc71
b9a81ebb9de684db509231c4469a7d2c88915808
/src/super/misc_preprocessing.lean
1104b441d32bc5afabda281e463115c66afb7705
[]
no_license
leanprover/super
3dd81ce8d9ac3cba20bce55e84833fadb2f5716e
47b107b4cec8f3b41d72daba9cbda2f9d54025de
refs/heads/master
1,678,482,996,979
1,676,526,367,000
1,676,526,367,000
92,215,900
12
6
null
1,513,327,539,000
1,495,570,640,000
Lean
UTF-8
Lean
false
false
1,134
lean
/- Copyright (c) 2017 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause .prover_state open expr list monad namespace super meta def is_taut (c : clause) : tactic bool := do qf ← c.open_constn c.num_quants, return $ list.bor $ do l1 ← qf.1.get_lits, guard l1.is_neg, l2 ← qf.1.get_lits, guard l2.is_pos, [decidable.to_bool $ l1.formula = l2.formula] meta def tautology_removal_pre : prover unit := preprocessing_rule $ λnew, filter (λc, bnot <$> is_taut c.c) new meta def remove_duplicates : list derived_clause → list derived_clause | [] := [] | (c :: cs) := let (same_type, other_type) := partition (λc' : derived_clause, c'.c.type = c.c.type) cs in { c with sc := foldl score.min c.sc (same_type.map $ λc, c.sc) } :: remove_duplicates other_type meta def remove_duplicates_pre : prover unit := preprocessing_rule $ λnew, return $ remove_duplicates new meta def clause_normalize_pre : prover unit := preprocessing_rule $ λnew, new.mmap $ λdc, do c' ← dc.c.normalize, return { dc with c := c' } end super
871bd14ed4525f5bc08baad8566d7bbf161fd482
367134ba5a65885e863bdc4507601606690974c1
/src/control/traversable/derive.lean
68d5db907885ac4267014a24678f6f14e689c8d2
[ "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
17,057
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Automation to construct `traversable` instances -/ import control.traversable.lemmas import data.list.basic namespace tactic.interactive open tactic list monad functor meta def with_prefix : option name → name → name | none n := n | (some p) n := p ++ n /-- similar to `nested_traverse` but for `functor` -/ meta def nested_map (f v : expr) : expr → tactic expr | t := do t ← instantiate_mvars t, mcond (succeeds $ is_def_eq t v) (pure f) (if ¬ v.occurs (t.app_fn) then do cl ← mk_app ``functor [t.app_fn], _inst ← mk_instance cl, f' ← nested_map t.app_arg, mk_mapp ``functor.map [t.app_fn,_inst,none,none,f'] else fail format!"type {t} is not a functor with respect to variable {v}") /-- similar to `traverse_field` but for `functor` -/ meta def map_field (n : name) (cl f α β e : expr) : tactic expr := do t ← infer_type e >>= whnf, if t.get_app_fn.const_name = n then fail "recursive types not supported" else if α =ₐ e then pure β else if α.occurs t then do f' ← nested_map f α t, pure $ f' e else (is_def_eq t.app_fn cl >> mk_app ``comp.mk [e]) <|> pure e /-- similar to `traverse_constructor` but for `functor` -/ meta def map_constructor (c n : name) (f α β : expr) (args₀ : list expr) (args₁ : list (bool × expr)) (rec_call : list expr) : tactic expr := do g ← target, (_, args') ← mmap_accuml (λ (x : list expr) (y : bool × expr), if y.1 then pure (x.tail,x.head) else prod.mk rec_call <$> map_field n g.app_fn f α β y.2) rec_call args₁, constr ← mk_const c, let r := constr.mk_app (args₀ ++ args'), return r /-- derive the `map` definition of a `functor` -/ meta def mk_map (type : name) := do ls ← local_context, [α,β,f,x] ← tactic.intro_lst [`α,`β,`f,`x], et ← infer_type x, xs ← tactic.induction x, xs.mmap' (λ (x : name × list expr × list (name × expr)), do let (c,args,_) := x, (args,rec_call) ← args.mpartition $ λ e, (bnot ∘ β.occurs) <$> infer_type e, args₀ ← args.mmap $ λ a, do { b ← et.occurs <$> infer_type a, pure (b,a) }, map_constructor c type f α β (ls ++ [β]) args₀ rec_call >>= tactic.exact) meta def mk_mapp_aux' : expr → expr → list expr → tactic expr | fn (expr.pi n bi d b) (a::as) := do infer_type a >>= unify d, fn ← head_beta (fn a), t ← whnf (b.instantiate_var a), mk_mapp_aux' fn t as | fn _ _ := pure fn meta def mk_mapp' (fn : expr) (args : list expr) : tactic expr := do t ← infer_type fn >>= whnf, mk_mapp_aux' fn t args /-- derive the equations for a specific `map` definition -/ meta def derive_map_equations (pre : option name) (n : name) (vs : list expr) (tgt : expr) : tactic unit := do e ← get_env, ((e.constructors_of n).enum_from 1).mmap' $ λ ⟨i,c⟩, do { mk_meta_var tgt >>= set_goals ∘ pure, vs ← intro_lst $ vs.map expr.local_pp_name, [α,β,f] ← tactic.intro_lst [`α,`β,`f] >>= mmap instantiate_mvars, c' ← mk_mapp c $ vs.map some ++ [α], tgt' ← infer_type c' >>= pis vs, mk_meta_var tgt' >>= set_goals ∘ pure, vs ← tactic.intro_lst $ vs.map expr.local_pp_name, vs' ← tactic.intros, c' ← mk_mapp c $ vs.map some ++ [α], arg ← mk_mapp' c' vs', n_map ← mk_const (with_prefix pre n <.> "map"), let call_map := λ x, mk_mapp' n_map (vs ++ [α,β,f,x]), lhs ← call_map arg, args ← vs'.mmap $ λ a, do { t ← infer_type a, pure ((expr.const_name (expr.get_app_fn t) = n : bool),a) }, let rec_call := args.filter_map $ λ ⟨b, e⟩, guard b >> pure e, rec_call ← rec_call.mmap call_map, rhs ← map_constructor c n f α β (vs ++ [β]) args rec_call, monad.join $ unify <$> infer_type lhs <*> infer_type rhs, eqn ← mk_app ``eq [lhs,rhs], let ws := eqn.list_local_consts, eqn ← pis ws.reverse eqn, eqn ← instantiate_mvars eqn, (_,pr) ← solve_aux eqn (tactic.intros >> refine ``(rfl)), let eqn_n := (with_prefix pre n <.> "map" <.> "equations" <.> "_eqn").append_after i, pr ← instantiate_mvars pr, add_decl $ declaration.thm eqn_n eqn.collect_univ_params eqn (pure pr), return () }, set_goals [], return () meta def derive_functor (pre : option name) : tactic unit := do vs ← local_context, `(functor %%f) ← target, env ← get_env, let n := f.get_app_fn.const_name, d ← get_decl n, refine ``( { functor . map := _ , .. } ), tgt ← target, extract_def (with_prefix pre n <.> "map") d.is_trusted $ mk_map n, when (d.is_trusted) $ do tgt ← pis vs tgt, derive_map_equations pre n vs tgt /-- `seq_apply_constructor f [x,y,z]` synthesizes `f <*> x <*> y <*> z` -/ private meta def seq_apply_constructor : expr → list (expr ⊕ expr) → tactic (list (tactic expr) × expr) | e (sum.inr x :: xs) := prod.map (cons intro1) id <$> (to_expr ``(%%e <*> %%x) >>= flip seq_apply_constructor xs) | e (sum.inl x :: xs) := prod.map (cons $ pure x) id <$> seq_apply_constructor e xs | e [] := return ([],e) /-- ``nested_traverse f α (list (array n (list α)))`` synthesizes the expression `traverse (traverse (traverse f))`. `nested_traverse` assumes that `α` appears in `(list (array n (list α)))` -/ meta def nested_traverse (f v : expr) : expr → tactic expr | t := do t ← instantiate_mvars t, mcond (succeeds $ is_def_eq t v) (pure f) (if ¬ v.occurs (t.app_fn) then do cl ← mk_app ``traversable [t.app_fn], _inst ← mk_instance cl, f' ← nested_traverse t.app_arg, mk_mapp ``traversable.traverse [t.app_fn,_inst,none,none,none,none,f'] else fail format!"type {t} is not traversable with respect to variable {v}") /-- For a sum type `inductive foo (α : Type) | foo1 : list α → ℕ → foo | ...` ``traverse_field `foo appl_inst f `α `(x : list α)`` synthesizes `traverse f x` as part of traversing `foo1`. -/ meta def traverse_field (n : name) (appl_inst cl f v e : expr) : tactic (expr ⊕ expr) := do t ← infer_type e >>= whnf, if t.get_app_fn.const_name = n then fail "recursive types not supported" else if v.occurs t then do f' ← nested_traverse f v t, pure $ sum.inr $ f' e else (is_def_eq t.app_fn cl >> sum.inr <$> mk_app ``comp.mk [e]) <|> pure (sum.inl e) /-- For a sum type `inductive foo (α : Type) | foo1 : list α → ℕ → foo | ...` ``traverse_constructor `foo1 `foo appl_inst f `α `β [`(x : list α), `(y : ℕ)]`` synthesizes `foo1 <$> traverse f x <*> pure y.` -/ meta def traverse_constructor (c n : name) (appl_inst f α β : expr) (args₀ : list expr) (args₁ : list (bool × expr)) (rec_call : list expr) : tactic expr := do g ← target, args' ← mmap (traverse_field n appl_inst g.app_fn f α) args₀, (_, args') ← mmap_accuml (λ (x : list expr) (y : bool × _), if y.1 then pure (x.tail, sum.inr x.head) else prod.mk x <$> traverse_field n appl_inst g.app_fn f α y.2) rec_call args₁, constr ← mk_const c, v ← mk_mvar, constr' ← to_expr ``(@pure _ (%%appl_inst).to_has_pure _ %%v), (vars_intro,r) ← seq_apply_constructor constr' (args₀.map sum.inl ++ args'), gs ← get_goals, set_goals [v], vs ← vars_intro.mmap id, tactic.exact (constr.mk_app vs), done, set_goals gs, return r /-- derive the `traverse` definition of a `traversable` instance -/ meta def mk_traverse (type : name) := do do ls ← local_context, [m,appl_inst,α,β,f,x] ← tactic.intro_lst [`m,`appl_inst,`α,`β,`f,`x], et ← infer_type x, reset_instance_cache, xs ← tactic.induction x, xs.mmap' (λ (x : name × list expr × list (name × expr)), do let (c,args,_) := x, (args,rec_call) ← args.mpartition $ λ e, (bnot ∘ β.occurs) <$> infer_type e, args₀ ← args.mmap $ λ a, do { b ← et.occurs <$> infer_type a, pure (b,a) }, traverse_constructor c type appl_inst f α β (ls ++ [β]) args₀ rec_call >>= tactic.exact) open applicative /-- derive the equations for a specific `traverse` definition -/ meta def derive_traverse_equations (pre : option name) (n : name) (vs : list expr) (tgt : expr) : tactic unit := do e ← get_env, ((e.constructors_of n).enum_from 1).mmap' $ λ ⟨i,c⟩, do { mk_meta_var tgt >>= set_goals ∘ pure, vs ← intro_lst $ vs.map expr.local_pp_name, [m,appl_inst,α,β,f] ← tactic.intro_lst [`m,`appl_inst,`α,`β,`f] >>= mmap instantiate_mvars, c' ← mk_mapp c $ vs.map some ++ [α], tgt' ← infer_type c' >>= pis vs, mk_meta_var tgt' >>= set_goals ∘ pure, vs ← tactic.intro_lst $ vs.map expr.local_pp_name, c' ← mk_mapp c $ vs.map some ++ [α], vs' ← tactic.intros, arg ← mk_mapp' c' vs', n_map ← mk_const (with_prefix pre n <.> "traverse"), let call_traverse := λ x, mk_mapp' n_map (vs ++ [m,appl_inst,α,β,f,x]), lhs ← call_traverse arg, args ← vs'.mmap $ λ a, do { t ← infer_type a, pure ((expr.const_name (expr.get_app_fn t) = n : bool),a) }, let rec_call := args.filter_map $ λ ⟨b, e⟩, guard b >> pure e, rec_call ← rec_call.mmap call_traverse, rhs ← traverse_constructor c n appl_inst f α β (vs ++ [β]) args rec_call, monad.join $ unify <$> infer_type lhs <*> infer_type rhs, eqn ← mk_app ``eq [lhs,rhs], let ws := eqn.list_local_consts, eqn ← pis ws.reverse eqn, eqn ← instantiate_mvars eqn, (_,pr) ← solve_aux eqn (tactic.intros >> refine ``(rfl)), let eqn_n := (with_prefix pre n <.> "traverse" <.> "equations" <.> "_eqn").append_after i, pr ← instantiate_mvars pr, add_decl $ declaration.thm eqn_n eqn.collect_univ_params eqn (pure pr), return () }, set_goals [], return () meta def derive_traverse (pre : option name) : tactic unit := do vs ← local_context, `(traversable %%f) ← target, env ← get_env, let n := f.get_app_fn.const_name, d ← get_decl n, constructor, tgt ← target, extract_def (with_prefix pre n <.> "traverse") d.is_trusted $ mk_traverse n, when (d.is_trusted) $ do tgt ← pis vs tgt, derive_traverse_equations pre n vs tgt meta def mk_one_instance (n : name) (cls : name) (tac : tactic unit) (namesp : option name) (mk_inst : name → expr → tactic expr := λ n arg, mk_app n [arg]) : tactic unit := do decl ← get_decl n, cls_decl ← get_decl cls, env ← get_env, guard (env.is_inductive n) <|> fail format!"failed to derive '{cls}', '{n}' is not an inductive type", let ls := decl.univ_params.map $ λ n, level.param n, -- incrementally build up target expression `Π (hp : p) [cls hp] ..., cls (n.{ls} hp ...)` -- where `p ...` are the inductive parameter types of `n` let tgt : expr := expr.const n ls, ⟨params, _⟩ ← open_pis (decl.type.instantiate_univ_params (decl.univ_params.zip ls)), let params := params.init, let tgt := tgt.mk_app params, tgt ← mk_inst cls tgt, tgt ← params.enum.mfoldr (λ ⟨i, param⟩ tgt, do -- add typeclass hypothesis for each inductive parameter tgt ← do { guard $ i < env.inductive_num_params n, param_cls ← mk_app cls [param], pure $ expr.pi `a binder_info.inst_implicit param_cls tgt } <|> pure tgt, pure $ tgt.bind_pi param ) tgt, () <$ mk_instance tgt <|> do (_, val) ← tactic.solve_aux tgt (do tactic.intros >> tac), val ← instantiate_mvars val, let trusted := decl.is_trusted ∧ cls_decl.is_trusted, let inst_n := with_prefix namesp n ++ cls, add_decl (declaration.defn inst_n decl.univ_params tgt val reducibility_hints.abbrev trusted), set_basic_attribute `instance inst_n namesp.is_none open interactive meta def get_equations_of (n : name) : tactic (list pexpr) := do e ← get_env, let pre := n <.> "equations", let x := e.fold [] $ λ d xs, if pre.is_prefix_of d.to_name then d.to_name :: xs else xs, x.mmap resolve_name meta def derive_lawful_functor (pre : option name) : tactic unit := do `(@is_lawful_functor %%f %%d) ← target, refine ``( { .. } ), let n := f.get_app_fn.const_name, let rules := λ r, [simp_arg_type.expr r, simp_arg_type.all_hyps], let goal := loc.ns [none], solve1 (do vs ← tactic.intros, try $ dunfold [``functor.map] (loc.ns [none]), dunfold [with_prefix pre n <.> "map",``id] (loc.ns [none]), () <$ tactic.induction vs.ilast; simp none none ff (rules ``(functor.map_id)) [] goal), focus1 (do vs ← tactic.intros, try $ dunfold [``functor.map] (loc.ns [none]), dunfold [with_prefix pre n <.> "map",``id] (loc.ns [none]), () <$ tactic.induction vs.ilast; simp none none ff (rules ``(functor.map_comp_map)) [] goal), return () meta def simp_functor (rs : list simp_arg_type := []) : tactic unit := simp none none ff rs [`functor_norm] (loc.ns [none]) meta def traversable_law_starter (rs : list simp_arg_type) := do vs ← tactic.intros, resetI, dunfold [``traversable.traverse,``functor.map] (loc.ns [none]), () <$ tactic.induction vs.ilast; simp_functor rs meta def derive_lawful_traversable (pre : option name) : tactic unit := do `(@is_lawful_traversable %%f %%d) ← target, let n := f.get_app_fn.const_name, eqns ← get_equations_of (with_prefix pre n <.> "traverse"), eqns' ← get_equations_of (with_prefix pre n <.> "map"), let def_eqns := eqns.map simp_arg_type.expr ++ eqns'.map simp_arg_type.expr ++ [simp_arg_type.all_hyps], let comp_def := [ simp_arg_type.expr ``(function.comp) ], let tr_map := list.map simp_arg_type.expr [``(traversable.traverse_eq_map_id')], let natur := λ (η : expr), [simp_arg_type.expr ``(traversable.naturality_pf %%η)], let goal := loc.ns [none], constructor; [ traversable_law_starter def_eqns; refl, traversable_law_starter def_eqns; (refl <|> simp_functor (def_eqns ++ comp_def)), traversable_law_starter def_eqns; (refl <|> simp none none tt tr_map [] goal ), traversable_law_starter def_eqns; (refl <|> do η ← get_local `η <|> do { t ← mk_const ``is_lawful_traversable.naturality >>= infer_type >>= pp, fail format!"expecting an `applicative_transformation` called `η` in\nnaturality : {t}"}, simp none none tt (natur η) [] goal) ]; refl, return () open function meta def guard_class (cls : name) (hdl : derive_handler) : derive_handler := λ p n, if p.is_constant_of cls then hdl p n else pure ff meta def higher_order_derive_handler (cls : name) (tac : tactic unit) (deps : list derive_handler := []) (namesp : option name) (mk_inst : name → expr → tactic expr := λ n arg, mk_app n [arg]) : derive_handler := λ p n, do mmap' (λ f : derive_handler, f p n) deps, mk_one_instance n cls tac namesp mk_inst, pure tt meta def functor_derive_handler' (nspace : option name := none) : derive_handler := higher_order_derive_handler ``functor (derive_functor nspace) [] nspace @[derive_handler] meta def functor_derive_handler : derive_handler := guard_class ``functor functor_derive_handler' meta def traversable_derive_handler' (nspace : option name := none) : derive_handler := higher_order_derive_handler ``traversable (derive_traverse nspace) [functor_derive_handler' nspace] nspace @[derive_handler] meta def traversable_derive_handler : derive_handler := guard_class ``traversable traversable_derive_handler' meta def lawful_functor_derive_handler' (nspace : option name := none) : derive_handler := higher_order_derive_handler ``is_lawful_functor (derive_lawful_functor nspace) [traversable_derive_handler' nspace] nspace (λ n arg, mk_mapp n [arg,none]) @[derive_handler] meta def lawful_functor_derive_handler : derive_handler := guard_class ``is_lawful_functor lawful_functor_derive_handler' meta def lawful_traversable_derive_handler' (nspace : option name := none) : derive_handler := higher_order_derive_handler ``is_lawful_traversable (derive_lawful_traversable nspace) [traversable_derive_handler' nspace, lawful_functor_derive_handler' nspace] nspace (λ n arg, mk_mapp n [arg,none]) @[derive_handler] meta def lawful_traversable_derive_handler : derive_handler := guard_class ``is_lawful_traversable lawful_traversable_derive_handler' end tactic.interactive
496f26b7a32b62e230b28004bb11492f1fc60928
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Server/AsyncList.lean
c45d696e0d3e9bf679c1f639333cdc850d15440a
[ "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
4,965
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Init.System.IO namespace IO universe u v /-- An async IO list is like a lazy list but instead of being *unevaluated* `Thunk`s, lazy tails are `Task`s *being evaluated asynchronously*. A tail can signal the end of computation (successful or due to a failure) with a terminating value of type `ε`. -/ inductive AsyncList (ε : Type u) (α : Type v) where | cons (hd : α) (tl : AsyncList ε α) | asyncTail (tl : Task $ Except ε $ AsyncList ε α) | nil namespace AsyncList instance : Inhabited (AsyncList ε α) := ⟨nil⟩ -- TODO(WN): tail-recursion without forcing sync? partial def append : AsyncList ε α → AsyncList ε α → AsyncList ε α | cons hd tl, s => cons hd (append tl s) | asyncTail ttl, s => asyncTail (ttl.map $ Except.map (append · s)) | nil, s => s instance : Append (AsyncList ε α) := ⟨append⟩ def ofList : List α → AsyncList ε α := List.foldr AsyncList.cons AsyncList.nil instance : Coe (List α) (AsyncList ε α) := ⟨ofList⟩ private def coeErr {β} [Coe Error ε] (t : Task $ Except Error $ Except ε β) : Task (Except ε β) := t.map $ fun | Except.ok v => v | Except.error (e : Error) => Except.error (e : ε) /-- Given a step computation `f` which takes the accumulator and either produces another value or stops with a terminating value, produces an async stream of its iterated applications. The initial value is *not* included. The computation can throw IO exceptions, so to handle this the terminating value type must include `IO.Error`. For cooperatively cancelling an ongoing computation, we recommend referencing a cancellation token in `f` and checking it when appropriate. -/ partial def unfoldAsync [Coe Error ε] (f : α → ExceptT ε IO α) (init : α) : IO (AsyncList ε α) := do let rec step (a : α) : ExceptT ε IO (AsyncList ε α) := do let aNext ← f a let tNext ← coeErr <$> asTask (step aNext) return cons aNext $ asyncTail tNext let tInit ← coeErr <$> asTask (step init) asyncTail tInit /-- The computed, synchronous list. If an async tail was present, returns also its terminating value. -/ partial def getAll : AsyncList ε α → List α × Option ε | cons hd tl => let ⟨l, e?⟩ := tl.getAll ⟨hd :: l, e?⟩ | nil => ⟨[], none⟩ | asyncTail tl => match tl.get with | Except.ok tl => tl.getAll | Except.error e => ⟨[], some e⟩ /-- Spawns a `Task` waiting on the prefix of elements for which `p` is true. -/ partial def waitAll [Coe Error ε] (p : α → Bool := fun _ => true) : AsyncList ε α → BaseIO (Task (List α × Option ε)) | cons hd tl => do if p hd then let t ← tl.waitAll p t.map fun ⟨l, e?⟩ => ⟨hd :: l, e?⟩ else return Task.pure ⟨[hd], none⟩ | nil => return Task.pure ⟨[], none⟩ | asyncTail tl => do let t : Task (Except IO.Error (List α × Option ε)) ← BaseIO.bindTask tl fun | Except.ok tl => Task.map Except.ok <$> tl.waitAll p | Except.error e => return Task.pure <| Except.ok ⟨[], some e⟩ t.map fun | Except.error e => ⟨[], some e⟩ | Except.ok v => v /-- Spawns a `Task` acting like `List.find?` but which will wait for tail evalution when necessary to traverse the list. If the tail terminates before a matching element is found, the task throws the terminating value. -/ partial def waitFind? (p : α → Bool) [Coe Error ε] : AsyncList ε α → BaseIO (Task $ Except ε $ Option α) | nil => return Task.pure <| Except.ok none | cons hd tl => do if p hd then return Task.pure <| Except.ok <| some hd else tl.waitFind? p | asyncTail tl => do let t ← BaseIO.bindTask tl fun | Except.ok tl => Task.map Except.ok <$> tl.waitFind? p | Except.error e => return Task.pure <| Except.ok <| Except.error e coeErr t /-- Extends the `finishedPrefix` as far as possible. If computation was ongoing and has finished, also returns the terminating value. -/ partial def updateFinishedPrefix : AsyncList ε α → BaseIO (AsyncList ε α × Option ε) | cons hd tl => do let ⟨tl, e?⟩ ← tl.updateFinishedPrefix pure ⟨cons hd tl, e?⟩ | nil => pure ⟨nil, none⟩ | l@(asyncTail tl) => do if (← hasFinished tl) then match tl.get with | Except.ok tl => tl.updateFinishedPrefix | Except.error e => pure ⟨nil, some e⟩ else pure ⟨l, none⟩ private partial def finishedPrefixAux : List α → AsyncList ε α → List α | acc, cons hd tl => finishedPrefixAux (hd :: acc) tl | acc, nil => acc | acc, asyncTail tl => acc /-- The longest already-computed prefix of the list. -/ def finishedPrefix : AsyncList ε α → List α := List.reverse ∘ (finishedPrefixAux []) end AsyncList end IO
4e9bc1ee5ac5a430575b35c2a088666c6c676b92
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/idempotents/karoubi_karoubi.lean
983eb2ac4b9e7539e9b198d9e1d056506390332a
[ "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,350
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import category_theory.idempotents.karoubi /-! # Idempotence of the Karoubi envelope In this file, we construct the equivalence of categories `karoubi_karoubi.equivalence C : karoubi C ≌ karoubi (karoubi C)` for any category `C`. -/ open category_theory.category open category_theory.idempotents.karoubi namespace category_theory namespace idempotents namespace karoubi_karoubi variables (C : Type*) [category C] /-- The canonical functor `karoubi (karoubi C) ⥤ karoubi C` -/ @[simps] def inverse : karoubi (karoubi C) ⥤ karoubi C := { obj := λ P, ⟨P.X.X, P.p.f, by simpa only [hom_ext] using P.idem⟩, map := λ P Q f, ⟨f.f.f, by simpa only [hom_ext] using f.comm⟩, } instance [preadditive C] : functor.additive (inverse C) := { } /-- The unit isomorphism of the equivalence -/ @[simps] def unit_iso : 𝟭 (karoubi C) ≅ to_karoubi (karoubi C) ⋙ inverse C := eq_to_iso begin apply functor.ext, { intros P Q f, ext, simp only [functor.id_map, inverse_map_f, to_karoubi_map_f, eq_to_hom_f, eq_to_hom_refl, comp_id, p_comp_assoc, functor.comp_map, comp], dsimp, simp only [id_eq, comp_p], }, { intro P, ext, { simpa only [eq_to_hom_refl, comp_id, id_comp], }, { refl, }, } end /-- The counit isomorphism of the equivalence -/ @[simps] def counit_iso : inverse C ⋙ to_karoubi (karoubi C) ≅ 𝟭 (karoubi (karoubi C)) := { hom := { app := λ P, { f := { f := P.p.1, comm := begin have h := P.idem, simp only [hom_ext, comp] at h, erw [← assoc, h, comp_p], end, }, comm := begin have h := P.idem, simp only [hom_ext, comp] at h ⊢, erw [h, h], end, }, naturality' := λ P Q f, by simpa only [hom_ext] using (p_comm f).symm, }, inv := { app := λ P, { f := { f := P.p.1, comm := begin have h := P.idem, simp only [hom_ext, comp] at h, erw [h, p_comp], end, }, comm := begin have h := P.idem, simp only [hom_ext, comp] at h ⊢, erw [h, h], end, }, naturality' := λ P Q f, by simpa [hom_ext] using (p_comm f).symm, }, hom_inv_id' := by { ext P, simpa only [hom_ext, id_eq] using P.idem, }, inv_hom_id' := by { ext P, simpa only [hom_ext, id_eq] using P.idem, }, } /-- The equivalence `karoubi C ≌ karoubi (karoubi C)` -/ @[simps] def equivalence : karoubi C ≌ karoubi (karoubi C) := { functor := to_karoubi (karoubi C), inverse := karoubi_karoubi.inverse C, unit_iso := karoubi_karoubi.unit_iso C, counit_iso := karoubi_karoubi.counit_iso C, functor_unit_iso_comp' := λ P, begin ext, simp only [eq_to_hom_f, eq_to_hom_refl, comp_id, counit_iso_hom_app_f_f, to_karoubi_obj_p, id_eq, assoc, comp, unit_iso_hom, eq_to_hom_app, eq_to_hom_map], erw [P.idem, P.idem], end, } instance equivalence.additive_functor [preadditive C] : functor.additive (equivalence C).functor := by { dsimp, apply_instance, } instance equivalence.additive_inverse [preadditive C] : functor.additive (equivalence C).inverse := by { dsimp, apply_instance, } end karoubi_karoubi end idempotents end category_theory
067c31a1795434fcf1a28acb8b00c7f0ed5a40be
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/tactic/linarith.lean
61e706c1fd8a7857677715a1476853b4b5d1e803
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
32,563
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis A tactic for discharging linear arithmetic goals using Fourier-Motzkin elimination. `linarith` is (in principle) complete for ℚ and ℝ. It is not complete for non-dense orders, i.e. ℤ. @TODO: investigate storing comparisons in a list instead of a set, for possible efficiency gains @TODO: delay proofs of denominator normalization and nat casting until after contradiction is found -/ import tactic.ring data.nat.gcd data.list.basic meta.rb_map 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))) open native namespace linarith section lemmas lemma int.coe_nat_bit0 (n : ℕ) : (↑(bit0 n : ℕ) : ℤ) = bit0 (↑n : ℤ) := by simp [bit0] lemma int.coe_nat_bit1 (n : ℕ) : (↑(bit1 n : ℕ) : ℤ) = bit1 (↑n : ℤ) := by simp [bit1, bit0] lemma int.coe_nat_bit0_mul (n : ℕ) (x : ℕ) : (↑(bit0 n * x) : ℤ) = (↑(bit0 n) : ℤ) * (↑x : ℤ) := by simp lemma int.coe_nat_bit1_mul (n : ℕ) (x : ℕ) : (↑(bit1 n * x) : ℤ) = (↑(bit1 n) : ℤ) * (↑x : ℤ) := by simp lemma int.coe_nat_one_mul (x : ℕ) : (↑(1 * x) : ℤ) = 1 * (↑x : ℤ) := by simp lemma int.coe_nat_zero_mul (x : ℕ) : (↑(0 * x) : ℤ) = 0 * (↑x : ℤ) := by simp lemma int.coe_nat_mul_bit0 (n : ℕ) (x : ℕ) : (↑(x * bit0 n) : ℤ) = (↑x : ℤ) * (↑(bit0 n) : ℤ) := by simp lemma int.coe_nat_mul_bit1 (n : ℕ) (x : ℕ) : (↑(x * bit1 n) : ℤ) = (↑x : ℤ) * (↑(bit1 n) : ℤ) := by simp lemma int.coe_nat_mul_one (x : ℕ) : (↑(x * 1) : ℤ) = (↑x : ℤ) * 1 := by simp lemma int.coe_nat_mul_zero (x : ℕ) : (↑(x * 0) : ℤ) = (↑x : ℤ) * 0 := by simp lemma nat_eq_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 = n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 = z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_eq_coe_nat_iff] lemma nat_le_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 ≤ n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 ≤ z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_le] lemma nat_lt_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 < n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 < z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_lt] lemma eq_of_eq_of_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b = 0) : a + b = 0 := by simp * lemma le_of_eq_of_le {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b ≤ 0) : a + b ≤ 0 := by simp * lemma lt_of_eq_of_lt {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b < 0) : a + b < 0 := by simp * lemma le_of_le_of_eq {α} [ordered_semiring α] {a b : α} (ha : a ≤ 0) (hb : b = 0) : a + b ≤ 0 := by simp * lemma lt_of_lt_of_eq {α} [ordered_semiring α] {a b : α} (ha : a < 0) (hb : b = 0) : a + b < 0 := by simp * lemma mul_neg {α} [ordered_ring α] {a b : α} (ha : a < 0) (hb : b > 0) : b * a < 0 := have (-b)*a > 0, from mul_pos_of_neg_of_neg (neg_neg_of_pos hb) ha, neg_of_neg_pos (by simpa) lemma mul_nonpos {α} [ordered_ring α] {a b : α} (ha : a ≤ 0) (hb : b > 0) : b * a ≤ 0 := have (-b)*a ≥ 0, from mul_nonneg_of_nonpos_of_nonpos (le_of_lt (neg_neg_of_pos hb)) ha, nonpos_of_neg_nonneg (by simp at this; exact this) lemma mul_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b > 0) : b * a = 0 := by simp * lemma eq_of_not_lt_of_not_gt {α} [linear_order α] (a b : α) (h1 : ¬ a < b) (h2 : ¬ b < a) : a = b := le_antisymm (le_of_not_gt h2) (le_of_not_gt h1) lemma add_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 + e2) = t1 + t2 := by simp [left_distrib, *] lemma sub_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 - e2) = t1 - t2 := by simp [left_distrib, *] lemma neg_subst {α} [ring α] {n e t : α} (h1 : n * e = t) : n * (-e) = -t := by simp * private meta def apnn : tactic unit := `[norm_num] lemma mul_subst {α} [comm_ring α] {n1 n2 k e1 e2 t1 t2 : α} (h1 : n1 * e1 = t1) (h2 : n2 * e2 = t2) (h3 : n1*n2 = k . apnn) : k * (e1 * e2) = t1 * t2 := have h3 : n1 * n2 = k, from h3, by rw [←h3, mul_comm n1, mul_assoc n2, ←mul_assoc n1, h1, ←mul_assoc n2, mul_comm n2, mul_assoc, h2] -- OUCH lemma div_subst {α} [field α] {n1 n2 k e1 e2 t1 : α} (h1 : n1 * e1 = t1) (h2 : n2 / e2 = 1) (h3 : n1*n2 = k) : k * (e1 / e2) = t1 := by rw [←h3, mul_assoc, mul_div_comm, h2, ←mul_assoc, h1, mul_comm, one_mul] end lemmas section datatypes @[derive decidable_eq] inductive ineq | eq | le | lt open ineq def ineq.max : ineq → ineq → ineq | eq a := a | le a := a | lt a := lt def ineq.is_lt : ineq → ineq → bool | eq le := tt | eq lt := tt | le lt := tt | _ _ := ff def ineq.to_string : ineq → string | eq := "=" | le := "≤" | lt := "<" instance : has_to_string ineq := ⟨ineq.to_string⟩ /-- The main datatype for FM elimination. Variables are represented by natural numbers, each of which has an integer coefficient. Index 0 is reserved for constants, i.e. `coeffs.find 0` is the coefficient of 1. The represented term is coeffs.keys.sum (λ i, coeffs.find i * Var[i]). str determines the direction of the comparison -- is it < 0, ≤ 0, or = 0? -/ meta structure comp := (str : ineq) (coeffs : rb_map ℕ int) meta instance : inhabited comp := ⟨⟨ineq.eq, mk_rb_map⟩⟩ meta inductive comp_source | assump : ℕ → comp_source | add : comp_source → comp_source → comp_source | scale : ℕ → comp_source → comp_source meta def comp_source.flatten : comp_source → rb_map ℕ ℕ | (comp_source.assump n) := mk_rb_map.insert n 1 | (comp_source.add c1 c2) := (comp_source.flatten c1).add (comp_source.flatten c2) | (comp_source.scale n c) := (comp_source.flatten c).map (λ v, v * n) meta def comp_source.to_string : comp_source → string | (comp_source.assump e) := to_string e | (comp_source.add c1 c2) := comp_source.to_string c1 ++ " + " ++ comp_source.to_string c2 | (comp_source.scale n c) := to_string n ++ " * " ++ comp_source.to_string c meta instance comp_source.has_to_format : has_to_format comp_source := ⟨λ a, comp_source.to_string a⟩ meta structure pcomp := (c : comp) (src : comp_source) meta def map_lt (m1 m2 : rb_map ℕ int) : bool := list.lex (prod.lex (<) (<)) m1.to_list m2.to_list -- make more efficient meta def comp.lt (c1 c2 : comp) : bool := (c1.str.is_lt c2.str) || (c1.str = c2.str) && map_lt c1.coeffs c2.coeffs meta instance comp.has_lt : has_lt comp := ⟨λ a b, comp.lt a b⟩ meta instance pcomp.has_lt : has_lt pcomp := ⟨λ p1 p2, p1.c < p2.c⟩ meta instance pcomp.has_lt_dec : decidable_rel ((<) : pcomp → pcomp → Prop) := by apply_instance meta def comp.coeff_of (c : comp) (a : ℕ) : ℤ := c.coeffs.zfind a meta def comp.scale (c : comp) (n : ℕ) : comp := { c with coeffs := c.coeffs.map ((*) (n : ℤ)) } meta def comp.add (c1 c2 : comp) : comp := ⟨c1.str.max c2.str, c1.coeffs.add c2.coeffs⟩ meta def pcomp.scale (c : pcomp) (n : ℕ) : pcomp := ⟨c.c.scale n, comp_source.scale n c.src⟩ meta def pcomp.add (c1 c2 : pcomp) : pcomp := ⟨c1.c.add c2.c, comp_source.add c1.src c2.src⟩ meta instance pcomp.to_format : has_to_format pcomp := ⟨λ p, to_fmt p.c.coeffs ++ to_string p.c.str ++ "0"⟩ meta instance comp.to_format : has_to_format comp := ⟨λ p, to_fmt p.coeffs⟩ end datatypes section fm_elim /-- If c1 and c2 both contain variable a with opposite coefficients, produces v1, v2, and c such that a has been cancelled in c := v1*c1 + v2*c2 -/ meta def elim_var (c1 c2 : comp) (a : ℕ) : option (ℕ × ℕ × comp) := let v1 := c1.coeff_of a, v2 := c2.coeff_of a in if v1 * v2 < 0 then let vlcm := nat.lcm v1.nat_abs v2.nat_abs, v1' := vlcm / v1.nat_abs, v2' := vlcm / v2.nat_abs in some ⟨v1', v2', comp.add (c1.scale v1') (c2.scale v2')⟩ else none meta def pelim_var (p1 p2 : pcomp) (a : ℕ) : option pcomp := do (n1, n2, c) ← elim_var p1.c p2.c a, return ⟨c, comp_source.add (p1.src.scale n1) (p2.src.scale n2)⟩ meta def comp.is_contr (c : comp) : bool := c.coeffs.empty ∧ c.str = ineq.lt meta def pcomp.is_contr (p : pcomp) : bool := p.c.is_contr meta def elim_with_set (a : ℕ) (p : pcomp) (comps : rb_set pcomp) : rb_set pcomp := if ¬ p.c.coeffs.contains a then mk_rb_set.insert p else comps.fold mk_rb_set $ λ pc s, match pelim_var p pc a with | some pc := s.insert pc | none := s end /-- The state for the elimination monad. vars: the set of variables present in comps comps: a set of comparisons inputs: a set of pairs of exprs (t, pf), where t is a term and pf is a proof that t {<, ≤, =} 0, indexed by ℕ. has_false: stores a pcomp of 0 < 0 if one has been found TODO: is it more efficient to store comps as a list, to avoid comparisons? -/ meta structure linarith_structure := (vars : rb_set ℕ) (comps : rb_set pcomp) @[reducible] meta def linarith_monad := state_t linarith_structure (except_t pcomp id) meta instance : monad linarith_monad := state_t.monad meta instance : monad_except pcomp linarith_monad := state_t.monad_except pcomp meta def get_vars : linarith_monad (rb_set ℕ) := linarith_structure.vars <$> get meta def get_var_list : linarith_monad (list ℕ) := rb_set.to_list <$> get_vars meta def get_comps : linarith_monad (rb_set pcomp) := linarith_structure.comps <$> get meta def validate : linarith_monad unit := do ⟨_, comps⟩ ← get, match comps.to_list.find (λ p : pcomp, p.is_contr) with | none := return () | some c := throw c end meta def update (vars : rb_set ℕ) (comps : rb_set pcomp) : linarith_monad unit := state_t.put ⟨vars, comps⟩ >> validate meta def monad.elim_var (a : ℕ) : linarith_monad unit := do vs ← get_vars, when (vs.contains a) $ do comps ← get_comps, let cs' := comps.fold mk_rb_set (λ p s, s.union (elim_with_set a p comps)), update (vs.erase a) cs' meta def elim_all_vars : linarith_monad unit := get_var_list >>= list.mmap' monad.elim_var end fm_elim section parse open ineq tactic meta def map_of_expr_mul_aux (c1 c2 : rb_map ℕ ℤ) : option (rb_map ℕ ℤ) := match c1.keys, c2.keys with | [0], _ := some $ c2.scale (c1.zfind 0) | _, [0] := some $ c1.scale (c2.zfind 0) | [], _ := some mk_rb_map | _, [] := some mk_rb_map | _, _ := none end /-- Turns an expression into a map from ℕ to ℤ, for use in a comp object. The expr_map ℕ argument identifies which expressions have already been assigned numbers. Returns a new map. -/ meta def map_of_expr : expr_map ℕ → expr → option (expr_map ℕ × rb_map ℕ ℤ) | m e@`(%%e1 * %%e2) := (do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, mp ← map_of_expr_mul_aux comp1 comp2, return (m', mp)) <|> (match m.find e with | some k := return (m, mk_rb_map.insert k 1) | none := let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1) end) | m `(%%e1 + %%e2) := do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, return (m', comp1.add comp2) | m `(%%e1 - %%e2) := do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, return (m', comp1.add (comp2.scale (-1))) | m `(-%%e) := do (m', comp) ← map_of_expr m e, return (m', comp.scale (-1)) | m e := match e.to_int, m.find e with | some 0, _ := return ⟨m, mk_rb_map⟩ | some z, _ := return ⟨m, mk_rb_map.insert 0 z⟩ | none, some k := return (m, mk_rb_map.insert k 1) | none, none := let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1) end meta def parse_into_comp_and_expr : expr → option (ineq × expr) | `(%%e < 0) := (ineq.lt, e) | `(%%e ≤ 0) := (ineq.le, e) | `(%%e = 0) := (ineq.eq, e) | _ := none meta def to_comp (e : expr) (m : expr_map ℕ) : option (comp × expr_map ℕ) := do (iq, e) ← parse_into_comp_and_expr e, (m', comp') ← map_of_expr m e, return ⟨⟨iq, comp'⟩, m'⟩ meta def to_comp_fold : expr_map ℕ → list expr → (list (option comp) × expr_map ℕ) | m [] := ([], m) | m (h::t) := match to_comp h m with | some (c, m') := let (l, mp) := to_comp_fold m' t in (c::l, mp) | none := let (l, mp) := to_comp_fold m t in (none::l, mp) end /-- Takes a list of proofs of props of the form t {<, ≤, =} 0, and creates a linarith_structure. -/ meta def mk_linarith_structure (l : list expr) : tactic (linarith_structure × rb_map ℕ (expr × expr)) := do pftps ← l.mmap infer_type, let (l', map) := to_comp_fold mk_rb_map pftps, let lz := list.enum $ ((l.zip pftps).zip l').filter_map (λ ⟨a, b⟩, prod.mk a <$> b), let prmap := rb_map.of_list $ lz.map (λ ⟨n, x⟩, (n, x.1)), let vars : rb_set ℕ := rb_map.set_of_list $ list.range map.size.succ, let pc : rb_set pcomp := rb_map.set_of_list $ lz.map (λ ⟨n, x⟩, ⟨x.2, comp_source.assump n⟩), return (⟨vars, pc⟩, prmap) meta def linarith_monad.run {α} (tac : linarith_monad α) (l : list expr) : tactic ((pcomp ⊕ α) × rb_map ℕ (expr × expr)) := do (struct, inputs) ← mk_linarith_structure l, match (state_t.run (validate >> tac) struct).run with | (except.ok (a, _)) := return (sum.inr a, inputs) | (except.error contr) := return (sum.inl contr, inputs) end end parse section prove open ineq tactic meta def get_rel_sides : expr → tactic (expr × expr) | `(%%a < %%b) := return (a, b) | `(%%a ≤ %%b) := return (a, b) | `(%%a = %%b) := return (a, b) | `(%%a ≥ %%b) := return (a, b) | `(%%a > %%b) := return (a, b) | _ := failed meta def mul_expr (n : ℕ) (e : expr) : pexpr := if n = 1 then ``(%%e) else ``(%%(nat.to_pexpr n) * %%e) meta def add_exprs_aux : pexpr → list pexpr → pexpr | p [] := p | p [a] := ``(%%p + %%a) | p (h::t) := add_exprs_aux ``(%%p + %%h) t meta def add_exprs : list pexpr → pexpr | [] := ``(0) | (h::t) := add_exprs_aux h t meta def find_contr (m : rb_set pcomp) : option pcomp := m.keys.find (λ p, p.c.is_contr) meta def ineq_const_mul_nm : ineq → name | lt := ``mul_neg | le := ``mul_nonpos | eq := ``mul_eq meta def ineq_const_nm : ineq → ineq → (name × ineq) | eq eq := (``eq_of_eq_of_eq, eq) | eq le := (``le_of_eq_of_le, le) | eq lt := (``lt_of_eq_of_lt, lt) | le eq := (``le_of_le_of_eq, le) | le le := (`add_nonpos, le) | le lt := (`add_neg_of_nonpos_of_neg, lt) | lt eq := (``lt_of_lt_of_eq, lt) | lt le := (`add_neg_of_neg_of_nonpos, lt) | lt lt := (`add_neg, lt) meta def mk_single_comp_zero_pf (c : ℕ) (h : expr) : tactic (ineq × expr) := do tp ← infer_type h, some (iq, e) ← return $ parse_into_comp_and_expr tp, if c = 0 then do e' ← mk_app ``zero_mul [e], return (eq, e') else if c = 1 then return (iq, h) else do nm ← resolve_name (ineq_const_mul_nm iq), tp ← (prod.snd <$> (infer_type h >>= get_rel_sides)) >>= infer_type, cpos ← to_expr ``((%%c.to_pexpr : %%tp) > 0), (_, ex) ← solve_aux cpos `[norm_num, done], -- e' ← mk_app (ineq_const_mul_nm iq) [h, ex], -- this takes many seconds longer in some examples! why? e' ← to_expr ``(%%nm %%h %%ex) ff, return (iq, e') meta def mk_lt_zero_pf_aux (c : ineq) (pf npf : expr) (coeff : ℕ) : tactic (ineq × expr) := do (iq, h') ← mk_single_comp_zero_pf coeff npf, let (nm, niq) := ineq_const_nm c iq, n ← resolve_name nm, e' ← to_expr ``(%%n %%pf %%h'), return (niq, e') /-- Takes a list of coefficients [c] and list of expressions, of equal length. Each expression is a proof of a prop of the form t {<, ≤, =} 0. Produces a proof that the sum of (c*t) {<, ≤, =} 0, where the comp is as strong as possible. -/ meta def mk_lt_zero_pf : list ℕ → list expr → tactic expr | _ [] := fail "no linear hypotheses found" | [c] [h] := prod.snd <$> mk_single_comp_zero_pf c h | (c::ct) (h::t) := do (iq, h') ← mk_single_comp_zero_pf c h, prod.snd <$> (ct.zip t).mfoldl (λ pr ce, mk_lt_zero_pf_aux pr.1 pr.2 ce.2 ce.1) (iq, h') | _ _ := fail "not enough args to mk_lt_zero_pf" meta def term_of_ineq_prf (prf : expr) : tactic expr := do (lhs, _) ← infer_type prf >>= get_rel_sides, return lhs meta structure linarith_config := (discharger : tactic unit := `[ring]) (restrict_type : option Type := none) (restrict_type_reflect : reflected restrict_type . apply_instance) (exfalso : bool := tt) meta def ineq_pf_tp (pf : expr) : tactic expr := do (_, z) ← infer_type pf >>= get_rel_sides, infer_type z meta def mk_neg_one_lt_zero_pf (tp : expr) : tactic expr := to_expr ``((neg_neg_of_pos zero_lt_one : -1 < (0 : %%tp))) /-- Assumes e is a proof that t = 0. Creates a proof that -t = 0. -/ meta def mk_neg_eq_zero_pf (e : expr) : tactic expr := to_expr ``(neg_eq_zero.mpr %%e) meta def add_neg_eq_pfs : list expr → tactic (list expr) | [] := return [] | (h::t) := do some (iq, tp) ← parse_into_comp_and_expr <$> infer_type h, match iq with | ineq.eq := do nep ← mk_neg_eq_zero_pf h, tl ← add_neg_eq_pfs t, return $ h::nep::tl | _ := list.cons h <$> add_neg_eq_pfs t end /-- Takes a list of proofs of propositions of the form t {<, ≤, =} 0, and tries to prove the goal `false`. -/ meta def prove_false_by_linarith1 (cfg : linarith_config) : list expr → tactic unit | [] := fail "no args to linarith" | l@(h::t) := do l' ← add_neg_eq_pfs l, hz ← ineq_pf_tp h >>= mk_neg_one_lt_zero_pf, (sum.inl contr, inputs) ← elim_all_vars.run (hz::l') | fail "linarith failed to find a contradiction", let coeffs := inputs.keys.map (λ k, (contr.src.flatten.ifind k)), let pfs : list expr := inputs.keys.map (λ k, (inputs.ifind k).1), let zip := (coeffs.zip pfs).filter (λ pr, pr.1 ≠ 0), let (coeffs, pfs) := zip.unzip, mls ← zip.mmap (λ pr, do e ← term_of_ineq_prf pr.2, return (mul_expr pr.1 e)), sm ← to_expr $ add_exprs mls, tgt ← to_expr ``(%%sm = 0), (a, b) ← solve_aux tgt (cfg.discharger >> done), pf ← mk_lt_zero_pf coeffs pfs, pftp ← infer_type pf, (_, nep, _) ← rewrite_core b pftp, pf' ← mk_eq_mp nep pf, mk_app `lt_irrefl [pf'] >>= exact end prove section normalize open tactic set_option eqn_compiler.max_steps 50000 meta def rem_neg (prf : expr) : expr → tactic expr | `(_ ≤ _) := to_expr ``(lt_of_not_ge %%prf) | `(_ < _) := to_expr ``(le_of_not_gt %%prf) | `(_ > _) := to_expr ``(le_of_not_gt %%prf) | `(_ ≥ _) := to_expr ``(lt_of_not_ge %%prf) | e := failed meta def rearr_comp : expr → expr → tactic expr | prf `(%%a ≤ 0) := return prf | prf `(%%a < 0) := return prf | prf `(%%a = 0) := return prf | prf `(%%a ≥ 0) := to_expr ``(neg_nonpos.mpr %%prf) | prf `(%%a > 0) := to_expr ``(neg_neg_of_pos %%prf) | prf `(0 ≥ %%a) := to_expr ``(show %%a ≤ 0, from %%prf) | prf `(0 > %%a) := to_expr ``(show %%a < 0, from %%prf) | prf `(0 = %%a) := to_expr ``(eq.symm %%prf) | prf `(0 ≤ %%a) := to_expr ``(neg_nonpos.mpr %%prf) | prf `(0 < %%a) := to_expr ``(neg_neg_of_pos %%prf) | prf `(%%a ≤ %%b) := to_expr ``(sub_nonpos.mpr %%prf) | prf `(%%a < %%b) := to_expr ``(sub_neg_of_lt %%prf) | prf `(%%a = %%b) := to_expr ``(sub_eq_zero.mpr %%prf) | prf `(%%a > %%b) := to_expr ``(sub_neg_of_lt %%prf) | prf `(%%a ≥ %%b) := to_expr ``(sub_nonpos.mpr %%prf) | prf `(¬ %%t) := do nprf ← rem_neg prf t, tp ← infer_type nprf, rearr_comp nprf tp | prf _ := fail "couldn't rearrange comp" meta def is_numeric : expr → option ℚ | `(%%e1 + %%e2) := (+) <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 - %%e2) := has_sub.sub <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 * %%e2) := (*) <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 / %%e2) := (/) <$> is_numeric e1 <*> is_numeric e2 | `(-%%e) := rat.neg <$> is_numeric e | e := e.to_rat inductive {u} tree (α : Type u) : Type u | nil {} : tree | node : α → tree → tree → tree def tree.repr {α} [has_repr α] : tree α → string | tree.nil := "nil" | (tree.node a t1 t2) := "tree.node " ++ repr a ++ " (" ++ tree.repr t1 ++ ") (" ++ tree.repr t2 ++ ")" instance {α} [has_repr α] : has_repr (tree α) := ⟨tree.repr⟩ meta def find_cancel_factor : expr → ℕ × tree ℕ | `(%%e1 + %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in (lcm, tree.node lcm t1 t2) | `(%%e1 - %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in (lcm, tree.node lcm t1 t2) | `(%%e1 * %%e2) := match is_numeric e1, is_numeric e2 with | none, none := (1, tree.node 1 tree.nil tree.nil) | _, _ := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, pd := v1*v2 in (pd, tree.node pd t1 t2) end | `(%%e1 / %%e2) := match is_numeric e2 with | some q := let (v1, t1) := find_cancel_factor e1, n := v1.lcm q.num.nat_abs in (n, tree.node n t1 (tree.node q.num.nat_abs tree.nil tree.nil)) | none := (1, tree.node 1 tree.nil tree.nil) end | `(-%%e) := find_cancel_factor e | _ := (1, tree.node 1 tree.nil tree.nil) open tree meta def mk_prod_prf : ℕ → tree ℕ → expr → tactic expr | v (node _ lhs rhs) `(%%e1 + %%e2) := do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``add_subst [v1, v2] | v (node _ lhs rhs) `(%%e1 - %%e2) := do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``sub_subst [v1, v2] | v (node n lhs@(node ln _ _) rhs) `(%%e1 * %%e2) := do tp ← infer_type e1, v1 ← mk_prod_prf ln lhs e1, v2 ← mk_prod_prf (v/ln) rhs e2, ln' ← tp.of_nat ln, vln' ← tp.of_nat (v/ln), v' ← tp.of_nat v, ntp ← to_expr ``(%%ln' * %%vln' = %%v'), (_, npf) ← solve_aux ntp `[norm_num, done], mk_app ``mul_subst [v1, v2, npf] | v (node n lhs rhs@(node rn _ _)) `(%%e1 / %%e2) := do tp ← infer_type e1, v1 ← mk_prod_prf (v/rn) lhs e1, rn' ← tp.of_nat rn, vrn' ← tp.of_nat (v/rn), n' ← tp.of_nat n, v' ← tp.of_nat v, ntp ← to_expr ``(%%rn' / %%e2 = 1), (_, npf) ← solve_aux ntp `[norm_num, done], ntp2 ← to_expr ``(%%vrn' * %%n' = %%v'), (_, npf2) ← solve_aux ntp2 `[norm_num, done], mk_app ``div_subst [v1, npf, npf2] | v t `(-%%e) := do v' ← mk_prod_prf v t e, mk_app ``neg_subst [v'] | v _ e := do tp ← infer_type e, v' ← tp.of_nat v, e' ← to_expr ``(%%v' * %%e), mk_app `eq.refl [e'] /-- e is a term with rational division. produces a natural number n and a proof that n*e = e', where e' has no division. -/ meta def kill_factors (e : expr) : tactic (ℕ × expr) := let (n, t) := find_cancel_factor e in do e' ← mk_prod_prf n t e, return (n, e') open expr meta def expr_contains (n : name) : expr → bool | (const nm _) := nm = n | (lam _ _ _ bd) := expr_contains bd | (pi _ _ _ bd) := expr_contains bd | (app e1 e2) := expr_contains e1 || expr_contains e2 | _ := ff lemma sub_into_lt {α} [ordered_semiring α] {a b : α} (he : a = b) (hl : a ≤ 0) : b ≤ 0 := by rwa he at hl meta def norm_hyp_aux (h' lhs : expr) : tactic expr := do (v, lhs') ← kill_factors lhs, if v = 1 then return h' else do (ih, h'') ← mk_single_comp_zero_pf v h', (_, nep, _) ← infer_type h'' >>= rewrite_core lhs', mk_eq_mp nep h'' meta def norm_hyp (h : expr) : tactic expr := do htp ← infer_type h, h' ← rearr_comp h htp, some (c, lhs) ← parse_into_comp_and_expr <$> infer_type h', if expr_contains `has_div.div lhs then norm_hyp_aux h' lhs else return h' meta def get_contr_lemma_name : expr → option name | `(%%a < %%b) := return `lt_of_not_ge | `(%%a ≤ %%b) := return `le_of_not_gt | `(%%a = %%b) := return ``eq_of_not_lt_of_not_gt | `(%%a ≥ %%b) := return `le_of_not_gt | `(%%a > %%b) := return `lt_of_not_ge | `(¬ %%a < %%b) := return `not.intro | `(¬ %%a ≤ %%b) := return `not.intro | `(¬ %%a = %%b) := return `not.intro | `(¬ %%a ≥ %%b) := return `not.intro | `(¬ %%a > %%b) := return `not.intro | _ := none -- assumes the input t is of type ℕ. Produces t' of type ℤ such that ↑t = t' and a proof of equality meta def cast_expr (e : expr) : tactic (expr × expr) := do s ← [`int.coe_nat_add, `int.coe_nat_zero, `int.coe_nat_one, ``int.coe_nat_bit0_mul, ``int.coe_nat_bit1_mul, ``int.coe_nat_zero_mul, ``int.coe_nat_one_mul, ``int.coe_nat_mul_bit0, ``int.coe_nat_mul_bit1, ``int.coe_nat_mul_zero, ``int.coe_nat_mul_one, ``int.coe_nat_bit0, ``int.coe_nat_bit1].mfoldl simp_lemmas.add_simp simp_lemmas.mk, ce ← to_expr ``(↑%%e : ℤ), simplify s [] ce {fail_if_unchanged := ff} meta def is_nat_int_coe : expr → option expr | `((↑(%%n : ℕ) : ℤ)) := some n | _ := none meta def mk_coe_nat_nonneg_prf (e : expr) : tactic expr := mk_app `int.coe_nat_nonneg [e] meta def get_nat_comps : expr → list expr | `(%%a + %%b) := (get_nat_comps a).append (get_nat_comps b) | `(%%a * %%b) := (get_nat_comps a).append (get_nat_comps b) | e := match is_nat_int_coe e with | some e' := [e'] | none := [] end meta def mk_coe_nat_nonneg_prfs (e : expr) : tactic (list expr) := (get_nat_comps e).mmap mk_coe_nat_nonneg_prf meta def mk_cast_eq_and_nonneg_prfs (pf a b : expr) (ln : name) : tactic (list expr) := do (a', prfa) ← cast_expr a, (b', prfb) ← cast_expr b, la ← mk_coe_nat_nonneg_prfs a', lb ← mk_coe_nat_nonneg_prfs b', pf' ← mk_app ln [pf, prfa, prfb], return $ pf'::(la.append lb) meta def mk_int_pfs_of_nat_pf (pf : expr) : tactic (list expr) := do tp ← infer_type pf, match tp with | `(%%a = %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_eq_subst | `(%%a ≤ %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_le_subst | `(%%a < %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_lt_subst | `(%%a ≥ %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_le_subst | `(%%a > %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_lt_subst | `(¬ %%a ≤ %%b) := do pf' ← mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_lt_subst | `(¬ %%a < %%b) := do pf' ← mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_le_subst | `(¬ %%a ≥ %%b) := do pf' ← mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_lt_subst | `(¬ %%a > %%b) := do pf' ← mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_le_subst | _ := fail "mk_int_pfs_of_nat_pf failed: proof is not an inequality" end meta def mk_non_strict_int_pf_of_strict_int_pf (pf : expr) : tactic expr := do tp ← infer_type pf, match tp with | `(%%a < %%b) := to_expr ``(@cast (%%a < %%b) (%%a + 1 ≤ %%b) (by refl) %%pf) | `(%%a > %%b) := to_expr ``(@cast (%%a > %%b) (%%a ≥ %%b + 1) (by refl) %%pf) | `(¬ %%a ≤ %%b) := to_expr ``(@cast (%%a > %%b) (%%a ≥ %%b + 1) (by refl) (lt_of_not_ge %%pf)) | `(¬ %%a ≥ %%b) := to_expr ``(@cast (%%a < %%b) (%%a + 1 ≤ %%b) (by refl) (lt_of_not_ge %%pf)) | _ := fail "mk_non_strict_int_pf_of_strict_int_pf failed: proof is not an inequality" end meta def guard_is_nat_prop : expr → tactic unit | `(%%a = _) := infer_type a >>= unify `(ℕ) | `(%%a ≤ _) := infer_type a >>= unify `(ℕ) | `(%%a < _) := infer_type a >>= unify `(ℕ) | `(%%a ≥ _) := infer_type a >>= unify `(ℕ) | `(%%a > _) := infer_type a >>= unify `(ℕ) | `(¬ %%p) := guard_is_nat_prop p | _ := failed meta def guard_is_strict_int_prop : expr → tactic unit | `(%%a < _) := infer_type a >>= unify `(ℤ) | `(%%a > _) := infer_type a >>= unify `(ℤ) | `(¬ %%a ≤ _) := infer_type a >>= unify `(ℤ) | `(¬ %%a ≥ _) := infer_type a >>= unify `(ℤ) | _ := failed meta def replace_nat_pfs : list expr → tactic (list expr) | [] := return [] | (h::t) := (do infer_type h >>= guard_is_nat_prop, ls ← mk_int_pfs_of_nat_pf h, list.append ls <$> replace_nat_pfs t) <|> list.cons h <$> replace_nat_pfs t meta def replace_strict_int_pfs : list expr → tactic (list expr) | [] := return [] | (h::t) := (do infer_type h >>= guard_is_strict_int_prop, l ← mk_non_strict_int_pf_of_strict_int_pf h, list.cons l <$> replace_strict_int_pfs t) <|> list.cons h <$> replace_strict_int_pfs t meta def partition_by_type_aux : rb_lmap expr expr → list expr → tactic (rb_lmap expr expr) | m [] := return m | m (h::t) := do tp ← ineq_pf_tp h, partition_by_type_aux (m.insert tp h) t meta def partition_by_type (l : list expr) : tactic (rb_lmap expr expr) := partition_by_type_aux mk_rb_map l private meta def try_linarith_on_lists (cfg : linarith_config) (ls : list (list expr)) : tactic unit := (first $ ls.map $ prove_false_by_linarith1 cfg) <|> fail "linarith failed" /-- Takes a list of proofs of propositions. Filters out the proofs of linear (in)equalities, and tries to use them to prove `false`. If pref_type is given, starts by working over this type -/ meta def prove_false_by_linarith (cfg : linarith_config) (pref_type : option expr) (l : list expr) : tactic unit := do l' ← replace_nat_pfs l, l'' ← replace_strict_int_pfs l', ls ← list.reduce_option <$> l''.mmap (λ h, (do s ← norm_hyp h, return (some s)) <|> return none) >>= partition_by_type, pref_type ← (unify pref_type.iget `(ℕ) >> return (some `(ℤ) : option expr)) <|> return pref_type, match cfg.restrict_type, ls.values, pref_type with | some rtp, _, _ := do m ← mk_mvar, unify `(some %%m : option Type) cfg.restrict_type_reflect, m ← instantiate_mvars m, prove_false_by_linarith1 cfg (ls.ifind m) | none, [ls'], _ := prove_false_by_linarith1 cfg ls' | none, ls', none := try_linarith_on_lists cfg ls' | none, _, (some t) := prove_false_by_linarith1 cfg (ls.ifind t) <|> try_linarith_on_lists cfg (ls.erase t).values end end normalize end linarith section open tactic linarith open lean lean.parser interactive tactic interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many meta def linarith.interactive_aux (cfg : linarith_config) : option expr → parse ident* → (parse (tk "using" *> pexpr_list)?) → tactic unit | pt l (some pe) := pe.mmap (λ p, i_to_expr p >>= note_anon) >> linarith.interactive_aux pt l none | pt [] none := do t ← target, if t = `(false) then local_context >>= prove_false_by_linarith cfg pt else match get_contr_lemma_name t with | some nm := seq (applyc nm) (do t ← intro1 >>= ineq_pf_tp, linarith.interactive_aux (some t) [] none) | none := if cfg.exfalso then exfalso >> linarith.interactive_aux pt [] none else fail "linarith failed: target type is not an inequality." end | pt ls none := (ls.mmap get_local) >>= prove_false_by_linarith cfg pt /-- Tries to prove a goal of `false` by linear arithmetic on hypotheses. If the goal is a linear (in)equality, tries to prove it by contradiction. If the goal is not `false` or an inequality, applies `exfalso` and tries linarith on the hypotheses. `linarith` will use all relevant hypotheses in the local context. `linarith h1 h2 h3` will only use hypotheses h1, h2, h3. `linarith using [t1, t2, t3]` will add proof terms t1, t2, t3 to the local context. Config options: `linarith {exfalso := ff}` will fail on a goal that is neither an inequality nor `false` `linarith {restrict_type := T}` will run only on hypotheses that are inequalities over `T` `linarith {discharger := tac}` will use `tac` instead of `ring` for normalization. Options: `ring2`, `ring SOP`, `simp` -/ meta def tactic.interactive.linarith (ids : parse (many ident)) (using_hyps : parse (tk "using" *> pexpr_list)?) (cfg : linarith_config := {}) : tactic unit := linarith.interactive_aux cfg none ids using_hyps end
95e29d0be07742962e61cf746cc857c91e78446a
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/algebra/group_power/basic.lean
df7acba22a56b19dfb1122fd3c88f853359e9914
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
26,397
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import algebra.ordered_ring import tactic.monotonicity.basic import deprecated.group /-! # Power operations on monoids and groups The power operation on monoids and groups. We separate this from group, because it depends on `ℕ`, which in turn depends on other parts of algebra. This module contains the definitions of `monoid.pow` and `group.pow` and their additive counterparts `nsmul` and `gsmul`, along with a few lemmas. Further lemmas can be found in `algebra.group_power.lemmas`. ## Notation The class `has_pow α β` provides the notation `a^b` for powers. We define instances of `has_pow M ℕ`, for monoids `M`, and `has_pow G ℤ` for groups `G`. We also define infix operators `•ℕ` and `•ℤ` for scalar multiplication by a natural and an integer numbers, respectively. ## Implementation details We adopt the convention that `0^0 = 1`. This module provides the instance `has_pow ℕ ℕ` (via `monoid.has_pow`) and is imported by `data.nat.basic`, so it has to live low in the import hierarchy. Not all of its imports are needed yet; the intent is to move more lemmas here from `.lemmas` so that they are available in `data.nat.basic`, and the imports will be required then. -/ universes u v w x y z u₁ u₂ variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z} {R : Type u₁} {S : Type u₂} /-- The power operation in a monoid. `a^n = a*a*...*a` n times. -/ def monoid.pow [has_mul M] [has_one M] (a : M) : ℕ → M | 0 := 1 | (n+1) := a * monoid.pow n /-- The scalar multiplication in an additive monoid. `n •ℕ a = a+a+...+a` n times. -/ def nsmul [has_add A] [has_zero A] (n : ℕ) (a : A) : A := @monoid.pow (multiplicative A) _ _ a n infix ` •ℕ `:70 := nsmul instance monoid.has_pow [monoid M] : has_pow M ℕ := ⟨monoid.pow⟩ @[simp] lemma monoid.pow_eq_has_pow [monoid M] (a : M) (n : ℕ) : monoid.pow a n = a^n := rfl /-! ### Commutativity First we prove some facts about `semiconj_by` and `commute`. They do not require any theory about `pow` and/or `nsmul` and will be useful later in this file. -/ namespace semiconj_by variables [monoid M] @[simp] lemma pow_right {a x y : M} (h : semiconj_by a x y) (n : ℕ) : semiconj_by a (x^n) (y^n) := nat.rec_on n (one_right a) $ λ n ihn, h.mul_right ihn end semiconj_by namespace commute variables [monoid M] {a b : M} @[simp] theorem pow_right (h : commute a b) (n : ℕ) : commute a (b ^ n) := h.pow_right n @[simp] theorem pow_left (h : commute a b) (n : ℕ) : commute (a ^ n) b := (h.symm.pow_right n).symm @[simp] theorem pow_pow (h : commute a b) (m n : ℕ) : commute (a ^ m) (b ^ n) := (h.pow_left m).pow_right n @[simp] theorem self_pow (a : M) (n : ℕ) : commute a (a ^ n) := (commute.refl a).pow_right n @[simp] theorem pow_self (a : M) (n : ℕ) : commute (a ^ n) a := (commute.refl a).pow_left n @[simp] theorem pow_pow_self (a : M) (m n : ℕ) : commute (a ^ m) (a ^ n) := (commute.refl a).pow_pow m n end commute section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp] theorem pow_zero (a : M) : a^0 = 1 := rfl @[simp] theorem zero_nsmul (a : A) : 0 •ℕ a = 0 := rfl theorem pow_succ (a : M) (n : ℕ) : a^(n+1) = a * a^n := rfl theorem succ_nsmul (a : A) (n : ℕ) : (n+1) •ℕ a = a + n •ℕ a := rfl theorem pow_two (a : M) : a^2 = a * a := show a*(a*1)=a*a, by rw mul_one theorem two_nsmul (a : A) : 2 •ℕ a = a + a := @pow_two (multiplicative A) _ a theorem pow_mul_comm' (a : M) (n : ℕ) : a^n * a = a * a^n := commute.pow_self a n theorem nsmul_add_comm' : ∀ (a : A) (n : ℕ), n •ℕ a + a = a + n •ℕ a := @pow_mul_comm' (multiplicative A) _ theorem pow_succ' (a : M) (n : ℕ) : a^(n+1) = a^n * a := by rw [pow_succ, pow_mul_comm'] theorem succ_nsmul' (a : A) (n : ℕ) : (n+1) •ℕ a = n •ℕ a + a := @pow_succ' (multiplicative A) _ _ _ theorem pow_add (a : M) (m n : ℕ) : a^(m + n) = a^m * a^n := by induction n with n ih; [rw [nat.add_zero, pow_zero, mul_one], rw [pow_succ', ← mul_assoc, ← ih, ← pow_succ', nat.add_assoc]] theorem add_nsmul : ∀ (a : A) (m n : ℕ), (m + n) •ℕ a = m •ℕ a + n •ℕ a := @pow_add (multiplicative A) _ @[simp] theorem pow_one (a : M) : a^1 = a := mul_one _ @[simp] theorem one_nsmul (a : A) : 1 •ℕ a = a := add_zero _ @[simp] lemma pow_ite (P : Prop) [decidable P] (a : M) (b c : ℕ) : a ^ (if P then b else c) = if P then a ^ b else a ^ c := by split_ifs; refl @[simp] lemma ite_pow (P : Prop) [decidable P] (a b : M) (c : ℕ) : (if P then a else b) ^ c = if P then a ^ c else b ^ c := by split_ifs; refl @[simp] lemma pow_boole (P : Prop) [decidable P] (a : M) : a ^ (if P then 1 else 0) = if P then a else 1 := by simp @[simp] theorem one_pow (n : ℕ) : (1 : M)^n = 1 := by induction n with n ih; [refl, rw [pow_succ, ih, one_mul]] @[simp] theorem nsmul_zero (n : ℕ) : n •ℕ (0 : A) = 0 := by induction n with n ih; [refl, rw [succ_nsmul, ih, zero_add]] theorem pow_mul (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n := by induction n with n ih; [rw nat.mul_zero, rw [nat.mul_succ, pow_add, pow_succ', ih]]; refl theorem mul_nsmul' : ∀ (a : A) (m n : ℕ), m * n •ℕ a = n •ℕ (m •ℕ a) := @pow_mul (multiplicative A) _ theorem pow_mul' (a : M) (m n : ℕ) : a^(m * n) = (a^n)^m := by rw [nat.mul_comm, pow_mul] theorem mul_nsmul (a : A) (m n : ℕ) : m * n •ℕ a = m •ℕ (n •ℕ a) := @pow_mul' (multiplicative A) _ a m n theorem pow_mul_pow_sub (a : M) {m n : ℕ} (h : m ≤ n) : a ^ m * a ^ (n - m) = a ^ n := by rw [←pow_add, nat.add_comm, nat.sub_add_cancel h] theorem nsmul_add_sub_nsmul (a : A) {m n : ℕ} (h : m ≤ n) : (m •ℕ a) + ((n - m) •ℕ a) = n •ℕ a := @pow_mul_pow_sub (multiplicative A) _ _ _ _ h theorem pow_sub_mul_pow (a : M) {m n : ℕ} (h : m ≤ n) : a ^ (n - m) * a ^ m = a ^ n := by rw [←pow_add, nat.sub_add_cancel h] theorem sub_nsmul_nsmul_add (a : A) {m n : ℕ} (h : m ≤ n) : ((n - m) •ℕ a) + (m •ℕ a) = n •ℕ a := @pow_sub_mul_pow (multiplicative A) _ _ _ _ h theorem pow_bit0 (a : M) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _ theorem bit0_nsmul (a : A) (n : ℕ) : bit0 n •ℕ a = n •ℕ a + n •ℕ a := add_nsmul _ _ _ theorem pow_bit1 (a : M) (n : ℕ) : a ^ bit1 n = a^n * a^n * a := by rw [bit1, pow_succ', pow_bit0] theorem bit1_nsmul : ∀ (a : A) (n : ℕ), bit1 n •ℕ a = n •ℕ a + n •ℕ a + a := @pow_bit1 (multiplicative A) _ theorem pow_mul_comm (a : M) (m n : ℕ) : a^m * a^n = a^n * a^m := commute.pow_pow_self a m n theorem nsmul_add_comm : ∀ (a : A) (m n : ℕ), m •ℕ a + n •ℕ a = n •ℕ a + m •ℕ a := @pow_mul_comm (multiplicative A) _ @[simp] theorem monoid_hom.map_pow (f : M →* N) (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n | 0 := f.map_one | (n+1) := by rw [pow_succ, pow_succ, f.map_mul, monoid_hom.map_pow] @[simp] theorem add_monoid_hom.map_nsmul (f : A →+ B) (a : A) (n : ℕ) : f (n •ℕ a) = n •ℕ f a := f.to_multiplicative.map_pow a n theorem is_monoid_hom.map_pow (f : M → N) [is_monoid_hom f] (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n := (monoid_hom.of f).map_pow a theorem is_add_monoid_hom.map_nsmul (f : A → B) [is_add_monoid_hom f] (a : A) (n : ℕ) : f (n •ℕ a) = n •ℕ f a := (add_monoid_hom.of f).map_nsmul a n lemma commute.mul_pow {a b : M} (h : commute a b) (n : ℕ) : (a * b) ^ n = a ^ n * b ^ n := nat.rec_on n (by simp) $ λ n ihn, by simp only [pow_succ, ihn, ← mul_assoc, (h.pow_left n).right_comm] theorem neg_pow [ring R] (a : R) (n : ℕ) : (- a) ^ n = (-1) ^ n * a ^ n := (neg_one_mul a) ▸ (commute.neg_one_left a).mul_pow n theorem pow_bit0' (a : M) (n : ℕ) : a ^ bit0 n = (a * a) ^ n := by rw [pow_bit0, (commute.refl a).mul_pow] theorem bit0_nsmul' (a : A) (n : ℕ) : bit0 n •ℕ a = n •ℕ (a + a) := @pow_bit0' (multiplicative A) _ _ _ theorem pow_bit1' (a : M) (n : ℕ) : a ^ bit1 n = (a * a) ^ n * a := by rw [bit1, pow_succ', pow_bit0'] theorem bit1_nsmul' : ∀ (a : A) (n : ℕ), bit1 n •ℕ a = n •ℕ (a + a) + a := @pow_bit1' (multiplicative A) _ @[simp] theorem neg_pow_bit0 [ring R] (a : R) (n : ℕ) : (- a) ^ (bit0 n) = a ^ (bit0 n) := by rw [pow_bit0', neg_mul_neg, pow_bit0'] @[simp] theorem neg_pow_bit1 [ring R] (a : R) (n : ℕ) : (- a) ^ (bit1 n) = - a ^ (bit1 n) := by simp only [bit1, pow_succ, neg_pow_bit0, neg_mul_eq_neg_mul] end monoid /-! ### Commutative (additive) monoid -/ section comm_monoid variables [comm_monoid M] [add_comm_monoid A] theorem mul_pow (a b : M) (n : ℕ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_pow n theorem nsmul_add : ∀ (a b : A) (n : ℕ), n •ℕ (a + b) = n •ℕ a + n •ℕ b := @mul_pow (multiplicative A) _ instance pow.is_monoid_hom (n : ℕ) : is_monoid_hom ((^ n) : M → M) := { map_mul := λ _ _, mul_pow _ _ _, map_one := one_pow _ } instance nsmul.is_add_monoid_hom (n : ℕ) : is_add_monoid_hom (nsmul n : A → A) := { map_add := λ _ _, nsmul_add _ _ _, map_zero := nsmul_zero _ } lemma dvd_pow {x y : M} : ∀ {n : ℕ} (hxy : x ∣ y) (hn : n ≠ 0), x ∣ y^n | 0 hxy hn := (hn rfl).elim | (n+1) hxy hn := by { rw [pow_succ], exact dvd_mul_of_dvd_left hxy _ } end comm_monoid section group variables [group G] [group H] [add_group A] [add_group B] open int /-- The power operation in a group. This extends `monoid.pow` to negative integers with the definition `a^(-n) = (a^n)⁻¹`. -/ def gpow (a : G) : ℤ → G | (of_nat n) := a^n | -[1+n] := (a^(nat.succ n))⁻¹ /-- The scalar multiplication by integers on an additive group. This extends `nsmul` to negative integers with the definition `(-n) •ℤ a = -(n •ℕ a)`. -/ def gsmul (n : ℤ) (a : A) : A := @gpow (multiplicative A) _ a n instance group.has_pow : has_pow G ℤ := ⟨gpow⟩ infix ` •ℤ `:70 := gsmul @[simp] lemma group.gpow_eq_has_pow (a : G) (n : ℤ) : gpow a n = a ^ n := rfl section nat @[simp] theorem inv_pow (a : G) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ := by induction n with n ih; [exact one_inv.symm, rw [pow_succ', pow_succ, ih, mul_inv_rev]] @[simp] theorem neg_nsmul : ∀ (a : A) (n : ℕ), n •ℕ (-a) = -(n •ℕ a) := @inv_pow (multiplicative A) _ theorem pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a^(m - n) = a^m * (a^n)⁻¹ := have h1 : m - n + n = m, from nat.sub_add_cancel h, have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1], eq_mul_inv_of_mul_eq h2 theorem nsmul_sub : ∀ (a : A) {m n : ℕ}, n ≤ m → (m - n) •ℕ a = m •ℕ a - n •ℕ a := by simpa only [sub_eq_add_neg] using @pow_sub (multiplicative A) _ theorem pow_inv_comm (a : G) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m := (commute.refl a).inv_left.pow_pow m n theorem nsmul_neg_comm : ∀ (a : A) (m n : ℕ), m •ℕ (-a) + n •ℕ a = n •ℕ a + m •ℕ (-a) := @pow_inv_comm (multiplicative A) _ end nat @[simp] theorem gpow_coe_nat (a : G) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl @[simp] theorem gsmul_coe_nat (a : A) (n : ℕ) : n •ℤ a = n •ℕ a := rfl theorem gpow_of_nat (a : G) (n : ℕ) : a ^ of_nat n = a ^ n := rfl theorem gsmul_of_nat (a : A) (n : ℕ) : of_nat n •ℤ a = n •ℕ a := rfl @[simp] theorem gpow_neg_succ_of_nat (a : G) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl @[simp] theorem gsmul_neg_succ_of_nat (a : A) (n : ℕ) : -[1+n] •ℤ a = - (n.succ •ℕ a) := rfl @[simp] theorem gpow_zero (a : G) : a ^ (0:ℤ) = 1 := rfl @[simp] theorem zero_gsmul (a : A) : (0:ℤ) •ℤ a = 0 := rfl @[simp] theorem gpow_one (a : G) : a ^ (1:ℤ) = a := pow_one a @[simp] theorem one_gsmul (a : A) : (1:ℤ) •ℤ a = a := add_zero _ @[simp] theorem one_gpow : ∀ (n : ℤ), (1 : G) ^ n = 1 | (n : ℕ) := one_pow _ | -[1+ n] := show _⁻¹=(1:G), by rw [one_pow, one_inv] @[simp] theorem gsmul_zero : ∀ (n : ℤ), n •ℤ (0 : A) = 0 := @one_gpow (multiplicative A) _ @[simp] theorem gpow_neg (a : G) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹ | (n+1:ℕ) := rfl | 0 := one_inv.symm | -[1+ n] := (inv_inv _).symm lemma mul_gpow_neg_one (a b : G) : (a*b)^(-(1:ℤ)) = b^(-(1:ℤ))*a^(-(1:ℤ)) := by simp only [mul_inv_rev, gpow_one, gpow_neg] @[simp] theorem neg_gsmul : ∀ (a : A) (n : ℤ), -n •ℤ a = -(n •ℤ a) := @gpow_neg (multiplicative A) _ theorem gpow_neg_one (x : G) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x theorem neg_one_gsmul (x : A) : (-1:ℤ) •ℤ x = -x := congr_arg has_neg.neg $ one_nsmul x theorem inv_gpow (a : G) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹ | (n : ℕ) := inv_pow a n | -[1+ n] := congr_arg has_inv.inv $ inv_pow a (n+1) theorem gsmul_neg (a : A) (n : ℤ) : gsmul n (- a) = - gsmul n a := @inv_gpow (multiplicative A) _ a n theorem commute.mul_gpow {a b : G} (h : commute a b) : ∀ n : ℤ, (a * b) ^ n = a ^ n * b ^ n | (n : ℕ) := h.mul_pow n | -[1+n] := by simp [h.mul_pow, (h.pow_pow n.succ n.succ).inv_inv.symm.eq] end group section comm_group variables [comm_group G] [add_comm_group A] theorem mul_gpow (a b : G) (n : ℤ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_gpow n theorem gsmul_add : ∀ (a b : A) (n : ℤ), n •ℤ (a + b) = n •ℤ a + n •ℤ b := @mul_gpow (multiplicative A) _ theorem gsmul_sub (a b : A) (n : ℤ) : gsmul n (a - b) = gsmul n a - gsmul n b := by simp only [gsmul_add, gsmul_neg, sub_eq_add_neg] instance gpow.is_group_hom (n : ℤ) : is_group_hom ((^ n) : G → G) := { map_mul := λ _ _, mul_gpow _ _ n } instance gsmul.is_add_group_hom (n : ℤ) : is_add_group_hom (gsmul n : A → A) := { map_add := λ _ _, gsmul_add _ _ n } end comm_group lemma zero_pow [monoid_with_zero R] : ∀ {n : ℕ}, 0 < n → (0 : R) ^ n = 0 | (n+1) _ := zero_mul _ namespace ring_hom variables [semiring R] [semiring S] @[simp] lemma map_pow (f : R →+* S) (a) : ∀ n : ℕ, f (a ^ n) = (f a) ^ n := f.to_monoid_hom.map_pow a end ring_hom theorem neg_one_pow_eq_or [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1 | 0 := or.inl rfl | (n+1) := (neg_one_pow_eq_or n).swap.imp (λ h, by rw [pow_succ, h, neg_one_mul, neg_neg]) (λ h, by rw [pow_succ, h, mul_one]) lemma pow_dvd_pow [monoid R] (a : R) {m n : ℕ} (h : m ≤ n) : a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_comm, nat.sub_add_cancel h]⟩ theorem pow_dvd_pow_of_dvd [comm_monoid R] {a b : R} (h : a ∣ b) : ∀ n : ℕ, a ^ n ∣ b ^ n | 0 := dvd_refl _ | (n+1) := mul_dvd_mul h (pow_dvd_pow_of_dvd n) lemma pow_two_sub_pow_two {R : Type*} [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by simp only [pow_two, mul_sub, add_mul, sub_sub, add_sub, mul_comm, sub_add_cancel] lemma eq_or_eq_neg_of_pow_two_eq_pow_two [integral_domain R] (a b : R) (h : a ^ 2 = b ^ 2) : a = b ∨ a = -b := by rwa [← add_eq_zero_iff_eq_neg, ← sub_eq_zero, or_comm, ← mul_eq_zero, ← pow_two_sub_pow_two a b, sub_eq_zero] theorem sq_sub_sq [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by rw [pow_two, pow_two, mul_self_sub_mul_self] theorem pow_eq_zero [monoid_with_zero R] [no_zero_divisors R] {x : R} {n : ℕ} (H : x^n = 0) : x = 0 := begin induction n with n ih, { rw pow_zero at H, rw [← mul_one x, H, mul_zero] }, exact or.cases_on (mul_eq_zero.1 H) id ih end @[simp] lemma pow_eq_zero_iff [monoid_with_zero R] [no_zero_divisors R] {a : R} {n : ℕ} (hn : 0 < n) : a ^ n = 0 ↔ a = 0 := begin refine ⟨pow_eq_zero, _⟩, rintros rfl, exact zero_pow hn, end @[field_simps] theorem pow_ne_zero [monoid_with_zero R] [no_zero_divisors R] {a : R} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := mt pow_eq_zero h lemma pow_abs [linear_ordered_comm_ring R] (a : R) (n : ℕ) : (abs a)^n = abs (a^n) := (abs_hom.to_monoid_hom.map_pow a n).symm lemma abs_neg_one_pow [linear_ordered_comm_ring R] (n : ℕ) : abs ((-1 : R)^n) = 1 := by rw [←pow_abs, abs_neg, abs_one, one_pow] section add_monoid variable [ordered_add_comm_monoid A] theorem nsmul_nonneg {a : A} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n •ℕ a | 0 := le_refl _ | (n+1) := add_nonneg H (nsmul_nonneg n) lemma nsmul_pos {a : A} (ha : 0 < a) {k : ℕ} (hk : 0 < k) : 0 < k •ℕ a := begin rcases nat.exists_eq_succ_of_ne_zero (ne_of_gt hk) with ⟨l, rfl⟩, clear hk, induction l with l IH, { simpa using ha }, { exact add_pos ha IH } end theorem nsmul_le_nsmul {a : A} {n m : ℕ} (ha : 0 ≤ a) (h : n ≤ m) : n •ℕ a ≤ m •ℕ a := let ⟨k, hk⟩ := nat.le.dest h in calc n •ℕ a = n •ℕ a + 0 : (add_zero _).symm ... ≤ n •ℕ a + k •ℕ a : add_le_add_left (nsmul_nonneg ha _) _ ... = m •ℕ a : by rw [← hk, add_nsmul] lemma nsmul_le_nsmul_of_le_right {a b : A} (hab : a ≤ b) : ∀ i : ℕ, i •ℕ a ≤ i •ℕ b | 0 := by simp | (k+1) := add_le_add hab (nsmul_le_nsmul_of_le_right _) end add_monoid section add_group variable [ordered_add_comm_group A] theorem gsmul_nonneg {a : A} (H : 0 ≤ a) {n : ℤ} (hn : 0 ≤ n) : 0 ≤ n •ℤ a := begin lift n to ℕ using hn, apply nsmul_nonneg H end end add_group section cancel_add_monoid variable [ordered_cancel_add_comm_monoid A] theorem nsmul_lt_nsmul {a : A} {n m : ℕ} (ha : 0 < a) (h : n < m) : n •ℕ a < m •ℕ a := let ⟨k, hk⟩ := nat.le.dest h in begin have succ_swap : n.succ + k = n + k.succ := nat.succ_add n k, calc n •ℕ a = (n •ℕ a : A) + (0 : A) : (add_zero _).symm ... < n •ℕ a + (k.succ •ℕ a : A) : add_lt_add_left (nsmul_pos ha (nat.succ_pos k)) _ ... = m •ℕ a : by rw [← hk, succ_swap, add_nsmul] end end cancel_add_monoid section semiring variables [semiring R] lemma min_pow_dvd_add {n m : ℕ} {a b c : R} (ha : c ^ n ∣ a) (hb : c ^ m ∣ b) : c ^ (min n m) ∣ a + b := begin replace ha := dvd.trans (pow_dvd_pow c (min_le_left n m)) ha, replace hb := dvd.trans (pow_dvd_pow c (min_le_right n m)) hb, exact dvd_add ha hb end end semiring section comm_semiring variables [comm_semiring R] lemma add_pow_two (a b : R) : (a + b) ^ 2 = a ^ 2 + 2 * a * b + b ^ 2 := by simp only [pow_two, add_mul_self_eq] end comm_semiring namespace canonically_ordered_semiring variable [canonically_ordered_comm_semiring R] theorem pow_pos {a : R} (H : 0 < a) : ∀ n : ℕ, 0 < a ^ n | 0 := by { nontriviality, exact canonically_ordered_semiring.zero_lt_one } | (n+1) := canonically_ordered_semiring.mul_pos.2 ⟨H, pow_pos n⟩ @[mono] lemma pow_le_pow_of_le_left {a b : R} (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := canonically_ordered_semiring.mul_le_mul hab (pow_le_pow_of_le_left k) theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) (n : ℕ) : 1 ≤ a ^ n := by simpa only [one_pow] using pow_le_pow_of_le_left H n theorem pow_le_one {a : R} (H : a ≤ 1) (n : ℕ) : a ^ n ≤ 1:= by simpa only [one_pow] using pow_le_pow_of_le_left H n end canonically_ordered_semiring section ordered_semiring variable [ordered_semiring R] @[simp] theorem pow_pos {a : R} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n | 0 := by { nontriviality, exact zero_lt_one } | (n+1) := mul_pos H (pow_pos _) @[simp] theorem pow_nonneg {a : R} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n | 0 := zero_le_one | (n+1) := mul_nonneg H (pow_nonneg _) theorem pow_add_pow_le {x y : R} {n : ℕ} (hx : 0 ≤ x) (hy : 0 ≤ y) (hn : n ≠ 0) : x ^ n + y ^ n ≤ (x + y) ^ n := begin rcases nat.exists_eq_succ_of_ne_zero hn with ⟨k, rfl⟩, induction k with k ih, { simp only [pow_one] }, let n := k.succ, have h1 := add_nonneg (mul_nonneg hx (pow_nonneg hy n)) (mul_nonneg hy (pow_nonneg hx n)), have h2 := add_nonneg hx hy, calc x^n.succ + y^n.succ ≤ x*x^n + y*y^n + (x*y^n + y*x^n) : le_add_of_nonneg_right h1 ... = (x+y) * (x^n + y^n) : by rw [add_mul, mul_add, mul_add, add_comm (y*x^n), ← add_assoc, ← add_assoc, add_assoc (x*x^n) (x*y^n), add_comm (x*y^n) (y*y^n), ← add_assoc] ... ≤ (x+y)^n.succ : mul_le_mul_of_nonneg_left (ih (nat.succ_ne_zero k)) h2, end theorem pow_lt_pow_of_lt_left {x y : R} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) : x ^ n < y ^ n := begin cases lt_or_eq_of_le Hxpos, { rw ←nat.sub_add_cancel Hnpos, induction (n - 1), { simpa only [pow_one] }, rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one], apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) }, { rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),} end theorem strict_mono_incr_on_pow {n : ℕ} (hn : 0 < n) : strict_mono_incr_on (λ x : R, x ^ n) (set.Ici 0) := λ x hx y hy h, pow_lt_pow_of_lt_left h hx hn theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n | 0 := le_refl _ | (n+1) := by simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n) zero_le_one (le_trans zero_le_one H) lemma pow_mono {a : R} (h : 1 ≤ a) : monotone (λ n : ℕ, a ^ n) := monotone_of_monotone_nat $ λ n, le_mul_of_one_le_left (pow_nonneg (zero_le_one.trans h) _) h theorem pow_le_pow {a : R} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := pow_mono ha h lemma strict_mono_pow {a : R} (h : 1 < a) : strict_mono (λ n : ℕ, a ^ n) := have 0 < a := zero_le_one.trans_lt h, strict_mono.nat $ λ n, by simpa only [one_mul, pow_succ] using mul_lt_mul h (le_refl (a ^ n)) (pow_pos this _) this.le lemma pow_lt_pow {a : R} {n m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m := strict_mono_pow h h2 lemma pow_lt_pow_iff {a : R} {n m : ℕ} (h : 1 < a) : a ^ n < a ^ m ↔ n < m := (strict_mono_pow h).lt_iff_lt @[mono] lemma pow_le_pow_of_le_left {a b : R} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab) end ordered_semiring section linear_ordered_semiring variable [linear_ordered_semiring R] theorem pow_left_inj {x y : R} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n) (Hxyn : x ^ n = y ^ n) : x = y := (@strict_mono_incr_on_pow R _ _ Hnpos).inj_on Hxpos Hypos Hxyn lemma lt_of_pow_lt_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b := lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h lemma le_of_pow_le_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (hn : 0 < n) (h : a ^ n ≤ b ^ n) : a ≤ b := le_of_not_lt $ λ h1, not_le_of_lt (pow_lt_pow_of_lt_left h1 hb hn) h end linear_ordered_semiring section linear_ordered_ring variable [linear_ordered_ring R] theorem pow_bit0_nonneg (a : R) (n : ℕ) : 0 ≤ a ^ bit0 n := by { rw pow_bit0, exact mul_self_nonneg _ } theorem pow_two_nonneg (a : R) : 0 ≤ a ^ 2 := pow_bit0_nonneg a 1 theorem pow_bit0_pos {a : R} (h : a ≠ 0) (n : ℕ) : 0 < a ^ bit0 n := (pow_bit0_nonneg a n).lt_of_ne (pow_ne_zero _ h).symm theorem pow_two_pos_of_ne_zero (a : R) (h : a ≠ 0) : 0 < a ^ 2 := pow_bit0_pos h 1 variables {x y : R} @[simp] theorem sqr_abs (x : R) : abs x ^ 2 = x ^ 2 := by simpa only [pow_two] using abs_mul_abs_self x theorem abs_sqr (x : R) : abs (x ^ 2) = x ^ 2 := by simpa only [pow_two] using abs_mul_self x theorem sqr_lt_sqr (h : abs x < y) : x ^ 2 < y ^ 2 := by simpa only [sqr_abs] using pow_lt_pow_of_lt_left h (abs_nonneg x) (1:ℕ).succ_pos theorem sqr_lt_sqr' (h1 : -y < x) (h2 : x < y) : x ^ 2 < y ^ 2 := sqr_lt_sqr (abs_lt.mpr ⟨h1, h2⟩) theorem sqr_le_sqr (h : abs x ≤ y) : x ^ 2 ≤ y ^ 2 := by simpa only [sqr_abs] using pow_le_pow_of_le_left (abs_nonneg x) h 2 theorem sqr_le_sqr' (h1 : -y ≤ x) (h2 : x ≤ y) : x ^ 2 ≤ y ^ 2 := sqr_le_sqr (abs_le.mpr ⟨h1, h2⟩) theorem abs_lt_abs_of_sqr_lt_sqr (h : x^2 < y^2) : abs x < abs y := lt_of_pow_lt_pow 2 (abs_nonneg y) $ by rwa [← sqr_abs x, ← sqr_abs y] at h theorem abs_lt_of_sqr_lt_sqr (h : x^2 < y^2) (hy : 0 ≤ y) : abs x < y := begin rw [← abs_of_nonneg hy], exact abs_lt_abs_of_sqr_lt_sqr h, end theorem abs_lt_of_sqr_lt_sqr' (h : x^2 < y^2) (hy : 0 ≤ y) : -y < x ∧ x < y := abs_lt.mp $ abs_lt_of_sqr_lt_sqr h hy theorem abs_le_abs_of_sqr_le_sqr (h : x^2 ≤ y^2) : abs x ≤ abs y := le_of_pow_le_pow 2 (abs_nonneg y) (1:ℕ).succ_pos $ by rwa [← sqr_abs x, ← sqr_abs y] at h theorem abs_le_of_sqr_le_sqr (h : x^2 ≤ y^2) (hy : 0 ≤ y) : abs x ≤ y := begin rw [← abs_of_nonneg hy], exact abs_le_abs_of_sqr_le_sqr h, end theorem abs_le_of_sqr_le_sqr' (h : x^2 ≤ y^2) (hy : 0 ≤ y) : -y ≤ x ∧ x ≤ y := abs_le.mp $ abs_le_of_sqr_le_sqr h hy end linear_ordered_ring @[simp] lemma eq_of_pow_two_eq_pow_two [linear_ordered_comm_ring R] {a b : R} (ha : 0 ≤ a) (hb : 0 ≤ b) : a ^ 2 = b ^ 2 ↔ a = b := begin refine ⟨_, congr_arg _⟩, intros h, refine (eq_or_eq_neg_of_pow_two_eq_pow_two _ _ h).elim id _, rintros rfl, rw le_antisymm (neg_nonneg.mp ha) hb, exact neg_zero end @[simp] lemma neg_square {α} [ring α] (z : α) : (-z)^2 = z^2 := by simp [pow, monoid.pow] lemma of_add_nsmul [add_monoid A] (x : A) (n : ℕ) : multiplicative.of_add (n •ℕ x) = (multiplicative.of_add x)^n := rfl lemma of_add_gsmul [add_group A] (x : A) (n : ℤ) : multiplicative.of_add (n •ℤ x) = (multiplicative.of_add x)^n := rfl @[simp] lemma semiconj_by.gpow_right [group G] {a x y : G} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (x^m) (y^m) | (n : ℕ) := h.pow_right n | -[1+n] := (h.pow_right n.succ).inv_right namespace commute variables [group G] {a b : G} @[simp] lemma gpow_right (h : commute a b) (m : ℤ) : commute a (b^m) := h.gpow_right m @[simp] lemma gpow_left (h : commute a b) (m : ℤ) : commute (a^m) b := (h.symm.gpow_right m).symm lemma gpow_gpow (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) := (h.gpow_left m).gpow_right n variables (a) (m n : ℕ) @[simp] theorem self_gpow : commute a (a ^ n) := (commute.refl a).gpow_right n @[simp] theorem gpow_self : commute (a ^ n) a := (commute.refl a).gpow_left n @[simp] theorem gpow_gpow_self : commute (a ^ m) (a ^ n) := (commute.refl a).gpow_gpow m n end commute
b69ccb0f725afde9192e6f3a670b1729712aa1b8
6a205478518645c9c32139432d2515af695dade4
/src/Sample.lean
d7676262b6b28216b68510eda0ff66a1f03f77de
[ "LicenseRef-scancode-mit-taylor-variant", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
o89/sample-n2o
9febd9110b69ecb9c999e98d1d9ed5498425f5dd
6a6a450bbebc2f54a7f0d2ab66ef37c8a69feb45
refs/heads/master
1,655,813,514,957
1,655,472,697,000
1,655,472,697,000
205,369,860
2
2
null
null
null
null
UTF-8
Lean
false
false
464
lean
import Init.System.IO import N2O.Default def echoProto : Proto := { ev := Option String, nothing := Result.ok, proto := λ p => match p with | Msg.text s => some s | _ => none } def echo : echoProto.ev → Result | none => Result.ok | some s => Result.reply (Msg.text s) def router (cx : Cx echoProto) : Cx echoProto := ⟨cx.req, echo⟩ def handler : Handler := mkHandler echoProto [ router ] def main := startServer handler ("localhost", 9000)
cdb10be8aced6a688a28efbcf59f0ab7e8f0169f
ebbdcbd7ddc89a9ef7c3b397b301d5f5272a918f
/qp/p0_stdlib/c3_order.lean
2cd3a8365c457e65af92223db2fee7757d9936fd
[]
no_license
intoverflow/qvr
34b9ef23604738381ca20b7d622fd0399d88f2dd
0cfcd33fe4bf8d93851a00cec5bfd21e77105d74
refs/heads/master
1,616,591,570,371
1,492,575,772,000
1,492,575,772,000
80,061,627
0
0
null
null
null
null
UTF-8
Lean
false
false
659
lean
/- ----------------------------------------------------------------------- Facts about orders. ----------------------------------------------------------------------- -/ namespace qp namespace stdaux universe variables ℓ₁ ℓ₂ /-! #brief A monotone function. -/ definition monotone {A : Sort ℓ₁} (r : A → A → Prop) {B : Sort ℓ₂} (s : B → B → Prop) (f : A → B) : Prop := ∀ (a₁ a₂ : A) , r a₁ a₂ → s (f a₁) (f a₂) /-! #brief The identity function is monotone. -/ definition id.monotone {A : Sort ℓ₁} (r : A → A → Prop) : monotone r r id := λ a₁ a₂ ω, ω end stdaux end qp
27dfbf4e177fef44359464903d6c5ceb7e12359c
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/algebra/algebra/basic.lean
1664a13e31c388a23379696adafe05239bd1c52f
[ "Apache-2.0" ]
permissive
jesse-michael-han/mathlib
a15c58378846011b003669354cbab7062b893cfe
fa6312e4dc971985e6b7708d99a5bc3062485c89
refs/heads/master
1,625,200,760,912
1,602,081,753,000
1,602,081,753,000
181,787,230
0
0
null
1,555,460,682,000
1,555,460,682,000
null
UTF-8
Lean
false
false
44,610
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import tactic.nth_rewrite import data.matrix.basic import linear_algebra.tensor_product import ring_theory.subring import deprecated.subring /-! # Algebra over Commutative Semiring (under category) In this file we define algebra over commutative (semi)rings, algebra homomorphisms `alg_hom`, algebra equivalences `alg_equiv`. We also define usual operations on `alg_hom`s (`id`, `comp`). `subalgebra`s are defined in `algebra.algebra.subalgebra`. If `S` is an `R`-algebra and `A` is an `S`-algebra then `algebra.comap.algebra R S A` can be used to provide `A` with a structure of an `R`-algebra. Other than that, `algebra.comap` is now deprecated and replcaed with `is_scalar_tower`. ## Notations * `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`. * `A ≃ₐ[R] B` : `R`-algebra equivalence from `A` to `B`. -/ universes u v w u₁ v₁ open_locale tensor_product big_operators section prio -- We set this priority to 0 later in this file set_option extends_priority 200 /- control priority of `instance [algebra R A] : has_scalar R A` -/ /-- The category of R-algebras where R is a commutative ring is the under category R ↓ CRing. In the categorical setting we have a forgetful functor R-Alg ⥤ R-Mod. However here it extends module in order to preserve definitional equality in certain cases. -/ @[nolint has_inhabited_instance] class algebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A] extends has_scalar R A, R →+* A := (commutes' : ∀ r x, to_fun r * x = x * to_fun r) (smul_def' : ∀ r x, r • x = to_fun r * x) end prio /-- Embedding `R →+* A` given by `algebra` structure. -/ def algebra_map (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : R →+* A := algebra.to_ring_hom /-- Creating an algebra from a morphism to the center of a semiring. -/ def ring_hom.to_algebra' {R S} [comm_semiring R] [semiring S] (i : R →+* S) (h : ∀ c x, i c * x = x * i c) : algebra R S := { smul := λ c x, i c * x, commutes' := h, smul_def' := λ c x, rfl, .. i} /-- Creating an algebra from a morphism to a commutative semiring. -/ def ring_hom.to_algebra {R S} [comm_semiring R] [comm_semiring S] (i : R →+* S) : algebra R S := i.to_algebra' $ λ _, mul_comm _ namespace algebra variables {R : Type u} {S : Type v} {A : Type w} /-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure. If `(r • 1) * x = x * (r • 1) = r • x` for all `r : R` and `x : A`, then `A` is an `algebra` over `R`. -/ def of_semimodule' [comm_semiring R] [semiring A] [semimodule R A] (h₁ : ∀ (r : R) (x : A), (r • 1) * x = r • x) (h₂ : ∀ (r : R) (x : A), x * (r • 1) = r • x) : algebra R A := { to_fun := λ r, r • 1, map_one' := one_smul _ _, map_mul' := λ r₁ r₂, by rw [h₁, mul_smul], map_zero' := zero_smul _ _, map_add' := λ r₁ r₂, add_smul r₁ r₂ 1, commutes' := λ r x, by simp only [h₁, h₂], smul_def' := λ r x, by simp only [h₁] } /-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure. If `(r • x) * y = x * (r • y) = r • (x * y)` for all `r : R` and `x y : A`, then `A` is an `algebra` over `R`. -/ def of_semimodule [comm_semiring R] [semiring A] [semimodule R A] (h₁ : ∀ (r : R) (x y : A), (r • x) * y = r • (x * y)) (h₂ : ∀ (r : R) (x y : A), x * (r • y) = r • (x * y)) : algebra R A := of_semimodule' (λ r x, by rw [h₁, one_mul]) (λ r x, by rw [h₂, mul_one]) section semiring variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R A] lemma smul_def'' (r : R) (x : A) : r • x = algebra_map R A r * x := algebra.smul_def' r x /-- To prove two algebra structures on a fixed `[comm_semiring R] [semiring A]` agree, it suffices to check the `algebra_map`s agree. -/ -- We'll later use this to show `algebra ℤ M` is a subsingleton. @[ext] lemma algebra_ext {R : Type*} [comm_semiring R] {A : Type*} [semiring A] (P Q : algebra R A) (w : ∀ (r : R), by { haveI := P, exact algebra_map R A r } = by { haveI := Q, exact algebra_map R A r }) : P = Q := begin unfreezingI { rcases P with ⟨⟨P⟩⟩, rcases Q with ⟨⟨Q⟩⟩ }, congr, { funext r a, replace w := congr_arg (λ s, s * a) (w r), simp only [←algebra.smul_def''] at w, apply w, }, { ext r, exact w r, }, { apply proof_irrel_heq, }, { apply proof_irrel_heq, }, end @[priority 200] -- see Note [lower instance priority] instance to_semimodule : semimodule R A := { one_smul := by simp [smul_def''], mul_smul := by simp [smul_def'', mul_assoc], smul_add := by simp [smul_def'', mul_add], smul_zero := by simp [smul_def''], add_smul := by simp [smul_def'', add_mul], zero_smul := by simp [smul_def''] } -- from now on, we don't want to use the following instance anymore attribute [instance, priority 0] algebra.to_has_scalar lemma smul_def (r : R) (x : A) : r • x = algebra_map R A r * x := algebra.smul_def' r x lemma algebra_map_eq_smul_one (r : R) : algebra_map R A r = r • 1 := calc algebra_map R A r = algebra_map R A r * 1 : (mul_one _).symm ... = r • 1 : (algebra.smul_def r 1).symm theorem commutes (r : R) (x : A) : algebra_map R A r * x = x * algebra_map R A r := algebra.commutes' r x theorem left_comm (r : R) (x y : A) : x * (algebra_map R A r * y) = algebra_map R A r * (x * y) := by rw [← mul_assoc, ← commutes, mul_assoc] @[simp] lemma mul_smul_comm (s : R) (x y : A) : x * (s • y) = s • (x * y) := by rw [smul_def, smul_def, left_comm] @[simp] lemma smul_mul_assoc (r : R) (x y : A) : (r • x) * y = r • (x * y) := by rw [smul_def, smul_def, mul_assoc] section variables (r : R) (a : A) @[simp] lemma bit0_smul_one : bit0 r • (1 : A) = r • 2 := by simp [bit0, add_smul, smul_add] @[simp] lemma bit0_smul_bit0 : bit0 r • bit0 a = r • (bit0 (bit0 a)) := by simp [bit0, add_smul, smul_add] @[simp] lemma bit0_smul_bit1 : bit0 r • bit1 a = r • (bit0 (bit1 a)) := by simp [bit0, add_smul, smul_add] @[simp] lemma bit1_smul_one : bit1 r • (1 : A) = r • 2 + 1 := by simp [bit1, add_smul, smul_add] @[simp] lemma bit1_smul_bit0 : bit1 r • bit0 a = r • (bit0 (bit0 a)) + bit0 a := by simp [bit1, add_smul, smul_add] @[simp] lemma bit1_smul_bit1 : bit1 r • bit1 a = r • (bit0 (bit1 a)) + bit1 a := by { simp only [bit0, bit1, add_smul, smul_add, one_smul], abel } end variables (R A) /-- The canonical ring homomorphism `algebra_map R A : R →* A` for any `R`-algebra `A`, packaged as an `R`-linear map. -/ protected def linear_map : R →ₗ[R] A := { map_smul' := λ x y, begin dsimp, simp [algebra.smul_def], end, ..algebra_map R A } @[simp] lemma linear_map_apply (r : R) : algebra.linear_map R A r = algebra_map R A r := rfl instance id : algebra R R := (ring_hom.id R).to_algebra variables {R A} namespace id @[simp] lemma map_eq_self (x : R) : algebra_map R R x = x := rfl @[simp] lemma smul_eq_mul (x y : R) : x • y = x * y := rfl end id /-- Algebra over a subsemiring. -/ instance of_subsemiring (S : subsemiring R) : algebra S A := { smul := λ s x, (s : R) • x, commutes' := λ r x, algebra.commutes r x, smul_def' := λ r x, algebra.smul_def r x, .. (algebra_map R A).comp (subsemiring.subtype S) } /-- Algebra over a subring. -/ instance of_subring {R A : Type*} [comm_ring R] [ring A] [algebra R A] (S : subring R) : algebra S A := { smul := λ s x, (s : R) • x, commutes' := λ r x, algebra.commutes r x, smul_def' := λ r x, algebra.smul_def r x, .. (algebra_map R A).comp (subring.subtype S) } lemma algebra_map_of_subring {R : Type*} [comm_ring R] (S : subring R) : (algebra_map S R : S →+* R) = subring.subtype S := rfl lemma coe_algebra_map_of_subring {R : Type*} [comm_ring R] (S : subring R) : (algebra_map S R : S → R) = subtype.val := rfl lemma algebra_map_of_subring_apply {R : Type*} [comm_ring R] (S : subring R) (x : S) : algebra_map S R x = x := rfl /-- Algebra over a set that is closed under the ring operations. -/ instance of_is_subring {R A : Type*} [comm_ring R] [ring A] [algebra R A] (S : set R) [is_subring S] : algebra S A := algebra.of_subring S.to_subring lemma is_subring_coe_algebra_map_hom {R : Type*} [comm_ring R] (S : set R) [is_subring S] : (algebra_map S R : S →+* R) = is_subring.subtype S := rfl lemma is_subring_coe_algebra_map {R : Type*} [comm_ring R] (S : set R) [is_subring S] : (algebra_map S R : S → R) = subtype.val := rfl lemma is_subring_algebra_map_apply {R : Type*} [comm_ring R] (S : set R) [is_subring S] (x : S) : algebra_map S R x = x := rfl lemma set_range_subset {R : Type*} [comm_ring R] {T₁ T₂ : set R} [is_subring T₁] (hyp : T₁ ⊆ T₂) : set.range (algebra_map T₁ R) ⊆ T₂ := begin rintros x ⟨⟨t, ht⟩, rfl⟩, exact hyp ht, end variables (R A) /-- The multiplication in an algebra is a bilinear map. -/ def lmul : A →ₗ A →ₗ A := linear_map.mk₂ R (*) (λ x y z, add_mul x y z) (λ c x y, by rw [smul_def, smul_def, mul_assoc _ x y]) (λ x y z, mul_add x y z) (λ c x y, by rw [smul_def, smul_def, left_comm]) /-- The multiplication on the left in an algebra is a linear map. -/ def lmul_left (r : A) : A →ₗ A := lmul R A r /-- The multiplication on the right in an algebra is a linear map. -/ def lmul_right (r : A) : A →ₗ A := (lmul R A).flip r /-- Simultaneous multiplication on the left and right is a linear map. -/ def lmul_left_right (vw: A × A) : A →ₗ[R] A := (lmul_right R A vw.2).comp (lmul_left R A vw.1) /-- The multiplication map on an algebra, as an `R`-linear map from `A ⊗[R] A` to `A`. -/ def lmul' : A ⊗[R] A →ₗ[R] A := tensor_product.lift (algebra.lmul R A) variables {R A} @[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl @[simp] lemma lmul_left_apply (p q : A) : lmul_left R A p q = p * q := rfl @[simp] lemma lmul_right_apply (p q : A) : lmul_right R A p q = q * p := rfl @[simp] lemma lmul_left_right_apply (vw : A × A) (p : A) : lmul_left_right R A vw p = vw.1 * p * vw.2 := rfl @[simp] lemma lmul'_apply {x y} : algebra.lmul' R A (x ⊗ₜ y) = x * y := begin dsimp [algebra.lmul'], simp, end /-- Explicit characterization of the submonoid map in the case of an algebra. `S` is made explicit to help with type inference -/ def algebra_map_submonoid (S : Type*) [semiring S] [algebra R S] (M : submonoid R) : (submonoid S) := submonoid.map (algebra_map R S : R →* S) M lemma mem_algebra_map_submonoid_of_mem [algebra R S] {M : submonoid R} (x : M) : (algebra_map R S x) ∈ algebra_map_submonoid S M := set.mem_image_of_mem (algebra_map R S) x.2 instance linear_map.semimodule' (R : Type u) [comm_semiring R] (M : Type v) [add_comm_monoid M] [semimodule R M] (S : Type w) [comm_semiring S] [algebra R S] : semimodule S (M →ₗ[R] S) := { smul := λ s f, linear_map.llcomp _ _ _ _ (algebra.lmul R S s) f, one_smul := λ f, linear_map.ext $ λ x, one_mul _, mul_smul := λ s₁ s₂ f, linear_map.ext $ λ x, mul_assoc _ _ _, smul_add := λ s f g, linear_map.map_add _ _ _, smul_zero := λ s, linear_map.map_zero _, add_smul := λ s₁ s₂ f, linear_map.ext $ λ x, add_mul _ _ _, zero_smul := λ f, linear_map.ext $ λ x, zero_mul _ } end semiring section ring variables [comm_ring R] variables (R) /-- A `semiring` that is an `algebra` over a commutative ring carries a natural `ring` structure. -/ def semiring_to_ring [semiring A] [algebra R A] : ring A := { ..semimodule.add_comm_monoid_to_add_comm_group R, ..(infer_instance : semiring A) } variables {R} lemma mul_sub_algebra_map_commutes [ring A] [algebra R A] (x : A) (r : R) : x * (x - algebra_map R A r) = (x - algebra_map R A r) * x := by rw [mul_sub, ←commutes, sub_mul] lemma mul_sub_algebra_map_pow_commutes [ring A] [algebra R A] (x : A) (r : R) (n : ℕ) : x * (x - algebra_map R A r) ^ n = (x - algebra_map R A r) ^ n * x := begin induction n with n ih, { simp }, { rw [pow_succ, ←mul_assoc, mul_sub_algebra_map_commutes, mul_assoc, ih, ←mul_assoc], } end end ring end algebra namespace module instance endomorphism_algebra (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] : algebra R (M →ₗ[R] M) := { to_fun := λ r, r • linear_map.id, map_one' := one_smul _ _, map_zero' := zero_smul _ _, map_add' := λ r₁ r₂, add_smul _ _ _, map_mul' := λ r₁ r₂, by { ext x, simp [mul_smul] }, commutes' := by { intros, ext, simp }, smul_def' := by { intros, ext, simp } } lemma algebra_map_End_eq_smul_id (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] (a : R) : (algebra_map R (End R M)) a = a • linear_map.id := rfl lemma algebra_map_End_apply (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] (a : R) (m : M) : (algebra_map R (End R M)) a m = a • m := rfl lemma ker_algebra_map_End (K : Type u) (V : Type v) [field K] [add_comm_group V] [vector_space K V] (a : K) (ha : a ≠ 0) : ((algebra_map K (End K V)) a).ker = ⊥ := linear_map.ker_smul _ _ ha end module instance matrix_algebra (n : Type u) (R : Type v) [decidable_eq n] [fintype n] [comm_semiring R] : algebra R (matrix n n R) := { commutes' := by { intros, simp [matrix.scalar], }, smul_def' := by { intros, simp [matrix.scalar], }, ..(matrix.scalar n) } set_option old_structure_cmd true /-- Defining the homomorphism in the category R-Alg. -/ @[nolint has_inhabited_instance] structure alg_hom (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom A B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) run_cmd tactic.add_doc_string `alg_hom.to_ring_hom "Reinterpret an `alg_hom` as a `ring_hom`" infixr ` →ₐ `:25 := alg_hom _ notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁} section semiring variables [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D] variables [algebra R A] [algebra R B] [algebra R C] [algebra R D] instance : has_coe_to_fun (A →ₐ[R] B) := ⟨_, λ f, f.to_fun⟩ instance coe_ring_hom : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩ instance coe_monoid_hom : has_coe (A →ₐ[R] B) (A →* B) := ⟨λ f, ↑(f : A →+* B)⟩ instance coe_add_monoid_hom : has_coe (A →ₐ[R] B) (A →+ B) := ⟨λ f, ↑(f : A →+* B)⟩ @[simp, norm_cast] lemma coe_mk {f : A → B} (h₁ h₂ h₃ h₄ h₅) : ⇑(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := rfl @[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A →+* B) = f := rfl -- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute. @[norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →* B) = f := rfl -- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute. @[norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →+ B) = f := rfl variables (φ : A →ₐ[R] B) theorem coe_fn_inj ⦃φ₁ φ₂ : A →ₐ[R] B⦄ (H : ⇑φ₁ = φ₂) : φ₁ = φ₂ := by { cases φ₁, cases φ₂, congr, exact H } theorem coe_ring_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+* B)) := λ φ₁ φ₂ H, coe_fn_inj $ show ((φ₁ : (A →+* B)) : A → B) = ((φ₂ : (A →+* B)) : A → B), from congr_arg _ H theorem coe_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →* B)) := ring_hom.coe_monoid_hom_injective.comp coe_ring_hom_injective theorem coe_add_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+ B)) := ring_hom.coe_add_monoid_hom_injective.comp coe_ring_hom_injective @[ext] theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ := coe_fn_inj $ funext H theorem ext_iff {φ₁ φ₂ : A →ₐ[R] B} : φ₁ = φ₂ ↔ ∀ x, φ₁ x = φ₂ x := ⟨by { rintro rfl x, refl }, ext⟩ @[simp] theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r theorem comp_algebra_map : (φ : A →+* B).comp (algebra_map R A) = algebra_map R B := ring_hom.ext $ φ.commutes @[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s := φ.to_ring_hom.map_add r s @[simp] lemma map_zero : φ 0 = 0 := φ.to_ring_hom.map_zero @[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y := φ.to_ring_hom.map_mul x y @[simp] lemma map_one : φ 1 = 1 := φ.to_ring_hom.map_one @[simp] lemma map_smul (r : R) (x : A) : φ (r • x) = r • φ x := by simp only [algebra.smul_def, map_mul, commutes] @[simp] lemma map_pow (x : A) (n : ℕ) : φ (x ^ n) = (φ x) ^ n := φ.to_ring_hom.map_pow x n lemma map_sum {ι : Type*} (f : ι → A) (s : finset ι) : φ (∑ x in s, f x) = ∑ x in s, φ (f x) := φ.to_ring_hom.map_sum f s @[simp] lemma map_nat_cast (n : ℕ) : φ n = n := φ.to_ring_hom.map_nat_cast n @[simp] lemma map_bit0 (x) : φ (bit0 x) = bit0 (φ x) := φ.to_ring_hom.map_bit0 x @[simp] lemma map_bit1 (x) : φ (bit1 x) = bit1 (φ x) := φ.to_ring_hom.map_bit1 x section variables (R A) /-- Identity map as an `alg_hom`. -/ protected def id : A →ₐ[R] A := { commutes' := λ _, rfl, ..ring_hom.id A } end @[simp] lemma id_apply (p : A) : alg_hom.id R A p = p := rfl /-- Composition of algebra homeomorphisms. -/ def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C := { commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl, .. φ₁.to_ring_hom.comp ↑φ₂ } @[simp] lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) : φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl @[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ := ext $ λ x, rfl @[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ := ext $ λ x, rfl theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) : (φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) := ext $ λ x, rfl /-- R-Alg ⥤ R-Mod -/ def to_linear_map : A →ₗ B := { to_fun := φ, map_add' := φ.map_add, map_smul' := φ.map_smul } @[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl theorem to_linear_map_inj {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁.to_linear_map = φ₂.to_linear_map) : φ₁ = φ₂ := ext $ λ x, show φ₁.to_linear_map x = φ₂.to_linear_map x, by rw H @[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) : (g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [comm_semiring B] variables [algebra R A] [algebra R B] variables (φ : A →ₐ[R] B) lemma map_prod {ι : Type*} (f : ι → A) (s : finset ι) : φ (∏ x in s, f x) = ∏ x in s, φ (f x) := φ.to_ring_hom.map_prod f s end comm_semiring section ring variables [comm_ring R] [ring A] [ring B] [ring C] variables [algebra R A] [algebra R B] [algebra R C] (φ : A →ₐ[R] B) @[simp] lemma map_neg (x) : φ (-x) = -φ x := φ.to_ring_hom.map_neg x @[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y := φ.to_ring_hom.map_sub x y end ring section division_ring variables [comm_ring R] [division_ring A] [division_ring B] variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B) @[simp] lemma map_inv (x) : φ (x⁻¹) = (φ x)⁻¹ := φ.to_ring_hom.map_inv x @[simp] lemma map_div (x y) : φ (x / y) = φ x / φ y := φ.to_ring_hom.map_div x y end division_ring theorem injective_iff {R A B : Type*} [comm_semiring R] [ring A] [semiring B] [algebra R A] [algebra R B] (f : A →ₐ[R] B) : function.injective f ↔ (∀ x, f x = 0 → x = 0) := ring_hom.injective_iff (f : A →+* B) end alg_hom set_option old_structure_cmd true /-- An equivalence of algebras is an equivalence of rings commuting with the actions of scalars. -/ structure alg_equiv (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends A ≃ B, A ≃* B, A ≃+ B, A ≃+* B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) attribute [nolint doc_blame] alg_equiv.to_ring_equiv attribute [nolint doc_blame] alg_equiv.to_equiv attribute [nolint doc_blame] alg_equiv.to_add_equiv attribute [nolint doc_blame] alg_equiv.to_mul_equiv notation A ` ≃ₐ[`:50 R `] ` A' := alg_equiv R A A' namespace alg_equiv variables {R : Type u} {A₁ : Type v} {A₂ : Type w} {A₃ : Type u₁} variables [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃] variables [algebra R A₁] [algebra R A₂] [algebra R A₃] variables (e : A₁ ≃ₐ[R] A₂) instance : has_coe_to_fun (A₁ ≃ₐ[R] A₂) := ⟨_, alg_equiv.to_fun⟩ @[ext] lemma ext {f g : A₁ ≃ₐ[R] A₂} (h : ∀ a, f a = g a) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end lemma coe_fun_injective : @function.injective (A₁ ≃ₐ[R] A₂) (A₁ → A₂) (λ e, (e : A₁ → A₂)) := begin intros f g w, ext, exact congr_fun w a, end instance has_coe_to_ring_equiv : has_coe (A₁ ≃ₐ[R] A₂) (A₁ ≃+* A₂) := ⟨alg_equiv.to_ring_equiv⟩ @[simp] lemma mk_apply {to_fun inv_fun left_inv right_inv map_mul map_add commutes a} : (⟨to_fun, inv_fun, left_inv, right_inv, map_mul, map_add, commutes⟩ : A₁ ≃ₐ[R] A₂) a = to_fun a := rfl @[simp] lemma to_fun_apply {e : A₁ ≃ₐ[R] A₂} {a : A₁} : e.to_fun a = e a := rfl @[simp, norm_cast] lemma coe_ring_equiv : ((e : A₁ ≃+* A₂) : A₁ → A₂) = e := rfl lemma coe_ring_equiv_injective : function.injective (λ e : A₁ ≃ₐ[R] A₂, (e : A₁ ≃+* A₂)) := begin intros f g w, ext, replace w : ((f : A₁ ≃+* A₂) : A₁ → A₂) = ((g : A₁ ≃+* A₂) : A₁ → A₂) := congr_arg (λ e : A₁ ≃+* A₂, (e : A₁ → A₂)) w, exact congr_fun w a, end @[simp] lemma map_add : ∀ x y, e (x + y) = e x + e y := e.to_add_equiv.map_add @[simp] lemma map_zero : e 0 = 0 := e.to_add_equiv.map_zero @[simp] lemma map_mul : ∀ x y, e (x * y) = (e x) * (e y) := e.to_mul_equiv.map_mul @[simp] lemma map_one : e 1 = 1 := e.to_mul_equiv.map_one @[simp] lemma commutes : ∀ (r : R), e (algebra_map R A₁ r) = algebra_map R A₂ r := e.commutes' @[simp] lemma map_neg {A₁ : Type v} {A₂ : Type w} [ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (-x) = -(e x) := e.to_add_equiv.map_neg @[simp] lemma map_sub {A₁ : Type v} {A₂ : Type w} [ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x - y) = e x - e y := e.to_add_equiv.map_sub lemma map_sum {ι : Type*} (f : ι → A₁) (s : finset ι) : e (∑ x in s, f x) = ∑ x in s, e (f x) := e.to_add_equiv.map_sum f s /-- Interpret an algebra equivalence as an algebra homomorphism. This definition is included for symmetry with the other `to_*_hom` projections. The `simp` normal form is to use the coercion of the `has_coe_to_alg_hom` instance. -/ def to_alg_hom : A₁ →ₐ[R] A₂ := { map_one' := e.map_one, map_zero' := e.map_zero, ..e } instance has_coe_to_alg_hom : has_coe (A₁ ≃ₐ[R] A₂) (A₁ →ₐ[R] A₂) := ⟨to_alg_hom⟩ @[simp] lemma to_alg_hom_eq_coe : e.to_alg_hom = e := rfl @[simp, norm_cast] lemma coe_alg_hom : ((e : A₁ →ₐ[R] A₂) : A₁ → A₂) = e := rfl lemma injective : function.injective e := e.to_equiv.injective lemma surjective : function.surjective e := e.to_equiv.surjective lemma bijective : function.bijective e := e.to_equiv.bijective instance : has_one (A₁ ≃ₐ[R] A₁) := ⟨{commutes' := λ r, rfl, ..(1 : A₁ ≃+* A₁)}⟩ instance : inhabited (A₁ ≃ₐ[R] A₁) := ⟨1⟩ /-- Algebra equivalences are reflexive. -/ @[refl] def refl : A₁ ≃ₐ[R] A₁ := 1 @[simp] lemma coe_refl : (@refl R A₁ _ _ _ : A₁ →ₐ[R] A₁) = alg_hom.id R A₁ := alg_hom.ext (λ x, rfl) /-- Algebra equivalences are symmetric. -/ @[symm] def symm (e : A₁ ≃ₐ[R] A₂) : A₂ ≃ₐ[R] A₁ := { commutes' := λ r, by { rw ←e.to_ring_equiv.symm_apply_apply (algebra_map R A₁ r), congr, change _ = e _, rw e.commutes, }, ..e.to_ring_equiv.symm, } @[simp] lemma inv_fun_apply {e : A₁ ≃ₐ[R] A₂} {a : A₂} : e.inv_fun a = e.symm a := rfl @[simp] lemma symm_symm {e : A₁ ≃ₐ[R] A₂} : e.symm.symm = e := by { ext, refl, } /-- Algebra equivalences are transitive. -/ @[trans] def trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : A₁ ≃ₐ[R] A₃ := { commutes' := λ r, show e₂.to_fun (e₁.to_fun _) = _, by rw [e₁.commutes', e₂.commutes'], ..(e₁.to_ring_equiv.trans e₂.to_ring_equiv), } @[simp] lemma apply_symm_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply @[simp] lemma trans_apply (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) (x : A₁) : (e₁.trans e₂) x = e₂ (e₁ x) := rfl @[simp] lemma comp_symm (e : A₁ ≃ₐ[R] A₂) : alg_hom.comp (e : A₁ →ₐ[R] A₂) ↑e.symm = alg_hom.id R A₂ := by { ext, simp } @[simp] lemma symm_comp (e : A₁ ≃ₐ[R] A₂) : alg_hom.comp ↑e.symm (e : A₁ →ₐ[R] A₂) = alg_hom.id R A₁ := by { ext, simp } /-- If an algebra morphism has an inverse, it is a algebra isomorphism. -/ def of_alg_hom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ : f.comp g = alg_hom.id R A₂) (h₂ : g.comp f = alg_hom.id R A₁) : A₁ ≃ₐ[R] A₂ := { inv_fun := g, left_inv := alg_hom.ext_iff.1 h₂, right_inv := alg_hom.ext_iff.1 h₁, ..f } /-- Promotes a bijective algebra homomorphism to an algebra equivalence. -/ noncomputable def of_bijective (f : A₁ →ₐ[R] A₂) (hf : function.bijective f) : A₁ ≃ₐ[R] A₂ := { .. ring_equiv.of_bijective (f : A₁ →+* A₂) hf, .. f } /-- Forgetting the multiplicative structures, an equivalence of algebras is a linear equivalence. -/ def to_linear_equiv (e : A₁ ≃ₐ[R] A₂) : A₁ ≃ₗ[R] A₂ := { to_fun := e.to_fun, map_add' := λ x y, by simp, map_smul' := λ r x, by simp [algebra.smul_def''], inv_fun := e.symm.to_fun, left_inv := e.left_inv, right_inv := e.right_inv, } @[simp] lemma to_linear_equiv_apply (e : A₁ ≃ₐ[R] A₂) (x : A₁) : e.to_linear_equiv x = e x := rfl theorem to_linear_equiv_inj {e₁ e₂ : A₁ ≃ₐ[R] A₂} (H : e₁.to_linear_equiv = e₂.to_linear_equiv) : e₁ = e₂ := ext $ λ x, show e₁.to_linear_equiv x = e₂.to_linear_equiv x, by rw H /-- Interpret an algebra equivalence as a linear map. -/ def to_linear_map : A₁ →ₗ[R] A₂ := e.to_alg_hom.to_linear_map @[simp] lemma to_alg_hom_to_linear_map : (e : A₁ →ₐ[R] A₂).to_linear_map = e.to_linear_map := rfl @[simp] lemma to_linear_equiv_to_linear_map : e.to_linear_equiv.to_linear_map = e.to_linear_map := rfl @[simp] lemma to_linear_map_apply (x : A₁) : e.to_linear_map x = e x := rfl theorem to_linear_map_inj {e₁ e₂ : A₁ ≃ₐ[R] A₂} (H : e₁.to_linear_map = e₂.to_linear_map) : e₁ = e₂ := ext $ λ x, show e₁.to_linear_map x = e₂.to_linear_map x, by rw H @[simp] lemma trans_to_linear_map (f : A₁ ≃ₐ[R] A₂) (g : A₂ ≃ₐ[R] A₃) : (f.trans g).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl end alg_equiv namespace algebra variables (R : Type u) (S : Type v) (A : Type w) include R S A /-- `comap R S A` is a type alias for `A`, and has an R-algebra structure defined on it when `algebra R S` and `algebra S A`. If `S` is an `R`-algebra and `A` is an `S`-algebra then `algebra.comap.algebra R S A` can be used to provide `A` with a structure of an `R`-algebra. Other than that, `algebra.comap` is now deprecated and replaced with `is_scalar_tower`. -/ /- This is done to avoid a type class search with meta-variables `algebra R ?m_1` and `algebra ?m_1 A -/ /- The `nolint` attribute is added because it has unused arguments `R` and `S`, but these are necessary for synthesizing the appropriate type classes -/ @[nolint unused_arguments] def comap : Type w := A instance comap.inhabited [h : inhabited A] : inhabited (comap R S A) := h instance comap.semiring [h : semiring A] : semiring (comap R S A) := h instance comap.ring [h : ring A] : ring (comap R S A) := h instance comap.comm_semiring [h : comm_semiring A] : comm_semiring (comap R S A) := h instance comap.comm_ring [h : comm_ring A] : comm_ring (comap R S A) := h instance comap.algebra' [comm_semiring S] [semiring A] [h : algebra S A] : algebra S (comap R S A) := h /-- Identity homomorphism `A →ₐ[S] comap R S A`. -/ def comap.to_comap [comm_semiring S] [semiring A] [algebra S A] : A →ₐ[S] comap R S A := alg_hom.id S A /-- Identity homomorphism `comap R S A →ₐ[S] A`. -/ def comap.of_comap [comm_semiring S] [semiring A] [algebra S A] : comap R S A →ₐ[S] A := alg_hom.id S A variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] /-- `R ⟶ S` induces `S-Alg ⥤ R-Alg` -/ instance comap.algebra : algebra R (comap R S A) := { smul := λ r x, (algebra_map R S r • x : A), commutes' := λ r x, algebra.commutes _ _, smul_def' := λ _ _, algebra.smul_def _ _, .. (algebra_map S A).comp (algebra_map R S) } /-- Embedding of `S` into `comap R S A`. -/ def to_comap : S →ₐ[R] comap R S A := { commutes' := λ r, rfl, .. algebra_map S A } theorem to_comap_apply (x) : to_comap R S A x = algebra_map S A x := rfl end algebra namespace alg_hom variables {R : Type u} {S : Type v} {A : Type w} {B : Type u₁} variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] (φ : A →ₐ[S] B) include R /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def comap : algebra.comap R S A →ₐ[R] algebra.comap R S B := { commutes' := λ r, φ.commutes (algebra_map R S r) ..φ } end alg_hom namespace rat instance algebra_rat {α} [division_ring α] [char_zero α] : algebra ℚ α := (rat.cast_hom α).to_algebra' $ λ r x, r.cast_commute x end rat namespace algebra variables (R : Type u) (A : Type v) variables [comm_semiring R] [semiring A] [algebra R A] /-- `algebra_map` as an `alg_hom`. -/ def of_id : R →ₐ[R] A := { commutes' := λ _, rfl, .. algebra_map R A } variables {R} theorem of_id_apply (r) : of_id R A r = algebra_map R A r := rfl end algebra section nat variables (R : Type*) [semiring R] /-- Reinterpret a `ring_hom` as an `ℕ`-algebra homomorphism. -/ def alg_hom_nat {R : Type u} [semiring R] [algebra ℕ R] {S : Type v} [semiring S] [algebra ℕ S] (f : R →+* S) : R →ₐ[ℕ] S := { commutes' := λ i, show f _ = _, by simp, .. f } /-- Semiring ⥤ ℕ-Alg -/ instance algebra_nat : algebra ℕ R := { commutes' := nat.cast_commute, smul_def' := λ _ _, nsmul_eq_mul _ _, .. nat.cast_ring_hom R } section span_nat open submodule lemma span_nat_eq_add_group_closure (s : set R) : (span ℕ s).to_add_submonoid = add_submonoid.closure s := eq.symm $ add_submonoid.closure_eq_of_le subset_span $ λ x hx, span_induction hx (λ x hx, add_submonoid.subset_closure hx) (add_submonoid.zero_mem _) (λ _ _, add_submonoid.add_mem _) (λ _ _ _, add_submonoid.nsmul_mem _ ‹_› _) @[simp] lemma span_nat_eq (s : add_submonoid R) : (span ℕ (s : set R)).to_add_submonoid = s := by rw [span_nat_eq_add_group_closure, s.closure_eq] end span_nat end nat section int variables (R : Type*) [ring R] /-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/ def alg_hom_int {R : Type u} [comm_ring R] [algebra ℤ R] {S : Type v} [comm_ring S] [algebra ℤ S] (f : R →+* S) : R →ₐ[ℤ] S := { commutes' := λ i, show f _ = _, by simp, .. f } /-- Ring ⥤ ℤ-Alg -/ instance algebra_int : algebra ℤ R := { commutes' := int.cast_commute, smul_def' := λ _ _, gsmul_eq_mul _ _, .. int.cast_ring_hom R } /-- Promote a ring homomorphisms to a `ℤ`-algebra homomorphism. -/ def ring_hom.to_int_alg_hom {R S : Type*} [ring R] [ring S] (f : R →+* S) : R →ₐ[ℤ] S := { commutes' := λ n, by simp, .. f } variables {R} section variables {S : Type*} [ring S] instance int_algebra_subsingleton : subsingleton (algebra ℤ S) := ⟨λ P Q, by { ext, simp, }⟩ end section variables {S : Type*} [semiring S] instance nat_algebra_subsingleton : subsingleton (algebra ℕ S) := ⟨λ P Q, by { ext, simp, }⟩ end section span_int open submodule lemma span_int_eq_add_group_closure (s : set R) : (span ℤ s).to_add_subgroup = add_subgroup.closure s := eq.symm $ add_subgroup.closure_eq_of_le _ subset_span $ λ x hx, span_induction hx (λ x hx, add_subgroup.subset_closure hx) (add_subgroup.zero_mem _) (λ _ _, add_subgroup.add_mem _) (λ _ _ _, add_subgroup.gsmul_mem _ ‹_› _) @[simp] lemma span_int_eq (s : add_subgroup R) : (span ℤ (s : set R)).to_add_subgroup = s := by rw [span_int_eq_add_group_closure, s.closure_eq] end span_int end int /-! The R-algebra structure on `Π i : I, A i` when each `A i` is an R-algebra. We couldn't set this up back in `algebra.pi_instances` because this file imports it. -/ namespace pi variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) variables (I f) instance algebra (α) {r : comm_semiring α} [s : ∀ i, semiring (f i)] [∀ i, algebra α (f i)] : algebra α (Π i : I, f i) := { commutes' := λ a f, begin ext, simp [algebra.commutes], end, smul_def' := λ a f, begin ext, simp [algebra.smul_def''], end, ..pi.ring_hom (λ i, algebra_map α (f i)) } @[simp] lemma algebra_map_apply (α) {r : comm_semiring α} [s : ∀ i, semiring (f i)] [∀ i, algebra α (f i)] (a : α) (i : I) : algebra_map α (Π i, f i) a i = algebra_map α (f i) a := rfl -- One could also build a `Π i, R i`-algebra structure on `Π i, A i`, -- when each `A i` is an `R i`-algebra, although I'm not sure that it's useful. end pi section is_scalar_tower variables {R : Type*} [comm_semiring R] variables (A : Type*) [semiring A] [algebra R A] variables {M : Type*} [add_comm_monoid M] [semimodule A M] [semimodule R M] [is_scalar_tower R A M] variables {N : Type*} [add_comm_monoid N] [semimodule A N] [semimodule R N] [is_scalar_tower R A N] lemma algebra_compatible_smul (r : R) (m : M) : r • m = ((algebra_map R A) r) • m := by rw [←(one_smul A m), ←smul_assoc, algebra.smul_def, mul_one, one_smul] variable {A} lemma smul_algebra_smul_comm (r : R) (a : A) (m : M) : a • r • m = r • a • m := by rw [algebra_compatible_smul A r (a • m), smul_smul, algebra.commutes, mul_smul, ←algebra_compatible_smul] @[simp] lemma map_smul_eq_smul_map (f : M →ₗ[A] N) (r : R) (m : M) : f (r • m) = r • f m := by rw [algebra_compatible_smul A r m, linear_map.map_smul, ←algebra_compatible_smul A r (f m)] instance : has_coe (M →ₗ[A] N) (M →ₗ[R] N) := ⟨λ f, ⟨f.to_fun, λ x y, f.map_add' x y, λ r n, map_smul_eq_smul_map _ _ _⟩⟩ end is_scalar_tower section restrict_scalars /- In this section, we describe restriction of scalars: if `S` is an algebra over `R`, then `S`-modules are also `R`-modules. -/ section semimodule variables (R : Type*) [comm_semiring R] (S : Type*) [semiring S] [algebra R S] variables (E : Type*) [add_comm_monoid E] [semimodule S E] variables {F : Type*} [add_comm_monoid F] [semimodule S F] /-- When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a module structure over `R`, called `module.restrict_scalars' R S E`. We do not register this as an instance as `S` can not be inferred. -/ def semimodule.restrict_scalars' : semimodule R E := { smul := λ c x, (algebra_map R S c) • x, one_smul := by simp, mul_smul := by simp [mul_smul], smul_add := by simp [smul_add], smul_zero := by simp [smul_zero], add_smul := by simp [add_smul], zero_smul := by simp [zero_smul] } /-- When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a module structure over `R`, provided as a type synonym `module.restrict_scalars R S E := E`. When the `R`-module structure on `E` is registered directly (using `module.restrict_scalars'` for instance, or for `S = ℂ` and `R = ℝ`), theorems on `module.restrict_scalars R S E` can be directly applied to `E` as these types are the same for the kernel. -/ @[nolint unused_arguments] def semimodule.restrict_scalars (R : Type*) (S : Type*) (E : Type*) : Type* := E instance (R : Type*) (S : Type*) (E : Type*) [I : inhabited E] : inhabited (semimodule.restrict_scalars R S E) := I instance (R : Type*) (S : Type*) (E : Type*) [I : add_comm_monoid E] : add_comm_monoid (semimodule.restrict_scalars R S E) := I instance semimodule.restrict_scalars.module_orig (R : Type*) (S : Type*) [semiring S] (E : Type*) [add_comm_monoid E] [I : semimodule S E] : semimodule S (semimodule.restrict_scalars R S E) := I instance : semimodule R (semimodule.restrict_scalars R S E) := (semimodule.restrict_scalars' R S E : semimodule R E) lemma semimodule.restrict_scalars_smul_def (c : R) (x : semimodule.restrict_scalars R S E) : c • x = ((algebra_map R S c) • x : E) := rfl /-- `module.restrict_scalars R S S` is `R`-linearly equivalent to the original algebra `S`. Unfortunately these structures are not generally definitionally equal: the `R`-module structure on `S` is part of the data of `S`, while the `R`-module structure on `module.restrict_scalars R S S` comes from the ring homomorphism `R →+* S`, which is a separate part of the data of `S`. The field `algebra.smul_def'` gives the equation we need here. -/ def algebra.restrict_scalars_equiv : (semimodule.restrict_scalars R S S) ≃ₗ[R] S := { to_fun := λ s, s, inv_fun := λ s, s, left_inv := λ s, rfl, right_inv := λ s, rfl, map_add' := λ x y, rfl, map_smul' := λ c x, (algebra.smul_def' _ _).symm, } @[simp] lemma algebra.restrict_scalars_equiv_apply (s : S) : algebra.restrict_scalars_equiv R S s = s := rfl @[simp] lemma algebra.restrict_scalars_equiv_symm_apply (s : S) : (algebra.restrict_scalars_equiv R S).symm s = s := rfl variables {S E} open semimodule instance : is_scalar_tower R S (restrict_scalars R S E) := ⟨λ r s e, by { rw [algebra.smul_def, mul_smul], refl }⟩ /-- `V.restrict_scalars R` is the `R`-submodule of the `R`-module given by restriction of scalars, corresponding to `V`, an `S`-submodule of the original `S`-module. -/ @[simps] def submodule.restrict_scalars (V : submodule S E) : submodule R (restrict_scalars R S E) := { carrier := V.carrier, zero_mem' := V.zero_mem, smul_mem' := λ c e h, V.smul_mem _ h, add_mem' := λ x y hx hy, V.add_mem hx hy, } @[simp] lemma submodule.restrict_scalars_mem (V : submodule S E) (e : E) : e ∈ V.restrict_scalars R ↔ e ∈ V := iff.refl _ @[simp] lemma submodule.restrict_scalars_bot : submodule.restrict_scalars R (⊥ : submodule S E) = ⊥ := rfl @[simp] lemma submodule.restrict_scalars_top : submodule.restrict_scalars R (⊤ : submodule S E) = ⊤ := rfl /-- The `R`-linear map induced by an `S`-linear map when `S` is an algebra over `R`. -/ def linear_map.restrict_scalars (f : E →ₗ[S] F) : (restrict_scalars R S E) →ₗ[R] (restrict_scalars R S F) := { to_fun := f.to_fun, map_add' := λx y, f.map_add x y, map_smul' := λc x, f.map_smul (algebra_map R S c) x } @[simp, norm_cast squash] lemma linear_map.coe_restrict_scalars_eq_coe (f : E →ₗ[S] F) : (f.restrict_scalars R : E → F) = f := rfl @[simp] lemma restrict_scalars_ker (f : E →ₗ[S] F) : (f.restrict_scalars R).ker = submodule.restrict_scalars R f.ker := rfl /-- `A`-linearly coerce a `R`-linear map from `M` to `R` to a function, given an algebra `A` over a commutative semiring `R` and `M` a semimodule over `R`. -/ def linear_map.lto_fun (R : Type u) (M : Type v) (A : Type w) [comm_semiring R] [add_comm_monoid M] [semimodule R M] [comm_ring A] [algebra R A] : (M →ₗ[R] A) →ₗ[A] (M → A) := { to_fun := linear_map.to_fun, map_add' := λ f g, rfl, map_smul' := λ c f, rfl } end semimodule section module instance (R : Type*) (S : Type*) (E : Type*) [I : add_comm_group E] : add_comm_group (semimodule.restrict_scalars R S E) := I end module end restrict_scalars section extend_scalars /-! When `V` is an `R`-module and `W` is an `S`-module, where `S` is an algebra over `R`, then the collection of `R`-linear maps from `V` to `W` admits an `S`-module structure, given by multiplication in the target -/ variables (R : Type*) [comm_semiring R] (S : Type*) [semiring S] [algebra R S] (V : Type*) [add_comm_monoid V] [semimodule R V] (W : Type*) [add_comm_monoid W] [semimodule S W] /-- The set of `R`-linear maps admits an `S`-action by left multiplication -/ instance linear_map.has_scalar_extend_scalars : has_scalar S (V →ₗ[R] (semimodule.restrict_scalars R S W)) := { smul := λ r f, { to_fun := λ v, r • f v, map_add' := by simp [smul_add], map_smul' := λ c x, by rw [linear_map.map_smul, smul_algebra_smul_comm] }} /-- The set of `R`-linear maps is an `S`-module-/ instance linear_map.module_extend_scalars : semimodule S (V →ₗ[R] (semimodule.restrict_scalars R S W)) := { one_smul := λ f, by { ext v, simp [(•)] }, mul_smul := λ r r' f, by { ext v, simp [(•), smul_smul] }, smul_add := λ r f g, by { ext v, simp [(•), smul_add] }, smul_zero := λ r, by { ext v, simp [(•)] }, add_smul := λ r r' f, by { ext v, simp [(•), add_smul] }, zero_smul := λ f, by { ext v, simp [(•)] } } variables {R S V W} /-- When `f` is a linear map taking values in `S`, then `λb, f b • x` is a linear map. -/ def smul_algebra_right (f : V →ₗ[R] S) (x : semimodule.restrict_scalars R S W) : V →ₗ[R] (semimodule.restrict_scalars R S W) := { to_fun := λb, f b • x, map_add' := by simp [add_smul], map_smul' := λ b y, by { simp [algebra.smul_def, ← smul_smul], refl } } @[simp] theorem smul_algebra_right_apply (f : V →ₗ[R] S) (x : semimodule.restrict_scalars R S W) (c : V) : smul_algebra_right f x c = f c • x := rfl end extend_scalars /-! When `V` and `W` are `S`-modules, for some `R`-algebra `S`, the collection of `S`-linear maps from `V` to `W` forms an `R`-module. (But not generally an `S`-module, because `S` may be non-commutative.) -/ section module_of_linear_maps variables (R : Type*) [comm_semiring R] (S : Type*) [semiring S] [algebra R S] (V : Type*) [add_comm_monoid V] [semimodule S V] (W : Type*) [add_comm_monoid W] [semimodule S W] /-- For `r : R`, and `f : V →ₗ[S] W` (where `S` is an `R`-algebra) we define `(r • f) v = f (r • v)`. -/ def linear_map_algebra_has_scalar : has_scalar R (V →ₗ[S] W) := { smul := λ r f, { to_fun := λ v, f ((algebra_map R S r) • v), map_add' := λ x y, by simp [smul_add], map_smul' := λ s v, by simp [smul_smul, algebra.commutes], } } local attribute [instance] linear_map_algebra_has_scalar /-- The `R`-module structure on `S`-linear maps, for `S` an `R`-algebra. -/ def linear_map_algebra_module : semimodule R (V →ₗ[S] W) := { one_smul := λ f, begin ext v, dsimp [(•)], simp, end, mul_smul := λ r r' f, begin ext v, dsimp [(•)], rw [linear_map.map_smul, linear_map.map_smul, linear_map.map_smul, ring_hom.map_mul, smul_smul, algebra.commutes], end, smul_zero := λ r, by { ext v, dsimp [(•)], refl, }, smul_add := λ r f g, by { ext v, dsimp [(•)], simp [linear_map.map_add], }, zero_smul := λ f, by { ext v, dsimp [(•)], simp, }, add_smul := λ r r' f, by { ext v, dsimp [(•)], simp [add_smul], }, } local attribute [instance] linear_map_algebra_module variables {R S V W} @[simp] lemma linear_map_algebra_module.smul_apply (c : R) (f : V →ₗ[S] W) (v : V) : (c • f) v = (c • (f v) : semimodule.restrict_scalars R S W) := begin erw [linear_map.map_smul], refl, end end module_of_linear_maps
2e14262aa483a5efa3f3f06679c9a965f9fe49e9
b66669ef1ec06ddbd9526fe3afe0a68566dfbad3
/src/wireworld.lean
bce2d21ce2c294f0e94b2c9eacff856a3a7eda20
[ "MIT" ]
permissive
FerdoSil/LatticesAndCellularAutomata
40185a9099bb3cf1371c85f1ca33a17c2e26fecb
2a69d2e74a231addf0e446dca86ef90d50d60218
refs/heads/master
1,587,683,992,072
1,586,018,471,000
1,586,018,471,000
171,533,028
0
0
null
null
null
null
UTF-8
Lean
false
false
7,071
lean
-- Implementation of Wireworld. -- Cell states 'cellT' are represented as follows. -- 'empty' -- 'ehead' for electron head -- 'etail' for electron tail -- 'condu' for conductor -- The definition 'mk_hpp' builds an instance of HPP -- from an initial configuration of cell states. import cell_automaton utils data.vector open utils namespace ww section ww -- empty | electron head | electron tail | conductor @[derive decidable_eq] inductive cellT | empty | ehead | etail | condu open cellT def cellT_str : cellT → string | empty := " " | ehead := "H" | etail := "T" | condu := "X" instance cellT_to_str : has_to_string cellT := ⟨cellT_str⟩ instance cellT_repr : has_repr cellT := ⟨cellT_str⟩ attribute [reducible] def ww := cell_automaton cellT def step : cellT → ℕ → cellT | empty _ := empty | ehead _ := etail | etail _ := condu | condu c := if c = 1 ∨ c = 2 then ehead else condu def ww_step (cell : cellT) (neigh : list cellT) := step cell $ count_at_single neigh ehead def mk_ww (g : vec_grid₀ cellT) : ww := ⟨g, empty, cell_automatons.moore, ww_step, cell_automatons.ext_id⟩ def wire_g := vec_grid₀.mk ⟨1, 5, dec_trivial, ⟨[etail, ehead, condu, condu, condu], rfl⟩⟩ ⟨0, 1⟩ def wire : ww := mk_ww wire_g def or_g_10 := vec_grid₀.mk ⟨5, 6, dec_trivial, ⟨[etail, ehead, empty, empty, empty, empty, empty, empty, condu, empty, empty, empty, empty, condu, condu, condu, condu, condu, empty, empty, condu, empty, empty, empty, condu, condu, empty, empty, empty, empty], rfl⟩⟩ ⟨0, 1⟩ def or_10 : ww := mk_ww or_g_10 def or_g_01 := vec_grid₀.mk ⟨5, 6, dec_trivial, ⟨[condu, condu, empty, empty, empty, empty, empty, empty, condu, empty, empty, empty, empty, condu, condu, condu, condu, condu, empty, empty, condu, empty, empty, empty, etail, ehead, empty, empty, empty, empty], rfl⟩⟩ ⟨0, 1⟩ def or_01 : ww := mk_ww or_g_01 open cardinals section ww_or def or_gate' := vec_grid₀.mk ⟨5, 6, dec_trivial, ⟨[condu, condu, empty, empty, empty, empty, empty, empty, condu, empty, empty, empty, empty, condu, condu, condu, condu, condu, empty, empty, condu, empty, empty, empty, etail, ehead, empty, empty, empty, empty], rfl⟩⟩ ⟨-5, -5⟩ def or_gate : ww := mk_ww or_gate' def write_input (i₁ : bool) (i₂ : bool) := let (b₁, b₂) := if i₁ then (etail, ehead) else (condu, condu) in let (b₃, b₄) := if i₂ then (etail, ehead) else (condu, condu) in mod_many [(⟨-5, -10⟩, b₁), (⟨-4, -10⟩, b₂), (⟨-5, -6⟩, b₃), (⟨-4, -6⟩, b₄)] or_gate def sim_or (i₁ i₂ : bool) : bool := let sim := step_n (write_input i₁ i₂) 3 in yield_at sim ⟨-8, -2⟩ = etail ∧ yield_at sim ⟨-8, -1⟩ = ehead end ww_or section ww_xor inductive direction | N | W | E | S open direction structure inout := (p₁ : point) (p₂ : point) (dir : direction) structure ww₁ := (aut : ww) (ins : list inout) (ous : list inout) def str_of_ww₁ : ww₁ → string | ⟨aut, _, _⟩ := to_string aut instance ww₁_to_str : has_to_string ww₁ := ⟨str_of_ww₁⟩ instance ww₁_repr : has_repr ww₁ := ⟨str_of_ww₁⟩ def mk_ww₁ (g : vec_grid₀ cellT) (inputs outputs : list inout) : ww₁ := ⟨mk_ww g, inputs, outputs⟩ def write (a : ww₁) (n : ℕ) (b : bool) : ww₁ := let input := list.nth a.ins n in match input with | none := a | some ⟨p₁, p₂, dir⟩ := if b then match dir with | N := ww₁.mk (mod_many [(up p₁ p₂, ehead), (down p₁ p₂, etail)] a.aut) a.ins a.ous | S := ww₁.mk (mod_many [(down p₁ p₂, ehead), (up p₁ p₂, etail)] a.aut) a.ins a.ous | W := ww₁.mk (mod_many [(left p₁ p₂, ehead), (right p₁ p₂, etail)] a.aut) a.ins a.ous | E := ww₁.mk (mod_many [(right p₁ p₂, ehead), (left p₁ p₂, etail)] a.aut) a.ins a.ous end else ww₁.mk (mod_many [(p₁, condu), (p₂, condu)] a.aut) a.ins a.ous end def read (a : ww₁) (n : ℕ) : bool := let output := list.nth a.ous n in match output with | none := ff | some ⟨p₁, p₂, dir⟩ := match dir with | N := yield_at a.aut (up p₁ p₂) = ehead ∧ yield_at a.aut (down p₁ p₂) = etail | S := yield_at a.aut (up p₁ p₂) = etail ∧ yield_at a.aut (down p₁ p₂) = ehead | W := yield_at a.aut (left p₁ p₂) = ehead ∧ yield_at a.aut (right p₁ p₂) = etail | E := yield_at a.aut (left p₁ p₂) = etail ∧ yield_at a.aut (right p₁ p₂) = ehead end end def xor_gate' := vec_grid₀.mk ⟨7, 7, dec_trivial, ⟨[condu, condu, empty, empty, empty, empty, empty, empty, empty, condu, empty, empty, empty, empty, empty, condu, condu, condu, condu, empty, empty, empty, condu, empty, empty, condu, condu, condu, empty, condu, condu, condu, condu, empty, empty, empty, empty, condu, empty, empty, empty, empty, condu, condu, empty, empty, empty, empty, empty], rfl⟩⟩ ⟨0, 0⟩ def xor_gate_inputs : list inout := [⟨⟨0, 6⟩, ⟨1, 6⟩, E⟩, ⟨⟨0, 0⟩, ⟨1, 0⟩, E⟩] def xor_gate_outputs : list inout := [⟨⟨5, 3⟩, ⟨6, 3⟩, E⟩] def mk_xor (a : ww) : ww₁ := ⟨a, xor_gate_inputs, xor_gate_outputs⟩ def xor_gate_w : ww := mk_ww xor_gate' def xor_gate : ww₁ := mk_xor xor_gate_w def xor' (b₁ b₂ : bool) : bool := read (mk_xor (step_n (write (write xor_gate 0 b₂) 1 b₁).aut 5)) 0 theorem xor_iff_xor' {b₁ b₂} : bxor b₁ b₂ ↔ xor' b₁ b₂ := begin cases b₁; cases b₂; split; intros h, { dsimp at h, contradiction }, { have : xor' ff ff = ff, from dec_trivial, rw this at h, contradiction }, { exact dec_trivial }, { dsimp, unfold_coes }, { exact dec_trivial }, { dsimp, unfold_coes }, { dsimp at h, contradiction }, { have : xor' tt tt = ff, from dec_trivial, rw this at h, contradiction } end end ww_xor end ww end ww
a2861dbcba5a36d7b31a613d48252087ab6eb2e1
36938939954e91f23dec66a02728db08a7acfcf9
/lean/deps/x86_semantics/src/x86_semantics/evaluator.lean
1546757a2eb33e30b9749bf1121da77fcffd344f
[ "Apache-2.0" ]
permissive
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
38,128
lean
-- Evaluates actions in an environment. import galois.data.bitvec import .common import .machine_memory import .sexpr -- FIXME: move def annotate {ε} {m} [monad m] [monad_except ε m] {a} (f : ε -> ε) (c : m a) : m a := catch c (λe, throw (f e)) def annotate' {m} [monad m] [monad_except string m] {a} (e : string) (c : m a) : m a := annotate (λs, e ++ ": " ++ s) c namespace mc_semantics -- This represents only nats (not lhs or expression binders), and is -- used to instantiate nat_exprs @[reducible] def nat_env := list (option nat) namespace nat_expr @[reducible] def eval (e : nat_env) : nat_expr -> option ℕ | (lit n) := some n | (var idx) := monad.join (list.nth e idx) | (add e1 e2) := (+) <$> (eval e1) <*> (eval e2) | (sub e1 e2) := (λx y, x - y) <$> (eval e1) <*> (eval e2) | (mul e1 e2) := (*) <$> (eval e1) <*> (eval e2) | (div e1 e2) := (/) <$> (eval e1) <*> (eval e2) def wf_nat_expr (nenv : nat_env) : nat_expr -> Prop | (lit _) := true | (var idx) := option.is_some (monad.join (list.nth nenv idx)) | (add e1 e2) := wf_nat_expr e1 ∧ wf_nat_expr e2 | (sub e1 e2) := wf_nat_expr e1 ∧ wf_nat_expr e2 | (mul e1 e2) := wf_nat_expr e1 ∧ wf_nat_expr e2 | (div e1 e2) := wf_nat_expr e1 ∧ wf_nat_expr e2 lemma eval_add_eq {e} {x y} : eval e (x + y) = (+) <$> (eval e x) <*> (eval e y) := by { cases x; cases y; simp [ has_add.add, nat_expr.do_add, nat_expr.eval] } lemma eval_sub_eq {e} {x y} : eval e (x - y) = (λx y, x - y) <$> (eval e x) <*> (eval e y) := by { cases x; cases y; simp [ has_sub.sub, nat_expr.do_sub, nat_expr.eval] } lemma eval_mul_eq {e} {x y} : eval e (x * y) = (*) <$> (eval e x) <*> (eval e y) := by { cases x; cases y; simp [ has_mul.mul, nat_expr.do_mul, nat_expr.eval] } @[reducible] def eval_default (e : nat_env) : nat_expr -> ℕ | (lit n) := n | (var idx) := match list.nth e idx with | (some (some n)) := n | _ := 0 end | (add e1 e2) := (eval_default e1) + (eval_default e2) | (sub e1 e2) := (eval_default e1) - (eval_default e2) | (mul e1 e2) := (eval_default e1) * (eval_default e2) | (div e1 e2) := (eval_default e1) / (eval_default e2) -- instance {nenv} : decidable_pred (wf_nat_expr nenv) := -- begin -- unfold decidable_pred, -- intros e, -- induction e; simp [wf_nat_expr], -- case lit { apply is_true, trivial }, -- case var { apply coe_decidable_eq }, -- apply_instance, -- end lemma eval_default_add_eq {e} {x y} : eval_default e (x + y) = (eval_default e x) + (eval_default e y) := by { cases x; cases y; simp [ has_add.add, nat_expr.do_add, eval_default] } lemma eval_default_sub_eq {e} {x y} : eval_default e (x - y) = (eval_default e x) - (eval_default e y) := by { cases x; cases y; simp [ has_sub.sub, nat_expr.do_sub, nat_expr.eval_default] } lemma eval_default_mul_eq {e} {x y} : eval_default e (x * y) = (eval_default e x) * (eval_default e y) := by { cases x; cases y; simp [ has_mul.mul, nat_expr.do_mul, nat_expr.eval_default] } -- @[reducible] -- def eval : nat_expr -> ℕ -- | (nat_expr.lit n) := n -- -- | (nat_expr.var idx) := match list.nth nat_env idx with | (some (some n)) := n | _ := 0 end -- | (nat_expr.var idx) := 0 -- -- FIXME, maybe use sorry? -- | (nat_expr.add e1 e2) := (eval e1) + (eval e2) -- | (nat_expr.sub e1 e2) := (eval e1) - (eval e2) -- | (nat_expr.mul e1 e2) := (eval e1) * (eval e2) -- | (nat_expr.div e1 e2) := (eval e1) / (eval e2) end nat_expr namespace type @[reducible] def eval (nenv : nat_env) : type -> option type | (bv e) := (λn, bv (nat_expr.lit n)) <$> nat_expr.eval nenv e | (fn arg res) := fn <$> (eval arg) <*> (eval res) | tp := return tp def eval_default (nenv : nat_env) : type -> type | (bv e) := bv (nat_expr.lit (nat_expr.eval_default nenv e)) | (fn arg res) := fn (eval_default arg) (eval_default res) | tp := tp def assert_types {m} [monad m] [monad_except string m] (nenv : nat_env) (t1 t2 : type) : m unit := if eval_default nenv t1 = eval_default nenv t2 then return () else throw $ "Type mismatch: " ++ t1.pp ++ " and " ++ t2.pp ++ " in " ++ repr nenv def assert_bv {m} [monad m] [monad_except string m] (nenv : nat_env) (tp : type) : m ℕ := match tp with | (bv e) := return (nat_expr.eval_default nenv e) | _ := throw "Not a bitvecor" end end type end mc_semantics namespace x86 open mc_semantics open mc_semantics.type @[reducible] def machine_word := bitvec 64 namespace reg def inject : Π(rtp : gpreg_type), bitvec rtp.width' -> machine_word -> machine_word | gpreg_type.reg32 b _ := bitvec.append (bitvec.zero 32) b | gpreg_type.reg8h b old := old.set_bits 48 b (of_as_true trivial) | rtp b old := old.set_bits (64 - rtp.width') b (begin cases rtp; simp end) def project : Π(rtp : gpreg_type), machine_word -> bitvec rtp.width' | gpreg_type.reg8h b := b.get_bits 48 8 (begin simp [gpreg_type.width'], exact dec_trivial end) | rtp b := b.get_bits (64 - rtp.width') rtp.width' (begin cases rtp; simp end) end reg structure machine_state : Type := (mem : memory) (gpregs : array 16 machine_word) (flags : array 32 bool) (ip : machine_word) namespace machine_state -- Constructs an empty machine state, with 0 where we need a value. def empty : machine_state := { mem := memory.empty , gpregs := mk_array 16 0 , flags := mk_array 32 ff , ip := 0 } def get_gpreg (s : machine_state) (idx : fin 16) : machine_word := array.read s.gpregs idx def update_gpreg (idx : fin 16) (f : machine_word -> machine_word) (s : machine_state) : machine_state := { s with gpregs := array.write s.gpregs idx (f (get_gpreg s idx)) } def get_flag (s : machine_state) (idx : fin 32) : bool := array.read s.flags idx def update_flag (idx : fin 32) (f : bool -> bool) (s : machine_state) : machine_state := { s with flags := array.write s.flags idx (f (get_flag s idx))} -- def store_bytes (addr : machine_word) (bs : list (bitvec 8)) (s : machine_state) : machine_state := -- { s with mem := s.mem.store_bytes addr bs } -- def read_bytes (s : machine_state) (addr : machine_word) (n : ℕ) : option (list (bitvec 8)) := -- s.mem.read_bytes addr n -- lemma read_bytes_length {s : machine_state} {addr : machine_word} {n : ℕ} {bs : list (bitvec 8)} -- : read_bytes s addr n = some bs -> bs.length = n := memory.read_bytes_length def store_word {n : ℕ} (s : machine_state) (addr : machine_word) (b : bitvec (8 * n)) : machine_state := { s with mem := s.mem.store_word addr b } def read_word (s : machine_state) (addr : machine_word) (n : ℕ) : option (bitvec (8 * n)) := s.mem.read_word addr n def print_regs (s : machine_state) : string := let lines := list.zip_with (λn (r : bitvec 64), n ++ ": " ++ r.pp_hex ++ ", ") reg.r64_names s.gpregs.to_list in string.join lines def print_set_flags (s : machine_state) : string := let lines := list.zip_with (λn (r : bool), if r then n else "") reg.flag_names s.flags.to_list in "[" ++ string.intercalate ", " (list.filter (λs, s.length > 0) lines) ++ "]" end machine_state inductive arg_lval | reg {} {tp : type} : concrete_reg tp -> arg_lval | memloc (width : ℕ) (addr : machine_word) : arg_lval namespace arg_lval def repr : arg_lval -> string | (reg r) := r.repr | (memloc width addr) := has_repr.repr addr ++ "@" ++ has_repr.repr width instance arg_lval_repr : has_repr arg_lval := ⟨repr⟩ end arg_lval section with_nat_env -- OS stuff parameters (os_state : Type) structure system_state := (machine_state : machine_state) (os_state : os_state) @[reducible] def system_m := state_t system_state (except string) parameter (os_transition : system_m unit) parameter (nenv : nat_env) @[reducible] def eval_nat_expr (e : nat_expr) : nat := nat_expr.eval_default nenv e @[reducible] def eval_type : type -> type := type.eval_default nenv -- | (bv e) := bv (nat_expr.lit (eval_nat_expr e)) -- | (fn arg res) := fn (eval_type arg) (eval_type res) -- | tp := tp @[reducible] def value : type -> Type | (bv e) := bitvec (eval_nat_expr e) -- We use the _normalised_ value here. | bit := bool | float := unit -- FIXME | double := unit -- FIXME | x86_80 := unit -- FIXME | (vec w tp) := array (eval_nat_expr w) (value tp) -- FIXME | (pair tp tp') := value tp × value tp' | (fn arg res) := (value arg) -> (value res) -- namespace value -- def value.repr : Π{tp : type}, value tp -> string -- | (bv e) b := has_repr.repr b -- | (fn _ _ ) _ := "<function>" -- | _ _ := "Unsupported type" -- instance value_repr {tp : type} : has_repr (value tp) := ⟨value.repr⟩ -- end value -- Corresponding to the binder type, more or less. inductive arg_value -- natv is here for completeness --- the presumption is that a -- one_of param is only used in types, but in case it is not, we -- include a binding in the environment, | natv : ℕ -> arg_value -- covers reg, addr, and lhs bindings | lval : arg_lval -> arg_value | rval {tp : type} : value tp -> arg_value -- namespace arg_value -- def repr : arg_value -> string -- | (lval l) := l.repr -- | (rval v) := v.repr -- instance arg_value_repr : has_repr arg_value := ⟨repr⟩ -- end arg_value @[reducible] def environment := list arg_value structure evaluator_state : Type := (system_state : system_state) (environment : environment) -- read only, but reading can fail (locals : rbmap ℕ (sigma value)) -- namespace evaluator_state def evaluator_state.init (sst : system_state) : evaluator_state := { system_state := sst , environment := [] , locals := mk_rbmap ℕ (sigma value) } -- end evaluator_state -- Monad for evaluating with failure. This nesting might be useful to get the ip where things break? @[reducible] def evaluator := state_t evaluator_state (except string) -- FIXME: are these an oversight in the stdlib? instance (ε): monad_except ε (except ε) := { throw := λα e, except.error e, catch := λα m f, match m with | (except.error e) := f e | _ := m end } instance (ε) (m) [monad_except ε m] : has_orelse m := { orelse := λα, monad_except.orelse } instance (ε) [inhabited ε] : alternative (except ε) := { failure := λα, except.error (default ε)} -- namespace type -- If evaluation of the expr fails, we return the original type. -- def normalise (e : environment) : type -> type -- | (base b) := base (base_type.normalise e b) -- | (fn arg res) := fn (normalise arg) (normalise res) -- def equiv (e : environment) (t1 : type) (t2 : type) : Prop := -- normalise e t1 = normalise e t2 -- instance (e) : decidable_rel (equiv e) := -- λa b, begin simp [equiv], apply_instance end -- end type -- namespace value lemma value.type_eval_is_id: Π{tp : type}, value (eval_type tp) = value tp := begin intros, induction tp, case bv { refl }, case fn { simp [value, eval_type, type.eval_default], rw [ tp_ih_arg, tp_ih_res ] }, repeat { refl } end def value.eval_cong {tp tp' : type} (pf : eval_type tp = eval_type tp') (v : value tp) : value tp' := begin rw <- value.type_eval_is_id, rw <- value.type_eval_is_id at v, exact (eq.rec v pf) end -- This allows us to resolve arith in nat_exprs def value.type_check {m} [monad m] [monad_except string m] (tp : type) (v : value tp) (tp' : type) : m (value tp') := if H : eval_type tp = eval_type tp' then return (value.eval_cong H v) else throw "type_check: arg type mismatch" -- end value -- namespace evaluator def evaluator.run {a : Type} (m : evaluator a) (s : evaluator_state) : except string (a × evaluator_state) := (m.run s) def evaluator.read_memory_at (addr : machine_word) (n : ℕ) : evaluator (bitvec n) := do s <- get, match s.system_state.machine_state.read_word addr (n / 8) with | none := throw "read_memory_at: no bytes at addr" | (some w) := if H : 8 * (n / 8) = n then return (bitvec.cong H w) else throw "evaluator.read_memory_at: width not a multiple of 8" end def evaluator.map_machine_state (f : machine_state → machine_state) : evaluator unit := modify (λ(s : evaluator_state), { s with system_state := { s.system_state with machine_state := f s.system_state.machine_state } }) def evaluator.write_memory_at : Π{tp : type} (addr : machine_word) (bytes : value tp), evaluator unit | (bv e) addr bytes := let width := eval_nat_expr e in (if H : width = 8 * (width / 8) then evaluator.map_machine_state (λ(s : machine_state), s.store_word addr (bitvec.cong H bytes)) else throw "evaluator.write_memory_at: width not a multiple of 8") | _ _ _ := throw "evaluator.write_memory_at not a bv" def evaluator.arg_at_idx (idx : ℕ) : evaluator arg_value := do s <- get, match s.environment.nth idx with | (some a) := return a | none := throw "evaluator.arg_at_idx: no arg at idx" end -- We should factor out the type check, although it might depend on -- the functor (value in this case) if we generalise equality def evaluator.local_at_idx (idx : ℕ) (tp : type) : evaluator (value tp) := do s <- get, match s.locals.find idx with | (some (sigma.mk tp' v)) := value.type_check _ v tp | none := throw "local_at_idx: no arg at idx" end lemma width_width' : Π(rtp : gpreg_type), eval_nat_expr rtp.width = rtp.width' := begin intro, induction rtp; trivial end def concrete_reg.set : Π{tp : type}, concrete_reg tp -> value tp -> evaluator unit | ._ (concrete_reg.gpreg idx rtp) b := let b' : bitvec rtp.width' := eq.rec b (width_width' rtp) in evaluator.map_machine_state (machine_state.update_gpreg idx (reg.inject rtp b')) | ._ (concrete_reg.flagreg idx) b := evaluator.map_machine_state (machine_state.update_flag idx (λ_, b)) def concrete_reg.from_state : Π{tp : type}, concrete_reg tp -> machine_state -> value tp | _ (concrete_reg.gpreg idx rtp) s := let v := reg.project rtp (s.get_gpreg idx) in begin simp [value, width_width' nenv rtp], exact v end | _ (concrete_reg.flagreg idx) s := s.get_flag idx def concrete_reg.read {tp : type} (r : concrete_reg tp) : evaluator (value tp) := do s <- get, return (concrete_reg.from_state r s.system_state.machine_state) -- namespace arg_lval def arg_lval.to_value' {m} [monad m] [monad_except string m] (s : machine_state) : arg_lval -> Π(tp : type), m (value tp) | (@arg_lval.reg tp r) tp' := value.type_check tp (concrete_reg.from_state r s) tp' | (arg_lval.memloc width addr) tp' := match s.read_word addr (width / 8) with | none := throw "arg_lval.to_value': no bytes at addr" | (some w) := value.type_check (bv (8 * (width / 8))) w tp' end def arg_lval.to_value : arg_lval -> Π(tp : type), evaluator (value tp) | (@arg_lval.reg tp r) tp' := do v <- concrete_reg.read r, value.type_check tp v tp' | (arg_lval.memloc width addr) tp' := do v <- evaluator.read_memory_at addr width, value.type_check (bv width) v tp' def arg_lval.set_value : arg_lval -> Π{tp : type}, value tp -> evaluator unit | (@arg_lval.reg tp r) tp' v := do v' <- value.type_check _ v tp, concrete_reg.set r v' | (arg_lval.memloc _width addr) tp v := do evaluator.write_memory_at addr v -- def read_memory_at (av : arg_value) (n : ℕ) : evaluator (bitvec (8 * n)) := -- match av with -- | (@arg_value.bv 64 addr) := -- | _ := throw "addr.read: not a 64-bit bitvecor" -- end -- Can fail if types mismatch def arg_value.to_value : arg_value -> Π(tp : type), evaluator (value tp) | (arg_value.natv _ _) _ := throw "arg_value.to_value: saw a natv" | (arg_value.lval _ l) tp := arg_lval.to_value l tp | (arg_value.rval v) tp := value.type_check _ v tp def arg_value.set_value : arg_value -> Π{tp : type}, value tp -> evaluator unit | (arg_value.lval _ l) tp v := arg_lval.set_value l v | _ _ _ := throw "arg_value.set_value: not an lvalue" def addr.read : Π{tp : type}, addr tp -> evaluator (value tp) | tp (addr.arg idx) := do av <- evaluator.arg_at_idx idx, arg_value.to_value av tp -- FIXME: we should really check if this is a memloc first. -- w <- av.read_memory_at n, -- return (value.bv w) def addr.set : Π{tp : type}, addr tp -> value tp -> evaluator unit | tp (addr.arg idx) v := do av <- evaluator.arg_at_idx idx, -- FIXME: we should really check if this is a memloc first. arg_value.set_value av v -- This is the least-worst option. The other alternative is to have a -- value constructor for functions, which we only need here. inductive {u v} hlist {α : Type u} (f : α -> Type v): list α -> Type (max u v) | hnil : hlist [] | hcons {xs : list α} (x : α) : f x -> hlist xs -> hlist (x :: xs) -- namespace nat_expr -- def eval' (ne : nat_expr) : evaluator ℕ := do -- s <- get, -- match nat_expr.eval s.environment ne with -- | none := throw "nat_expr.eval': couldn't eval" -- | (some n) := return n -- end -- end nat_expr -- def prim_binop (e : nat_expr) (p : Π{n : ℕ}, bitvec n -> bitvec n -> bitvec n) := -- evaluator.with_nat_expr_as_nat' (λi, value (bv i .→ bv i .→ bv i)) e (λn, return (@p n)) -- lemma eval_add_eq {x y} : eval_nat_expr (x + y) = (eval_nat_expr x + eval_nat_expr y) := -- begin -- simp [eval_nat_expr, nat_expr.eval_add_eq, has_seq.seq], -- end -- by { cases x; cases y; simp [ -- has_add.add, has_seq.seq, nat_expr.do_add -- , nat_expr.eval] } -- FIXME: move -- Might be easier to define in terms of to_int/from_int etc. def bitvec.uext {n} (m : ℕ) (p: n ≤ m) (x:bitvec n) : bitvec m := bitvec.set_bits 0 0 x (begin simp, exact p end) def bitvec.sext {n} (m : ℕ) (p: n ≤ m) (x:bitvec n) : bitvec m := bitvec.set_bits (if x.msb then (bitvec.zero m).not else 0) 0 x (begin simp, exact p end) def bitvec.trunc {n} (m : ℕ) (p: m ≤ n) (x:bitvec n) : bitvec m := bitvec.get_bits x 0 m (begin simp, exact p end) def bit_to_bitvec (n : ℕ) (b : bool) : bitvec n := if b then 1 else 0 lemma eval_default_2 {e} : nat_expr.eval_default e 2 = 2 := rfl lemma nat_expr_eval_2 : eval_nat_expr 2 = 2 := rfl def type.has_eq : type -> Prop | (bv _) := true | bit := true | float := true | double := true | x86_80 := true | (vec _ tp) := type.has_eq tp | (pair tp tp') := type.has_eq tp ∧ type.has_eq tp' | (fn _ _) := false -- could probably come up with something, but nothing efficient @[reducible] def type.has_eq_dec : Π(tp : type), decidable (type.has_eq tp) | (bv _) := is_true true.intro | bit := is_true true.intro | float := is_true true.intro | double := is_true true.intro | x86_80 := is_true true.intro | (vec _ tp) := type.has_eq_dec tp | (pair tp tp') := @and.decidable _ _ (type.has_eq_dec tp) (type.has_eq_dec tp') | (fn _ _) := is_false not_false instance decidable_pred_type_has_eq: decidable_pred type.has_eq := type.has_eq_dec def value.partial_eq : Π{tp : type}, type.has_eq tp -> value tp -> value tp -> bool | (bv _) _ v1 v2 := (v1 = v2) | bit _ v1 v2 := (v1 = v2) | float _ v1 v2 := (v1 = v2) | double _ v1 v2 := (v1 = v2) | x86_80 _ v1 v2 := (v1 = v2) | (vec _ tp) pf v1 v2 := let pf' : type.has_eq tp := pf in (list.zip (array.to_list v1) (array.to_list v2)).all (λ(v : (value tp × value tp)), value.partial_eq pf' v.fst v.snd) | (pair tp tp') pf v1 v2 := band (value.partial_eq pf.left v1.fst v2.fst) (value.partial_eq pf.right v1.snd v2.snd) -- Returns the number of bits that are tt mod 2 def bitvec.parity {n : ℕ} (b : bitvec n) : bool := bitvec.foldl bxor ff b example : bitvec.parity (3 : bitvec 4) = ff := by refl example : bitvec.parity (7 : bitvec 4) = tt := by refl def prim.eval : Π{tp : type}, prim tp -> evaluator (value tp) -- `(eq tp)` returns `true` if two values are equal. | ._ (prim.eq tp) := if pf : type.has_eq tp then return (value.partial_eq pf) else throw "prim.eval.eq: eq at unsupported type" -- `(neq tp)` returns `true` if two values are not equal. | ._ (prim.neq tp) := if pf : type.has_eq tp then return (λv1 v2, bnot (value.partial_eq pf v1 v2)) else throw "prim.eval.neq: neq at unsupported type" -- `(mux tp) c t f` evaluates to `t` when `c` is true and `f` otherwise. -- This only evaluates `t` when `c` is true, and only evaluates `f` when -- `c` is false. | ._ (prim.mux tp) := return (λb l r, if b then l else r) -- `zero` is the zero bit | ._ prim.bit_zero := return ff -- `one` is the one bit | ._ prim.bit_one := return tt | ._ prim.bit_or := return bor | ._ prim.bit_and := return band | ._ prim.bit_xor := return bxor -- `bvnat` constructs a bit vector from a natural number. | ._ (prim.bv_nat w n) := return (bitvec.of_nat (eval_nat_expr w) (eval_nat_expr n)) -- `(add i)` returns the sum of two i-bit numbers. | ._ (prim.add i) := return bitvec.add -- `(adc i)` returns the sum of two i-bit numbers and a carry bit. | ._ (prim.adc i) := return (λx y b, bitvec.add x (bitvec.add y (bit_to_bitvec _ b))) | ._ (prim.uadc_overflows i) := return (λx y b, bitvec.ult (x + y + bit_to_bitvec (eval_nat_expr i) b) x) | ._ (prim.sadc_overflows i) := return (λx y b, bitvec.slt (x + y + bit_to_bitvec (eval_nat_expr i) b) x) -- `(bvsub i)` substracts two i-bit bitvectors. | ._ (prim.sub i) := return bitvec.sub -- `(ssbb_overflows i)` true if signed sub overflows, the bit -- is a borrow bit. -- FIXME: is this correct? | ._ (prim.ssbb_overflows i) := return (λx y b, bitvec.slt x (x - y - bit_to_bitvec (eval_nat_expr i) b)) -- `(usbb_overflows i)` true if unsigned sub overflows, -- the bit is a borrow bit. | ._ (prim.usbb_overflows i) := return (λx y b, bitvec.ult x (x - y - bit_to_bitvec (eval_nat_expr i) b)) -- `(neg tp)` Two's Complement negation. | ._ (prim.neg i) := return bitvec.neg -- `(mul i)` returns the product of two i-bit numbers. | ._ (prim.mul i) := return bitvec.mul -- `(quotRem i) n d` returns a pair `(q,r)` where `q` is a `floor (n/d)` -- and `r` is `n - d * floor (n/d)`. -- `n` and `d` are treated as unsigned values. -- If `d = 0` or `floor(n/d) >= 2^n`, then this triggers a #DE exception. | ._ (prim.quotRem i) := throw "prim.eval.quotRem unimplemented" -- `(squotRem i) n d` returns a pair `(q,r)` where `q` is a `trunc (n/d)` -- and `r` is `n - d * trunc (n/d)`. `trunc` always round to zero. -- `n` and `d` are treated as signed values. -- If `d = 0`, `trunc(n/d) >= 2^(n-1)` or `trunc(n/d) < -2^(n-1), then this -- triggers a #DE exception when evaluated. | ._ (prim.squotRem i) := throw "prim.eval.squotRem unimplemented" | ._ (prim.ule i) := return (λx y, bitvec.ule x y) | ._ (prim.ult i) := return (λx y, bitvec.ult x y) -- `(slice w u l)` takes bits `u` through `l` out of a `w`-bit number. -- prim (bv w .→ bv (u+1-l)) -- slice {w: ℕ} (u l k:ℕ) (H: w = k + (u + 1 - l)) (x: bitvec w) : bitvec (u + 1 - l) | tp (prim.slice w u l) := do let n := eval_nat_expr u + 1 - eval_nat_expr l, H <- annotate' "slice" (assert (eval_nat_expr w = (eval_nat_expr w - n + n))), return (begin have rewr : value nenv (bv (u + 1 - l)) = value nenv (bv (nat_expr.lit n)) := begin simp [n, value, nat_expr.eval_default_sub_eq , nat_expr.eval_default_add_eq , eval_nat_expr, nat_expr.eval_default], rw add_comm, refl end, simp [value], rw rewr, exact (bitvec.slice (eval_nat_expr nenv u) (eval_nat_expr nenv l) (eval_nat_expr nenv w - n) H.default) end) -- `(sext i o)` sign extends an `i`-bit number to a `o`-bit number. | ._ (prim.sext i o) := do H <- annotate' "sext" (assert (eval_nat_expr i ≤ eval_nat_expr o)), return (bitvec.sext (eval_nat_expr o) H.default) -- `(uext i o)` unsigned extension of an `i`-bit number to a `o`-bit number. | ._ (prim.uext i o) := do H <- annotate' "uext" (assert (eval_nat_expr i ≤ eval_nat_expr o)), return (bitvec.uext (eval_nat_expr o) H.default) -- `(trunc i o)` truncates an `i`-bit number to a `o`-bit number. | ._ (prim.trunc i o) := do H <- annotate' "trunc" (assert (eval_nat_expr o ≤ eval_nat_expr i)), return (bitvec.trunc (eval_nat_expr o) H.default) | ._ (prim.cat i) := return (λx y, bitvec.cong (begin simp [eval_nat_expr, nat_expr.eval_default_mul_eq, nat_expr.eval, eval_default_2, two_mul], end) (bitvec.append x y)) -- | bv_least_nibble (i:ℕ) : prim (bv i .→ bv 4) | ._ (prim.msb i) := return bitvec.msb | ._ (prim.bv_and i) := return bitvec.and | ._ (prim.bv_or i) := return bitvec.or | ._ (prim.bv_xor i) := return bitvec.xor | ._ (prim.bv_complement i) := return bitvec.not | ._ (prim.shl i) := return (λx (y : bitvec 8), bitvec.shl x y.to_nat) --- `(shl_carry w) c b i` returns the `i`th bit --- in the bitvector [c]++b where `i` is treated as an unsigned --- number with `0` as the most-significant bit. -- e.g., If `i` is `0`, then this returns `c`. If `i` -- exceeds the number of bits in `[c] ++ b` (i.e., i >= w+1), -- the the result is false. | ._ (prim.shl_carry w) := return (λc b (i : bitvec 8), match i.to_nat with | nat.zero := c -- FIXME: is this the intended behaviour? | (nat.succ n) := if n < eval_nat_expr w then bitvec.nth b (eval_nat_expr w - n - 1) else ff end) --- `(shr i) x y` shifts the bits in `x` to the right by --- `y` bits where `y` is treated as an unsigned integer. --- The new bits shifted in from the right are all zero. | ._ (prim.shr i) := return (λx (y : bitvec 8), bitvec.ushr x y.to_nat) --- `(shr_carry w) b c i` returns the `i`th bit --- in the bitvector b++[c] where `i` is treated as an unsigned --- number with `0` as the least-significant bit. -- e.g., If `i` is `0`, then this returns `c`. If `i` -- exceeds the number of bits in `b++[c]` (i.e., i >= w+1), -- the the result is false. | ._ (prim.shr_carry w) := return (λb c (i : bitvec 8), match i.to_nat with | nat.zero := c | (nat.succ n) := @ite (n < eval_nat_expr w) (nat.decidable_lt _ _) _ (bitvec.nth b n) ff -- if n < eval_nat_expr w -- then bitvec.nth b n -- else ff end) --- `(sar i) x y` arithmetically shifts the bits in `x` to --- the left by `y` bits where `y` is treated as an unsigned integer. --- The new bits shifted in all match the most-significant bit in y. | ._ (prim.sar i) := return (λx (y : bitvec 8), bitvec.sshr x y.to_nat) --- `(sar_carry w) b c i` returns the `i`th bit --- in the bitvector b++[c] where `i` is treated as an unsigned --- number with `0` as the least-significant bit. -- e.g., If `i` is `0`, then this returns `c`. If `i` -- exceeds the number of bits in `b++[c]` (i.e., i >= w+1), -- the the result is equal to the most-signfiicant bit. | ._ (prim.sar_carry w) := return (λb c (i : bitvec 8), match i.to_nat with | nat.zero := c | (nat.succ n) := @ite (n < eval_nat_expr w) (nat.decidable_lt _ _) _ (bitvec.nth b n) (bitvec.msb b) -- (if n < eval_nat_expr w -- then bitvec.nth b n -- else bitvec.msb b) end) | ._ (prim.even_parity i) := return (λb, bitvec.parity b = ff) -- `(bsf i)` returns the index of least-significant bit that is 1. | ._ (prim.bsf i) := throw "prim.eval.bsf unimplemented" -- `(bsr i)` returns the index of most-significant bit that is 1. | ._ (prim.bsr i) := throw "prim.eval.bsr unimplemented" -- `(bswap i)` reverses the bytes in the bitvector. | ._ (prim.bswap i) := throw "prim.eval.bswap unimplemented" -- `(btc w j) base idx` interprets base as bitvector and returns -- a bitvector contains the same bits as `base` except the `i`th bit -- (where 0 denotes the least-significant bit) is complemented. -- The value `i` is `idx` as a unsigned integer modulo `w`. | ._ (prim.btc w j) := throw "prim.eval.btc unimplemented" -- `(btr w j) base idx` interprets base as bitvector and returns -- a bitvector contains the same bits as `base` except the `i`th bit -- (where 0 denotes the least-significant bit) is cleared. -- The value `i` is `idx` as a unsigned integer modulo `w`. | ._ (prim.btr w j) := throw "prim.eval.btr unimplemented" -- `(bts w j) base idx` interprets base as bitvector and returns -- a bitvector contains the same bits as `base` except the `i`th bit -- (where 0 denotes the least-significant bit) is set. -- The value `i` is `idx` as a unsigned integer modulo `w`. | ._ (prim.bts w j) := throw "prim.eval.bts unimplemented" -- `bv_to_x86_80` converts a bitvector to an extended precision number (lossless) | ._ (prim.bv_to_x86_80 w) := throw "prim.eval.bv_to_x86_80 unimplemented" -- `float_to_x86_80` converts a float to an extended precision number (lossless) | ._ prim.float_to_x86_80 := throw "prim.eval.float_to_x86_80 unimplemented" -- `double_to_x86_80` converts a double to an extended precision number (lossless) | ._ prim.double_to_x86_80 := throw "prim.eval.double_to_x86_80 unimplemented" -- `x87_fadd` adds two extended precision values using the flags in the x87 register. | ._ prim.x87_fadd := throw "prim.eval.dx87_fadd unimplemented" -- Return first element of a pair | ._ (prim.pair_fst x y) := return (λ(v : value x × value y), v.fst) -- Return second element of a pair. | ._ (prim.pair_snd x y) := return (λ(v : value x × value y), v.snd) def value.make_undef : Π(tp : type), value tp | (bv e) := bitvec.of_nat (eval_nat_expr e) 0 | bit := ff | float := () | double := () | x86_80 := () | (vec w tp) := mk_array (eval_nat_expr w) (value.make_undef tp) | (pair tp tp') := (value.make_undef tp, value.make_undef tp') | (fn arg res) := λ_, value.make_undef res def expression.eval : Π{tp : type}, expression tp -> evaluator (value tp) | ._ (expression.primitive p) := prim.eval p | ._ (@expression.bit_test wr wi re idxe) := do r <- expression.eval re, idx <- expression.eval idxe, let idx' := idx.to_nat % eval_nat_expr wr in return (r.nth idx') | ._ (expression.mulc m xe) := do x <- expression.eval xe, return (bitvec.mul (bitvec.of_nat 64 (eval_nat_expr m)) x) | ._ (expression.quotc m xe) := throw "expression.eval.quotc unimplemented" | ._ (expression.undef tp) := return (value.make_undef tp) | ._ (expression.app f a) := (expression.eval f) <*> (expression.eval a) | ._ (expression.get_reg r) := concrete_reg.read r | ._ (expression.read tp addre) := do addr <- expression.eval addre, match tp with | (bv we) := evaluator.read_memory_at addr (eval_nat_expr we) | _ := throw "expression.eval.read Trying to store non-bitvector" end | ._ (expression.streg idx) := throw "expression.eval.streg unimplemented" | ._ (expression.get_local idx tp) := evaluator.local_at_idx idx tp -- This is overly general, we might not know that av here is an rval | ._ (expression.imm_arg idx tp) := do av <- evaluator.arg_at_idx idx, match av with | (arg_value.rval v) := value.type_check _ v tp | _ := throw "expression.eval.imm_arg Not an rval" end | ._ (expression.addr_arg idx) := do av <- evaluator.arg_at_idx idx, match av with | (arg_value.lval _ (arg_lval.memloc _ addr)) := return addr | _ := throw "expression.eval.addr_arg Not an memloc lval" end -- FIXME: isn't specific to arg_lval | ._ (expression.read_arg idx tp) := do av <- evaluator.arg_at_idx idx, arg_value.to_value av tp def evaluator.set_ip (new_ip : bitvec 64) : evaluator unit := evaluator.map_machine_state (λ(s : machine_state), { s with ip := new_ip }) def lhs.set : Π{tp : type}, lhs tp -> value tp -> evaluator unit | ._ (lhs.set_reg r) v := concrete_reg.set r v | ._ (lhs.write_addr ae tp) v := do a <- expression.eval ae, evaluator.write_memory_at a v | ._ (lhs.write_arg idx _tp) v := do av <- evaluator.arg_at_idx idx, -- fixme: we ignore tp here? arg_value.set_value av v | ._ (lhs.streg idx) v := throw "lhs.set: unsupported FP write" def lhs.read : Π{tp : type}, lhs tp -> evaluator (value tp) | ._ (lhs.set_reg r) := concrete_reg.read r | ._ (lhs.write_addr ae tp) := do addr <- expression.eval ae, match tp with | (bv we) := evaluator.read_memory_at addr (eval_nat_expr we) | _ := throw "lhs.read Trying to store non-bitvector" end | ._ (lhs.write_arg idx tp) := do av <- evaluator.arg_at_idx idx, -- fixme: we ignore tp here? arg_value.to_value av tp | ._ (lhs.streg idx) := throw "lhs.set: unsupported FP write" def evaluator.push64 (v : value (bv 64)) : evaluator unit := do sp <- lhs.read rsp, let sp' := sp - 8 in do lhs.set rsp sp', evaluator.write_memory_at sp' v def read_cpuid : evaluator unit := -- Copied from the cpuid results from my macbook -- Note: CPUID is allowed to return 0s let cpuid_values : rbmap ℕ (bitvec 32 × bitvec 32 × bitvec 32 × bitvec 32) := rbmap.from_list [ (0, (0xd, 0x756e6547, 0x6c65746e, 0x49656e69)) , (1, (0x40661, 0x2100800, 0x7ffafbff, 0xbfebfbff)) , (2, (0x76036301, 0xf0b5ff, 0x0, 0xc10000)) , (3, (0x0, 0x0, 0x0, 0x0)) , (4, (0x1c004121, 0x1c0003f, 0x3f, 0x0)) , (5, (0x40, 0x40, 0x3, 0x42120)) , (6, (0x77, 0x2, 0x9, 0x0)) , (7, (0x0, 0x27ab, 0x0, 0x9c000000)) , (8, (0x0, 0x0, 0x0, 0x0)) , (9, (0x0, 0x0, 0x0, 0x0)) , (10, (0x7300403, 0x0, 0x0, 0x603)) , (11, (0x1, 0x2, 0x100, 0x6)) , (12, (0x0, 0x0, 0x0, 0x0)) , (13, (0x7, 0x340, 0x340, 0x0)) , (2147483648, (0x80000008, 0x0, 0x0, 0x0)) , (2147483649, (0x0, 0x0, 0x21, 0x2c100800)) , (2147483650, (0x65746e49, 0x2952286c, 0x726f4320, 0x4d542865)) , (2147483651, (0x37692029, 0x3839342d, 0x20514830, 0x20555043)) , (2147483652, (0x2e322040, 0x48473038, 0x7a, 0x0)) , (2147483653, (0x0, 0x0, 0x0, 0x0)) , (2147483654, (0x0, 0x0, 0x1006040, 0x0)) , (2147483655, (0x0, 0x0, 0x0, 0x100)) , (2147483656, (0x3027, 0x0, 0x0, 0x0)) ] in -- FIXME: we need to look at rcx sometimes as well let cpuid_fn (n : ℕ) : (bitvec 32 × bitvec 32 × bitvec 32 × bitvec 32) := match cpuid_values.find n with | none := (0, 0, 0, 0) | (some r) := r end in do raxv <- lhs.read rax, match cpuid_fn raxv.to_nat with | (axv, bxv, cxv, dxv) := do lhs.set eax axv, lhs.set ebx bxv, lhs.set ecx cxv, lhs.set edx dxv end def event.eval : event -> evaluator unit | event.syscall := adapt_state (λ(s : evaluator_state), (s.system_state, s)) (λs s', { s' with system_state := s }) os_transition | (event.unsupported msg) := throw ("event.eval: unsupported: " ++ msg) | event.pop_x87_register_stack := throw "pop_x87_register_stack" | (event.call addr) := do new_ip <- expression.eval addr, s <- get, evaluator.push64 s.system_state.machine_state.ip, evaluator.set_ip new_ip | (event.jmp addr) := do new_ip <- expression.eval addr, evaluator.set_ip new_ip | (event.branch c addr) := do new_ip <- expression.eval addr, b <- expression.eval c, when b (evaluator.set_ip new_ip) | event.hlt := throw "halt" | (event.xchg addr1 addr2) := throw "xchg" | event.cpuid := read_cpuid -- def lhs.read : Π{tp : type}, lhs tp -> evaluator (value tp) -- | ._ (lhs.reg r) := reg.read r -- | ._ (lhs.addr a) := addr.read a -- | ._ (lhs.arg idx tp) := do av <- evaluator.arg_at_idx idx, -- arg_value.to_value av tp -- | ._ (lhs.streg idx) := throw "lhs.read: unsupported FP read" def action.eval : action -> evaluator unit | (action.set l e) := do v <- expression.eval e, lhs.set l v | (action.set_cond l c e) := do b <- expression.eval c, v <- expression.eval e, when b (lhs.set l v) | (@action.set_aligned (bv _) l e align) := do v <- expression.eval e, if v.to_nat % eval_nat_expr align = 0 then lhs.set l v else throw "Unaligned set_aligned" | (@action.set_aligned _ l e align) := throw "set_aligned: not a bv" | (@action.local_def tp idx e) := do v <- expression.eval e, modify (λs, { s with locals := s.locals.insert idx (sigma.mk tp v)}) | (action.event e) := event.eval e -- FIXME: check pattern.context |- environment def pattern.eval (p : pattern) (e : environment) (s : system_state) : except string system_state := -- only machine_state is preserved across instructions let st := { evaluator_state.init s with environment := e } in do (_, s') <- evaluator.run (monad.mapm' action.eval p.actions) st, return s'.system_state end with_nat_env end x86
ee5c0d851d53d796f06c3e0290445ed9ba6d54fc
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/category_theory/sites/sheaf.lean
4cb48c2e0b22c42e471829c06d26985cf2328f5c
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,338
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.sites.pretopology import category_theory.limits.shapes.types import category_theory.full_subcategory /-! # Sheaves on a Grothendieck topology Defines the notion of a sheaf on a Grothendieck topology, as well as a range of equivalent conditions useful in different situations. First define what it means for a presheaf `P : Cᵒᵖ ⥤ Type v` to be a sheaf *for* a particular presieve `R` on `X`: * A *family of elements* `x` for `P` at `R` is an element `x_f` of `P Y` for every `f : Y ⟶ X` in `R`. See `family_of_elements`. * The family `x` is *compatible* if, for any `f₁ : Y₁ ⟶ X` and `f₂ : Y₂ ⟶ X` both in `R`, and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂` such that `g₁ ≫ f₁ = g₂ ≫ f₂`, the restriction of `x_f₁` along `g₁` agrees with the restriction of `x_f₂` along `g₂`. See `family_of_elements.compatible`. * An *amalgamation* `t` for the family is an element of `P X` such that for every `f : Y ⟶ X` in `R`, the restriction of `t` on `f` is `x_f`. See `family_of_elements.is_amalgamation`. We then say `P` is *separated* for `R` if every compatible family has at most one amalgamation, and it is a *sheaf* for `R` if every compatible family has a unique amalgamation. See `is_separated_for` and `is_sheaf_for`. In the special case where `R` is a sieve, the compatibility condition can be simplified: * The family `x` is *compatible* if, for any `f : Y ⟶ X` in `R` and `g : Z ⟶ Y`, the restriction of `x_f` along `g` agrees with `x_(g ≫ f)` (which is well defined since `g ≫ f` is in `R`). See `family_of_elements.sieve_compatible` and `compatible_iff_sieve_compatible`. In the special case where `C` has pullbacks, the compatibility condition can be simplified: * The family `x` is *compatible* if, for any `f : Y ⟶ X` and `g : Z ⟶ X` both in `R`, the restriction of `x_f` along `π₁ : pullback f g ⟶ Y` agrees with the restriction of `x_g` along `π₂ : pullback f g ⟶ Z`. See `family_of_elements.pullback_compatible` and `pullback_compatible_iff`. Now given a Grothendieck topology `J`, `P` is a sheaf if it is a sheaf for every sieve in the topology. See `is_sheaf`. In the case where the topology is generated by a basis, it suffices to check `P` is a sheaf for every sieve in the pretopology. See `is_sheaf_pretopology`. We also provide equivalent conditions to satisfy alternate definitions given in the literature. * Stacks: In `equalizer.presieve.sheaf_condition`, the sheaf condition at a presieve is shown to be equivalent to that of https://stacks.math.columbia.edu/tag/00VM (and combined with `is_sheaf_pretopology`, this shows the notions of `is_sheaf` are exactly equivalent.) The condition of https://stacks.math.columbia.edu/tag/00Z8 is virtually identical to the statement of `yoneda_condition_iff_sheaf_condition` (since the bijection described there carries the same information as the unique existence.) * Maclane-Moerdijk [MM92]: Using `compatible_iff_sieve_compatible`, the definitions of `is_sheaf` are equivalent. There are also alternate definitions given: - Yoneda condition: Defined in `yoneda_sheaf_condition` and equivalence in `yoneda_condition_iff_sheaf_condition`. - Equalizer condition (Equation 3): Defined in the `equalizer.sieve` namespace, and equivalence in `equalizer.sieve.sheaf_condition`. - Matching family for presieves with pullback: `pullback_compatible_iff`. - Sheaf for a pretopology (Prop 1): `is_sheaf_pretopology` combined with the previous. - Sheaf for a pretopology as equalizer (Prop 1, bis): `equalizer.presieve.sheaf_condition` combined with the previous. ## Implementation The sheaf condition is given as a proposition, rather than a subsingleton in `Type (max u v)`. This doesn't seem to make a big difference, other than making a couple of definitions noncomputable, but it means that equivalent conditions can be given as `↔` statements rather than `≃` statements, which can be convenient. ## References * [MM92]: *Sheaves in geometry and logic*, Saunders MacLane, and Ieke Moerdijk: Chapter III, Section 4. * [Elephant]: *Sketches of an Elephant*, P. T. Johnstone: C2.1. * https://stacks.math.columbia.edu/tag/00VL (sheaves on a pretopology or site) * https://stacks.math.columbia.edu/tag/00ZB (sheaves on a topology) -/ universes v u namespace category_theory open opposite category_theory category limits sieve classical namespace presieve variables {C : Type u} [category.{v} C] variables {P : Cᵒᵖ ⥤ Type v} variables {X Y : C} {S : sieve X} {R : presieve X} variables (J J₂ : grothendieck_topology C) /-- A family of elements for a presheaf `P` given a collection of arrows `R` with fixed codomain `X` consists of an element of `P Y` for every `f : Y ⟶ X` in `R`. A presheaf is a sheaf (resp, separated) if every *compatible* family of elements has exactly one (resp, at most one) amalgamation. This data is referred to as a `family` in [MM92], Chapter III, Section 4. It is also a concrete version of the elements of the middle object in https://stacks.math.columbia.edu/tag/00VM which is more useful for direct calculations. It is also used implicitly in Definition C2.1.2 in [Elephant]. -/ def family_of_elements (P : Cᵒᵖ ⥤ Type v) (R : presieve X) := Π ⦃Y : C⦄ (f : Y ⟶ X), R f → P.obj (op Y) instance : inhabited (family_of_elements P (⊥ : presieve X)) := ⟨λ Y f, false.elim⟩ /-- A family of elements for a presheaf on the presieve `R₂` can be restricted to a smaller presieve `R₁`. -/ def family_of_elements.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) : family_of_elements P R₂ → family_of_elements P R₁ := λ x Y f hf, x f (h _ hf) /-- A family of elements for the arrow set `R` is *compatible* if for any `f₁ : Y₁ ⟶ X` and `f₂ : Y₂ ⟶ X` in `R`, and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂`, if the square `g₁ ≫ f₁ = g₂ ≫ f₂` commutes then the elements of `P Z` obtained by restricting the element of `P Y₁` along `g₁` and restricting the element of `P Y₂` along `g₂` are the same. In special cases, this condition can be simplified, see `pullback_compatible_iff` and `compatible_iff_sieve_compatible`. This is referred to as a "compatible family" in Definition C2.1.2 of [Elephant], and on nlab: https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents -/ def family_of_elements.compatible (x : family_of_elements P R) : Prop := ∀ ⦃Y₁ Y₂ Z⦄ (g₁ : Z ⟶ Y₁) (g₂ : Z ⟶ Y₂) ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄ (h₁ : R f₁) (h₂ : R f₂), g₁ ≫ f₁ = g₂ ≫ f₂ → P.map g₁.op (x f₁ h₁) = P.map g₂.op (x f₂ h₂) /-- If the category `C` has pullbacks, this is an alternative condition for a family of elements to be compatible: For any `f : Y ⟶ X` and `g : Z ⟶ X` in the presieve `R`, the restriction of the given elements for `f` and `g` to the pullback agree. This is equivalent to being compatible (provided `C` has pullbacks), shown in `pullback_compatible_iff`. This is the definition for a "matching" family given in [MM92], Chapter III, Section 4, Equation (5). Viewing the type `family_of_elements` as the middle object of the fork in https://stacks.math.columbia.edu/tag/00VM, this condition expresses that `pr₀* (x) = pr₁* (x)`, using the notation defined there. -/ def family_of_elements.pullback_compatible (x : family_of_elements P R) [has_pullbacks C] : Prop := ∀ ⦃Y₁ Y₂⦄ ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄ (h₁ : R f₁) (h₂ : R f₂), P.map (pullback.fst : pullback f₁ f₂ ⟶ _).op (x f₁ h₁) = P.map pullback.snd.op (x f₂ h₂) lemma pullback_compatible_iff (x : family_of_elements P R) [has_pullbacks C] : x.compatible ↔ x.pullback_compatible := begin split, { intros t Y₁ Y₂ f₁ f₂ hf₁ hf₂, apply t, apply pullback.condition }, { intros t Y₁ Y₂ Z g₁ g₂ f₁ f₂ hf₁ hf₂ comm, rw [←pullback.lift_fst _ _ comm, op_comp, functor_to_types.map_comp_apply, t hf₁ hf₂, ←functor_to_types.map_comp_apply, ←op_comp, pullback.lift_snd] } end /-- The restriction of a compatible family is compatible. -/ lemma family_of_elements.compatible.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) {x : family_of_elements P R₂} : x.compatible → (x.restrict h).compatible := λ q Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, q g₁ g₂ (h _ h₁) (h _ h₂) comm /-- Extend a family of elements to the sieve generated by an arrow set. This is the construction described as "easy" in Lemma C2.1.3 of [Elephant]. -/ noncomputable def family_of_elements.sieve_extend (x : family_of_elements P R) : family_of_elements P (generate R) := λ Z f hf, P.map (some (some_spec hf)).op (x _ (some_spec (some_spec (some_spec hf))).1) /-- The extension of a compatible family to the generated sieve is compatible. -/ lemma family_of_elements.compatible.sieve_extend (x : family_of_elements P R) (hx : x.compatible) : x.sieve_extend.compatible := begin intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, rw [←(some_spec (some_spec (some_spec h₁))).2, ←(some_spec (some_spec (some_spec h₂))).2, ←assoc, ←assoc] at comm, dsimp [family_of_elements.sieve_extend], rw [← functor_to_types.map_comp_apply, ← functor_to_types.map_comp_apply], apply hx _ _ _ _ comm, end /-- The extension of a family agrees with the original family. -/ lemma extend_agrees {x : family_of_elements P R} (t : x.compatible) {f : Y ⟶ X} (hf : R f) : x.sieve_extend f ⟨_, 𝟙 _, f, hf, id_comp _⟩ = x f hf := begin have h : (generate R) f := ⟨_, _, _, hf, id_comp _⟩, change P.map (some (some_spec h)).op (x _ _) = x f hf, rw t (some (some_spec h)) (𝟙 _) _ hf _, { simp }, simp_rw [id_comp], apply (some_spec (some_spec (some_spec h))).2, end /-- The restriction of an extension is the original. -/ @[simp] lemma restrict_extend {x : family_of_elements P R} (t : x.compatible) : x.sieve_extend.restrict (le_generate R) = x := begin ext Y f hf, exact extend_agrees t hf, end /-- If the arrow set for a family of elements is actually a sieve (i.e. it is downward closed) then the consistency condition can be simplified. This is an equivalent condition, see `compatible_iff_sieve_compatible`. This is the notion of "matching" given for families on sieves given in [MM92], Chapter III, Section 4, Equation 1, and nlab: https://ncatlab.org/nlab/show/matching+family. See also the discussion before Lemma C2.1.4 of [Elephant]. -/ def family_of_elements.sieve_compatible (x : family_of_elements P S) : Prop := ∀ ⦃Y Z⦄ (f : Y ⟶ X) (g : Z ⟶ Y) (hf), x (g ≫ f) (S.downward_closed hf g) = P.map g.op (x f hf) lemma compatible_iff_sieve_compatible (x : family_of_elements P S) : x.compatible ↔ x.sieve_compatible := begin split, { intros h Y Z f g hf, simpa using h (𝟙 _) g (S.downward_closed hf g) hf (id_comp _) }, { intros h Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ k, simp_rw [← h f₁ g₁ h₁, k, h f₂ g₂ h₂] } end lemma family_of_elements.compatible.to_sieve_compatible {x : family_of_elements P S} (t : x.compatible) : x.sieve_compatible := (compatible_iff_sieve_compatible x).1 t /-- Two compatible families on the sieve generated by a presieve `R` are equal if and only if they are equal when restricted to `R`. -/ lemma restrict_inj {x₁ x₂ : family_of_elements P (generate R)} (t₁ : x₁.compatible) (t₂ : x₂.compatible) : x₁.restrict (le_generate R) = x₂.restrict (le_generate R) → x₁ = x₂ := begin intro h, ext Z f ⟨Y, f, g, hg, rfl⟩, rw compatible_iff_sieve_compatible at t₁ t₂, erw [t₁ g f ⟨_, _, g, hg, id_comp _⟩, t₂ g f ⟨_, _, g, hg, id_comp _⟩], congr' 1, apply congr_fun (congr_fun (congr_fun h _) g) hg, end /-- Given a family of elements `x` for the sieve `S` generated by a presieve `R`, if `x` is restricted to `R` and then extended back up to `S`, the resulting extension equals `x`. -/ @[simp] lemma extend_restrict {x : family_of_elements P (generate R)} (t : x.compatible) : (x.restrict (le_generate R)).sieve_extend = x := begin apply restrict_inj, { exact (t.restrict (le_generate R)).sieve_extend _ }, { exact t }, rw restrict_extend, exact t.restrict (le_generate R), end /-- The given element `t` of `P.obj (op X)` is an *amalgamation* for the family of elements `x` if every restriction `P.map f.op t = x_f` for every arrow `f` in the presieve `R`. This is the definition given in https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents, and https://ncatlab.org/nlab/show/matching+family, as well as [MM92], Chapter III, Section 4, equation (2). -/ def family_of_elements.is_amalgamation (x : family_of_elements P R) (t : P.obj (op X)) : Prop := ∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : R f), P.map f.op t = x f h lemma is_compatible_of_exists_amalgamation (x : family_of_elements P R) (h : ∃ t, x.is_amalgamation t) : x.compatible := begin cases h with t ht, intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, rw [←ht _ h₁, ←ht _ h₂, ←functor_to_types.map_comp_apply, ←op_comp, comm], simp, end lemma is_amalgamation_restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) (x : family_of_elements P R₂) (t : P.obj (op X)) (ht : x.is_amalgamation t) : (x.restrict h).is_amalgamation t := λ Y f hf, ht f (h Y hf) lemma is_amalgamation_sieve_extend {R : presieve X} (x : family_of_elements P R) (t : P.obj (op X)) (ht : x.is_amalgamation t) : x.sieve_extend.is_amalgamation t := begin intros Y f hf, dsimp [family_of_elements.sieve_extend], rw [←ht _, ←functor_to_types.map_comp_apply, ←op_comp, (some_spec (some_spec (some_spec hf))).2], end /-- A presheaf is separated for a presieve if there is at most one amalgamation. -/ def is_separated_for (P : Cᵒᵖ ⥤ Type v) (R : presieve X) : Prop := ∀ (x : family_of_elements P R) (t₁ t₂), x.is_amalgamation t₁ → x.is_amalgamation t₂ → t₁ = t₂ lemma is_separated_for.ext {R : presieve X} (hR : is_separated_for P R) {t₁ t₂ : P.obj (op X)} (h : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : R f), P.map f.op t₁ = P.map f.op t₂) : t₁ = t₂ := hR (λ Y f hf, P.map f.op t₂) t₁ t₂ (λ Y f hf, h hf) (λ Y f hf, rfl) lemma is_separated_for_iff_generate : is_separated_for P R ↔ is_separated_for P (generate R) := begin split, { intros h x t₁ t₂ ht₁ ht₂, apply h (x.restrict (le_generate R)) t₁ t₂ _ _, { exact is_amalgamation_restrict _ x t₁ ht₁ }, { exact is_amalgamation_restrict _ x t₂ ht₂ } }, { intros h x t₁ t₂ ht₁ ht₂, apply h (x.sieve_extend), { exact is_amalgamation_sieve_extend x t₁ ht₁ }, { exact is_amalgamation_sieve_extend x t₂ ht₂ } } end lemma is_separated_for_top (P : Cᵒᵖ ⥤ Type v) : is_separated_for P (⊤ : presieve X) := λ x t₁ t₂ h₁ h₂, begin have q₁ := h₁ (𝟙 X) (by simp), have q₂ := h₂ (𝟙 X) (by simp), simp only [op_id, functor_to_types.map_id_apply] at q₁ q₂, rw [q₁, q₂], end /-- We define `P` to be a sheaf for the presieve `R` if every compatible family has a unique amalgamation. This is the definition of a sheaf for the given presieve given in C2.1.2 of [Elephant], and https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents. Using `compatible_iff_sieve_compatible`, this is equivalent to the definition of a sheaf in [MM92], Chapter III, Section 4. -/ def is_sheaf_for (P : Cᵒᵖ ⥤ Type v) (R : presieve X) : Prop := ∀ (x : family_of_elements P R), x.compatible → ∃! t, x.is_amalgamation t /-- This is an equivalent condition to be a sheaf, which is useful for the abstraction to local operators on elementary toposes. However this definition is defined only for sieves, not presieves. The equivalence between this and `is_sheaf_for` is given in `yoneda_condition_iff_sheaf_condition`. This version is also useful to establish that being a sheaf is preserved under isomorphism of presheaves. See the discussion before Equation (3) of [MM92], Chapter III, Section 4. See also C2.1.4 of [Elephant]. This is also a direct reformulation of https://stacks.math.columbia.edu/tag/00Z8. -/ def yoneda_sheaf_condition (P : Cᵒᵖ ⥤ Type v) (S : sieve X) : Prop := ∀ (f : S.functor ⟶ P), ∃! g, S.functor_inclusion ≫ g = f /-- (Implementation). This is a (primarily internal) equivalence between natural transformations and compatible families. Cf the discussion after Lemma 7.47.10 in https://stacks.math.columbia.edu/tag/00YW. See also the proof of C2.1.4 of [Elephant], and the discussion in [MM92], Chapter III, Section 4. -/ def nat_trans_equiv_compatible_family : (S.functor ⟶ P) ≃ {x : family_of_elements P S // x.compatible} := { to_fun := λ α, begin refine ⟨λ Y f hf, _, _⟩, { apply α.app (op Y) ⟨_, hf⟩ }, { rw compatible_iff_sieve_compatible, intros Y Z f g hf, dsimp, rw ← functor_to_types.naturality _ _ α g.op, refl } end, inv_fun := λ t, { app := λ Y f, t.1 _ f.2, naturality' := λ Y Z g, begin ext ⟨f, hf⟩, apply t.2.to_sieve_compatible _, end }, left_inv := λ α, begin ext X ⟨_, _⟩, refl end, right_inv := begin rintro ⟨x, hx⟩, refl, end } /-- (Implementation). A lemma useful to prove `yoneda_condition_iff_sheaf_condition`. -/ lemma extension_iff_amalgamation (x : S.functor ⟶ P) (g : yoneda.obj X ⟶ P) : S.functor_inclusion ≫ g = x ↔ (nat_trans_equiv_compatible_family x).1.is_amalgamation (yoneda_equiv g) := begin change _ ↔ ∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : S f), P.map f.op (yoneda_equiv g) = x.app (op Y) ⟨f, h⟩, split, { rintro rfl Y f hf, rw yoneda_equiv_naturality, dsimp, simp }, -- See note [dsimp, simp]. { intro h, ext Y ⟨f, hf⟩, have : _ = x.app Y _ := h f hf, rw yoneda_equiv_naturality at this, rw ← this, dsimp, simp }, -- See note [dsimp, simp]. end /-- The yoneda version of the sheaf condition is equivalent to the sheaf condition. C2.1.4 of [Elephant]. -/ lemma yoneda_condition_iff_sheaf_condition : is_sheaf_for P S ↔ yoneda_sheaf_condition P S := begin rw [is_sheaf_for, yoneda_sheaf_condition], simp_rw [extension_iff_amalgamation], rw equiv.forall_congr_left' nat_trans_equiv_compatible_family, rw subtype.forall, apply ball_congr, intros x hx, rw equiv.exists_unique_congr_left _, simp, end /-- `P` is a sheaf for `R` iff it is separated for `R` and there exists an amalgamation. -/ lemma is_separated_for_and_exists_is_amalgamation_iff_sheaf_for : is_separated_for P R ∧ (∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) ↔ is_sheaf_for P R := begin rw [is_separated_for, ←forall_and_distrib], apply forall_congr, intro x, split, { intros z hx, exact exists_unique_of_exists_of_unique (z.2 hx) z.1 }, { intros h, refine ⟨_, (exists_of_exists_unique ∘ h)⟩, intros t₁ t₂ ht₁ ht₂, apply (h _).unique ht₁ ht₂, exact is_compatible_of_exists_amalgamation x ⟨_, ht₂⟩ } end /-- If `P` is separated for `R` and every family has an amalgamation, then `P` is a sheaf for `R`. -/ lemma is_separated_for.is_sheaf_for (t : is_separated_for P R) : (∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) → is_sheaf_for P R := begin rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, exact and.intro t, end /-- If `P` is a sheaf for `R`, it is separated for `R`. -/ lemma is_sheaf_for.is_separated_for : is_sheaf_for P R → is_separated_for P R := λ q, (is_separated_for_and_exists_is_amalgamation_iff_sheaf_for.2 q).1 /-- Get the amalgamation of the given compatible family, provided we have a sheaf. -/ noncomputable def is_sheaf_for.amalgamate (t : is_sheaf_for P R) (x : family_of_elements P R) (hx : x.compatible) : P.obj (op X) := classical.some (t x hx).exists lemma is_sheaf_for.is_amalgamation (t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) : x.is_amalgamation (t.amalgamate x hx) := classical.some_spec (t x hx).exists @[simp] lemma is_sheaf_for.valid_glue (t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) (f : Y ⟶ X) (Hf : R f) : P.map f.op (t.amalgamate x hx) = x f Hf := t.is_amalgamation hx f Hf /-- C2.1.3 in [Elephant] -/ lemma is_sheaf_for_iff_generate : is_sheaf_for P R ↔ is_sheaf_for P (generate R) := begin rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, rw ← is_separated_for_iff_generate, apply and_congr (iff.refl _), split, { intros q x hx, apply exists_imp_exists _ (q _ (hx.restrict (le_generate R))), intros t ht, simpa [hx] using is_amalgamation_sieve_extend _ _ ht }, { intros q x hx, apply exists_imp_exists _ (q _ (hx.sieve_extend _)), intros t ht, simpa [hx] using is_amalgamation_restrict (le_generate R) _ _ ht }, end /-- Every presheaf is a sheaf for the family {𝟙 X}. [Elephant] C2.1.5(i) -/ lemma is_sheaf_for_singleton_iso (P : Cᵒᵖ ⥤ Type v) : is_sheaf_for P (presieve.singleton (𝟙 X)) := begin intros x hx, refine ⟨x _ (presieve.singleton_self _), _, _⟩, { rintro _ _ ⟨rfl, rfl⟩, simp }, { intros t ht, simpa using ht _ (presieve.singleton_self _) } end /-- Every presheaf is a sheaf for the maximal sieve. [Elephant] C2.1.5(ii) -/ lemma is_sheaf_for_top_sieve (P : Cᵒᵖ ⥤ Type v) : is_sheaf_for P ((⊤ : sieve X) : presieve X) := begin rw ← generate_of_singleton_split_epi (𝟙 X), rw ← is_sheaf_for_iff_generate, apply is_sheaf_for_singleton_iso, end /-- If `P` is a sheaf for `S`, and it is iso to `P'`, then `P'` is a sheaf for `S`. This shows that "being a sheaf for a presieve" is a mathematical or hygenic property. -/ lemma is_sheaf_for_iso {P' : Cᵒᵖ ⥤ Type v} (i : P ≅ P') : is_sheaf_for P R → is_sheaf_for P' R := begin rw [is_sheaf_for_iff_generate, yoneda_condition_iff_sheaf_condition, is_sheaf_for_iff_generate, yoneda_condition_iff_sheaf_condition], intros h f, obtain ⟨g, hg₁, hg₂⟩ := h (f ≫ i.inv), refine ⟨g ≫ i.hom, by simpa [iso.eq_comp_inv] using hg₁, _⟩, { intros g' hg', rw ← iso.comp_inv_eq, apply hg₂, rw reassoc_of hg' }, end /-- If a presieve `R` on `X` has a subsieve `S` such that: * `P` is a sheaf for `S`. * For every `f` in `R`, `P` is separated for the pullback of `S` along `f`, then `P` is a sheaf for `R`. This is closely related to [Elephant] C2.1.6(i). -/ lemma is_sheaf_for_subsieve_aux (P : Cᵒᵖ ⥤ Type v) {S : sieve X} {R : presieve X} (h : (S : presieve X) ≤ R) (hS : is_sheaf_for P S) (trans : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄, R f → is_separated_for P (S.pullback f)) : is_sheaf_for P R := begin rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, split, { intros x t₁ t₂ ht₁ ht₂, exact hS.is_separated_for _ _ _ (is_amalgamation_restrict h x t₁ ht₁) (is_amalgamation_restrict h x t₂ ht₂) }, { intros x hx, use hS.amalgamate _ (hx.restrict h), intros W j hj, apply (trans hj).ext, intros Y f hf, rw [←functor_to_types.map_comp_apply, ←op_comp, hS.valid_glue (hx.restrict h) _ hf, family_of_elements.restrict, ←hx (𝟙 _) f _ _ (id_comp _)], simp }, end /-- If `P` is a sheaf for every pullback of the sieve `S`, then `P` is a sheaf for any presieve which contains `S`. This is closely related to [Elephant] C2.1.6. -/ lemma is_sheaf_for_subsieve (P : Cᵒᵖ ⥤ Type v) {S : sieve X} {R : presieve X} (h : (S : presieve X) ≤ R) (trans : Π ⦃Y⦄ (f : Y ⟶ X), is_sheaf_for P (S.pullback f)) : is_sheaf_for P R := is_sheaf_for_subsieve_aux P h (by simpa using trans (𝟙 _)) (λ Y f hf, (trans f).is_separated_for) /-- A presheaf is separated for a topology if it is separated for every sieve in the topology. -/ def is_separated (P : Cᵒᵖ ⥤ Type v) : Prop := ∀ {X} (S : sieve X), S ∈ J X → is_separated_for P S /-- A presheaf is a sheaf for a topology if it is a sheaf for every sieve in the topology. If the given topology is given by a pretopology, `is_sheaf_for_pretopology` shows it suffices to check the sheaf condition at presieves in the pretopology. -/ def is_sheaf (P : Cᵒᵖ ⥤ Type v) : Prop := ∀ ⦃X⦄ (S : sieve X), S ∈ J X → is_sheaf_for P S lemma is_sheaf.is_sheaf_for {P : Cᵒᵖ ⥤ Type v} (hp : is_sheaf J P) (R : presieve X) (hr : generate R ∈ J X) : is_sheaf_for P R := is_sheaf_for_iff_generate.2 $ hp _ hr lemma is_sheaf_for_coarser_topology (P : Cᵒᵖ ⥤ Type v) {J₁ J₂ : grothendieck_topology C} : J₁ ≤ J₂ → is_sheaf J₂ P → is_sheaf J₁ P := λ h t X S hS, t S (h _ hS) lemma separated_of_sheaf (P : Cᵒᵖ ⥤ Type v) (h : is_sheaf J P) : is_separated J P := λ X S hS, (h S hS).is_separated_for /-- The property of being a sheaf is preserved by isomorphism. -/ lemma is_sheaf_iso {P' : Cᵒᵖ ⥤ Type v} (i : P ≅ P') (h : is_sheaf J P) : is_sheaf J P' := λ X S hS, is_sheaf_for_iso i (h S hS) lemma is_sheaf_yoneda (h : ∀ {X} (S : sieve X), S ∈ J X → yoneda_sheaf_condition P S) : is_sheaf J P := begin intros X S hS, rw yoneda_condition_iff_sheaf_condition, apply h _ hS, end /-- For a topology generated by a basis, it suffices to check the sheaf condition on the basis presieves only. -/ lemma is_sheaf_pretopology [has_pullbacks C] (K : pretopology C) : is_sheaf (K.to_grothendieck C) P ↔ (∀ {X : C} (R : presieve X), R ∈ K X → is_sheaf_for P R) := begin split, { intros PJ X R hR, rw is_sheaf_for_iff_generate, apply PJ (sieve.generate R) ⟨_, hR, le_generate R⟩ }, { rintro PK X S ⟨R, hR, RS⟩, have gRS : ⇑(generate R) ≤ S, { apply gi_generate.gc.monotone_u, rwa sets_iff_generate }, apply is_sheaf_for_subsieve P gRS _, intros Y f, rw [← pullback_arrows_comm, ← is_sheaf_for_iff_generate], exact PK (pullback_arrows f R) (K.pullbacks f R hR) } end end presieve namespace equalizer variables {C : Type v} [small_category C] (P : Cᵒᵖ ⥤ Type v) {X : C} (R : presieve X) (S : sieve X) noncomputable theory /-- The middle object of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram of https://stacks.math.columbia.edu/tag/00VM. -/ def first_obj : Type v := ∏ (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1)) /-- Show that `first_obj` is isomorphic to `family_of_elements`. -/ @[simps] def first_obj_eq_family : first_obj P R ≅ R.family_of_elements P := { hom := λ t Y f hf, pi.π (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1)) ⟨_, _, hf⟩ t, inv := pi.lift (λ f x, x _ f.2.2), hom_inv_id' := begin ext ⟨Y, f, hf⟩ p, simpa, end, inv_hom_id' := begin ext x Y f hf, apply limits.types.limit.lift_π_apply, end } instance : inhabited (first_obj P (⊥ : presieve X)) := ((first_obj_eq_family P _).to_equiv).inhabited /-- The left morphism of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram of https://stacks.math.columbia.edu/tag/00VM. -/ def fork_map : P.obj (op X) ⟶ first_obj P R := pi.lift (λ f, P.map f.2.1.op) /-! This section establishes the equivalence between the sheaf condition of Equation (3) [MM92] and the definition of `is_sheaf_for`. -/ namespace sieve /-- The rightmost object of the fork diagram of Equation (3) [MM92], which contains the data used to check a family is compatible. -/ def second_obj : Type v := ∏ (λ (f : Σ Y Z (g : Z ⟶ Y), {f' : Y ⟶ X // S f'}), P.obj (op f.2.1)) /-- The map `p` of Equations (3,4) [MM92]. -/ def first_map : first_obj P S ⟶ second_obj P S := pi.lift (λ fg, pi.π _ (⟨_, _, S.downward_closed fg.2.2.2.2 fg.2.2.1⟩ : Σ Y, {f : Y ⟶ X // S f})) instance : inhabited (second_obj P (⊥ : sieve X)) := ⟨first_map _ _ (default _)⟩ /-- The map `a` of Equations (3,4) [MM92]. -/ def second_map : first_obj P S ⟶ second_obj P S := pi.lift (λ fg, pi.π _ ⟨_, fg.2.2.2⟩ ≫ P.map fg.2.2.1.op) lemma w : fork_map P S ≫ first_map P S = fork_map P S ≫ second_map P S := begin apply limit.hom_ext, rintro ⟨Y, Z, g, f, hf⟩, simp [first_map, second_map, fork_map], end /-- The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map` map it to the same point. -/ lemma compatible_iff (x : first_obj P S) : ((first_obj_eq_family P S).hom x).compatible ↔ first_map P S x = second_map P S x := begin rw presieve.compatible_iff_sieve_compatible, split, { intro t, ext ⟨Y, Z, g, f, hf⟩, simpa [first_map, second_map] using t _ g hf }, { intros t Y Z f g hf, rw types.limit_ext_iff at t, simpa [first_map, second_map] using t ⟨Y, Z, g, f, hf⟩ } end /-- `P` is a sheaf for `S`, iff the fork given by `w` is an equalizer. -/ lemma equalizer_sheaf_condition : presieve.is_sheaf_for P S ↔ nonempty (is_limit (fork.of_ι _ (w P S))) := begin rw [types.type_equalizer_iff_unique, ← equiv.forall_congr_left (first_obj_eq_family P S).to_equiv.symm], simp_rw ← compatible_iff, simp only [inv_hom_id_apply, iso.to_equiv_symm_fun], apply ball_congr, intros x tx, apply exists_unique_congr, intro t, rw ← iso.to_equiv_symm_fun, rw equiv.eq_symm_apply, split, { intros q, ext Y f hf, simpa [first_obj_eq_family, fork_map] using q _ _ }, { intros q Y f hf, rw ← q, simp [first_obj_eq_family, fork_map] } end end sieve /-! This section establishes the equivalence between the sheaf condition of https://stacks.math.columbia.edu/tag/00VM and the definition of `is_sheaf_for`. -/ namespace presieve variables [has_pullbacks C] /-- The rightmost object of the fork diagram of https://stacks.math.columbia.edu/tag/00VM, which contains the data used to check a family of elements for a presieve is compatible. -/ def second_obj : Type v := ∏ (λ (fg : (Σ Y, {f : Y ⟶ X // R f}) × (Σ Z, {g : Z ⟶ X // R g})), P.obj (op (pullback fg.1.2.1 fg.2.2.1))) /-- The map `pr₀*` of https://stacks.math.columbia.edu/tag/00VL. -/ def first_map : first_obj P R ⟶ second_obj P R := pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.fst.op) instance : inhabited (second_obj P (⊥ : presieve X)) := ⟨first_map _ _ (default _)⟩ /-- The map `pr₁*` of https://stacks.math.columbia.edu/tag/00VL. -/ def second_map : first_obj P R ⟶ second_obj P R := pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.snd.op) lemma w : fork_map P R ≫ first_map P R = fork_map P R ≫ second_map P R := begin apply limit.hom_ext, rintro ⟨⟨Y, f, hf⟩, ⟨Z, g, hg⟩⟩, simp only [first_map, second_map, fork_map], simp only [limit.lift_π, limit.lift_π_assoc, assoc, fan.mk_π_app, subtype.coe_mk, subtype.val_eq_coe], rw [← P.map_comp, ← op_comp, pullback.condition], simp, end /-- The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map` map it to the same point. -/ lemma compatible_iff (x : first_obj P R) : ((first_obj_eq_family P R).hom x).compatible ↔ first_map P R x = second_map P R x := begin rw presieve.pullback_compatible_iff, split, { intro t, ext ⟨⟨Y, f, hf⟩, Z, g, hg⟩, simpa [first_map, second_map] using t hf hg }, { intros t Y Z f g hf hg, rw types.limit_ext_iff at t, simpa [first_map, second_map] using t ⟨⟨Y, f, hf⟩, Z, g, hg⟩ } end /-- `P` is a sheaf for `R`, iff the fork given by `w` is an equalizer. See https://stacks.math.columbia.edu/tag/00VM. -/ lemma sheaf_condition : R.is_sheaf_for P ↔ nonempty (is_limit (fork.of_ι _ (w P R))) := begin rw types.type_equalizer_iff_unique, erw ← equiv.forall_congr_left (first_obj_eq_family P R).to_equiv.symm, simp_rw [← compatible_iff, ← iso.to_equiv_fun, equiv.apply_symm_apply], apply ball_congr, intros x hx, apply exists_unique_congr, intros t, rw equiv.eq_symm_apply, split, { intros q, ext Y f hf, simpa [fork_map] using q _ _ }, { intros q Y f hf, rw ← q, simp [fork_map] } end end presieve end equalizer variables {C : Type u} [category.{v} C] variables (J : grothendieck_topology C) /-- The category of sheaves on a grothendieck topology. -/ @[derive category] def Sheaf (J : grothendieck_topology C) : Type (max u (v+1)) := {P : Cᵒᵖ ⥤ Type v // presieve.is_sheaf J P} instance : inhabited (Sheaf (⊥ : grothendieck_topology C)) := ⟨⟨(functor.const _).obj punit, λ X S hS, begin simp only [grothendieck_topology.bot_covering] at hS, subst hS, apply presieve.is_sheaf_for_top_sieve, end⟩⟩ /-- The inclusion functor from sheaves to presheaves. -/ @[simps {rhs_md := semireducible}, derive [full, faithful]] def Sheaf_to_presheaf : Sheaf J ⥤ (Cᵒᵖ ⥤ Type v) := full_subcategory_inclusion (presieve.is_sheaf J) end category_theory
bc8831b08e134db807ee69b6f631af640f0a6396
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/eq_class_error.lean
2c0cc5fd218fbe7b78f567dcbb0ce0c974551050
[ "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
621
lean
inductive foo := | a | b open foo -- This test demonstrates we need to disable local instances. set_option elaborator.local_instances false definition decidable_eq_foo [instance] : ∀ f₁ f₂ : foo, decidable (f₁ = f₂) | a a := by left; reflexivity | a b := by right; contradiction | b a := by right; contradiction -- If we don't disable the local_instances, then type class resolution synthesizes the term (decidable_eq_foo b b) which is not a -- valid "recursive application", and the recursive equation compiler fails with a cryptic message saying we should try to use well-founded recursion. | b b := _
bd62f90675898791313c86e466ce3e56650c98b8
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/data/set/lattice.lean
2aa3de791fb5586db63622c02695eb04faf301d7
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
34,287
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -- QUESTION: can make the first argument in ∀ x ∈ a, ... implicit? -/ import order.complete_boolean_algebra import data.sigma.basic import order.galois_connection open function tactic set auto universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {ι' : Sort y} namespace set instance lattice_set : complete_lattice (set α) := { le := (⊆), lt := (⊂), sup := (∪), inf := (∩), top := univ, bot := ∅, Sup := λs, {a | ∃ t ∈ s, a ∈ t }, Inf := λs, {a | ∀ t ∈ s, a ∈ t }, le_Sup := assume s t t_in a a_in, ⟨t, ⟨t_in, a_in⟩⟩, Sup_le := assume s t h a ⟨t', ⟨t'_in, a_in⟩⟩, h t' t'_in a_in, le_Inf := assume s t h a a_in t' t'_in, h t' t'_in a_in, Inf_le := assume s t t_in a h, h _ t_in, .. (infer_instance : complete_lattice (α → Prop)) } instance : distrib_lattice (set α) := { le_sup_inf := λ s t u x, or_and_distrib_left.2, ..set.lattice_set } /-- Image is monotone. See `set.image_image` for the statement in terms of `⊆`. -/ lemma monotone_image {f : α → β} : monotone (image f) := assume s t, assume h : s ⊆ t, image_subset _ h theorem monotone_inter [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λx, f x ∩ g x) := assume b₁ b₂ h, inter_subset_inter (hf h) (hg h) theorem monotone_union [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λx, f x ∪ g x) := assume b₁ b₂ h, union_subset_union (hf h) (hg h) theorem monotone_set_of [preorder α] {p : α → β → Prop} (hp : ∀b, monotone (λa, p a b)) : monotone (λa, {b | p a b}) := assume a a' h b, hp b h section galois_connection variables {f : α → β} protected lemma image_preimage : galois_connection (image f) (preimage f) := assume a b, image_subset_iff /-- `kern_image f s` is the set of `y` such that `f ⁻¹ y ⊆ s` -/ def kern_image (f : α → β) (s : set α) : set β := {y | ∀ ⦃x⦄, f x = y → x ∈ s} protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) := assume a b, ⟨ assume h x hx y hy, have f y ∈ a, from hy.symm ▸ hx, h this, assume h x (hx : f x ∈ a), h hx rfl⟩ end galois_connection /- union and intersection over a family of sets indexed by a type -/ /-- Indexed union of a family of sets -/ @[reducible] def Union (s : ι → set β) : set β := supr s /-- Indexed intersection of a family of sets -/ @[reducible] def Inter (s : ι → set β) : set β := infi s notation `⋃` binders `, ` r:(scoped f, Union f) := r notation `⋂` binders `, ` r:(scoped f, Inter f) := r @[simp] theorem mem_Union {x : β} {s : ι → set β} : x ∈ Union s ↔ ∃ i, x ∈ s i := ⟨assume ⟨t, ⟨⟨a, (t_eq : s a = t)⟩, (h : x ∈ t)⟩⟩, ⟨a, t_eq.symm ▸ h⟩, assume ⟨a, h⟩, ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩ /- alternative proof: dsimp [Union, supr, Sup]; simp -/ -- TODO: more rewrite rules wrt forall / existentials and logical connectives -- TODO: also eliminate ∃i, ... ∧ i = t ∧ ... theorem set_of_exists (p : ι → β → Prop) : {x | ∃ i, p i x} = ⋃ i, {x | p i x} := ext $ λ i, mem_Union.symm @[simp] theorem mem_Inter {x : β} {s : ι → set β} : x ∈ Inter s ↔ ∀ i, x ∈ s i := ⟨assume (h : ∀a ∈ {a : set β | ∃i, s i = a}, x ∈ a) a, h (s a) ⟨a, rfl⟩, assume h t ⟨a, (eq : s a = t)⟩, eq ▸ h a⟩ theorem set_of_forall (p : ι → β → Prop) : {x | ∀ i, p i x} = ⋂ i, {x | p i x} := ext $ λ i, mem_Inter.symm theorem Union_subset {s : ι → set β} {t : set β} (h : ∀ i, s i ⊆ t) : (⋃ i, s i) ⊆ t := -- TODO: should be simpler when sets' order is based on lattices @supr_le (set β) _ set.lattice_set _ _ h theorem Union_subset_iff {s : ι → set β} {t : set β} : (⋃ i, s i) ⊆ t ↔ (∀ i, s i ⊆ t) := ⟨assume h i, subset.trans (le_supr s _) h, Union_subset⟩ theorem mem_Inter_of_mem {x : β} {s : ι → set β} : (∀ i, x ∈ s i) → (x ∈ ⋂ i, s i) := mem_Inter.2 theorem subset_Inter {t : set β} {s : ι → set β} (h : ∀ i, t ⊆ s i) : t ⊆ ⋂ i, s i := -- TODO: should be simpler when sets' order is based on lattices @le_infi (set β) _ set.lattice_set _ _ h theorem subset_Union : ∀ (s : ι → set β) (i : ι), s i ⊆ (⋃ i, s i) := le_supr theorem Inter_subset : ∀ (s : ι → set β) (i : ι), (⋂ i, s i) ⊆ s i := infi_le lemma Inter_subset_of_subset {s : ι → set α} {t : set α} (i : ι) (h : s i ⊆ t) : (⋂ i, s i) ⊆ t := set.subset.trans (set.Inter_subset s i) h lemma Inter_subset_Inter {s t : ι → set α} (h : ∀ i, s i ⊆ t i) : (⋂ i, s i) ⊆ (⋂ i, t i) := set.subset_Inter $ λ i, set.Inter_subset_of_subset i (h i) lemma Inter_subset_Inter2 {s : ι → set α} {t : ι' → set α} (h : ∀ j, ∃ i, s i ⊆ t j) : (⋂ i, s i) ⊆ (⋂ j, t j) := set.subset_Inter $ λ j, let ⟨i, hi⟩ := h j in Inter_subset_of_subset i hi theorem Union_const [nonempty ι] (s : set β) : (⋃ i:ι, s) = s := ext $ by simp theorem Inter_const [nonempty ι] (s : set β) : (⋂ i:ι, s) = s := ext $ by simp @[simp] -- complete_boolean_algebra theorem compl_Union (s : ι → set β) : - (⋃ i, s i) = (⋂ i, - s i) := ext (by simp) -- classical -- complete_boolean_algebra theorem compl_Inter (s : ι → set β) : -(⋂ i, s i) = (⋃ i, - s i) := ext (λ x, by simp [classical.not_forall]) -- classical -- complete_boolean_algebra theorem Union_eq_comp_Inter_comp (s : ι → set β) : (⋃ i, s i) = - (⋂ i, - s i) := by simp [compl_Inter, compl_compl] -- classical -- complete_boolean_algebra theorem Inter_eq_comp_Union_comp (s : ι → set β) : (⋂ i, s i) = - (⋃ i, -s i) := by simp [compl_compl] theorem inter_Union (s : set β) (t : ι → set β) : s ∩ (⋃ i, t i) = ⋃ i, s ∩ t i := ext $ by simp theorem Union_inter (s : set β) (t : ι → set β) : (⋃ i, t i) ∩ s = ⋃ i, t i ∩ s := ext $ by simp theorem Union_union_distrib (s : ι → set β) (t : ι → set β) : (⋃ i, s i ∪ t i) = (⋃ i, s i) ∪ (⋃ i, t i) := ext $ by simp [exists_or_distrib] theorem Inter_inter_distrib (s : ι → set β) (t : ι → set β) : (⋂ i, s i ∩ t i) = (⋂ i, s i) ∩ (⋂ i, t i) := ext $ by simp [forall_and_distrib] theorem union_Union [nonempty ι] (s : set β) (t : ι → set β) : s ∪ (⋃ i, t i) = ⋃ i, s ∪ t i := by rw [Union_union_distrib, Union_const] theorem Union_union [nonempty ι] (s : set β) (t : ι → set β) : (⋃ i, t i) ∪ s = ⋃ i, t i ∪ s := by rw [Union_union_distrib, Union_const] theorem inter_Inter [nonempty ι] (s : set β) (t : ι → set β) : s ∩ (⋂ i, t i) = ⋂ i, s ∩ t i := by rw [Inter_inter_distrib, Inter_const] theorem Inter_inter [nonempty ι] (s : set β) (t : ι → set β) : (⋂ i, t i) ∩ s = ⋂ i, t i ∩ s := by rw [Inter_inter_distrib, Inter_const] -- classical theorem union_Inter (s : set β) (t : ι → set β) : s ∪ (⋂ i, t i) = ⋂ i, s ∪ t i := ext $ assume x, by simp [classical.forall_or_distrib_left] theorem Union_diff (s : set β) (t : ι → set β) : (⋃ i, t i) \ s = ⋃ i, t i \ s := Union_inter _ _ theorem diff_Union [nonempty ι] (s : set β) (t : ι → set β) : s \ (⋃ i, t i) = ⋂ i, s \ t i := by rw [diff_eq, compl_Union, inter_Inter]; refl theorem diff_Inter (s : set β) (t : ι → set β) : s \ (⋂ i, t i) = ⋃ i, s \ t i := by rw [diff_eq, compl_Inter, inter_Union]; refl lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊆) f) (h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) := by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact assume a₁ b₁ fb₁ a₂ b₂ fb₂, let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂, ⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in ⟨x, ⟨z, xf⟩, xa₁, xa₂⟩ /- bounded unions and intersections -/ theorem mem_bUnion_iff {s : set α} {t : α → set β} {y : β} : y ∈ (⋃ x ∈ s, t x) ↔ ∃ x ∈ s, y ∈ t x := by simp theorem mem_bInter_iff {s : set α} {t : α → set β} {y : β} : y ∈ (⋂ x ∈ s, t x) ↔ ∀ x ∈ s, y ∈ t x := by simp theorem mem_bUnion {s : set α} {t : α → set β} {x : α} {y : β} (xs : x ∈ s) (ytx : y ∈ t x) : y ∈ ⋃ x ∈ s, t x := by simp; exact ⟨x, ⟨xs, ytx⟩⟩ theorem mem_bInter {s : set α} {t : α → set β} {y : β} (h : ∀ x ∈ s, y ∈ t x) : y ∈ ⋂ x ∈ s, t x := by simp; assumption theorem bUnion_subset {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, u x ⊆ t) : (⋃ x ∈ s, u x) ⊆ t := show (⨆ x ∈ s, u x) ≤ t, -- TODO: should not be necessary when sets' order is based on lattices from supr_le $ assume x, supr_le (h x) theorem subset_bInter {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, t ⊆ u x) : t ⊆ (⋂ x ∈ s, u x) := subset_Inter $ assume x, subset_Inter $ h x theorem subset_bUnion_of_mem {s : set α} {u : α → set β} {x : α} (xs : x ∈ s) : u x ⊆ (⋃ x ∈ s, u x) := show u x ≤ (⨆ x ∈ s, u x), from le_supr_of_le x $ le_supr _ xs theorem bInter_subset_of_mem {s : set α} {t : α → set β} {x : α} (xs : x ∈ s) : (⋂ x ∈ s, t x) ⊆ t x := show (⨅x ∈ s, t x) ≤ t x, from infi_le_of_le x $ infi_le _ xs theorem bUnion_subset_bUnion_left {s s' : set α} {t : α → set β} (h : s ⊆ s') : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s', t x) := bUnion_subset (λ x xs, subset_bUnion_of_mem (h xs)) theorem bInter_subset_bInter_left {s s' : set α} {t : α → set β} (h : s' ⊆ s) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s', t x) := subset_bInter (λ x xs, bInter_subset_of_mem (h xs)) theorem bUnion_subset_bUnion_right {s : set α} {t1 t2 : α → set β} (h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋃ x ∈ s, t1 x) ⊆ (⋃ x ∈ s, t2 x) := bUnion_subset (λ x xs, subset.trans (h x xs) (subset_bUnion_of_mem xs)) theorem bInter_subset_bInter_right {s : set α} {t1 t2 : α → set β} (h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋂ x ∈ s, t1 x) ⊆ (⋂ x ∈ s, t2 x) := subset_bInter (λ x xs, subset.trans (bInter_subset_of_mem xs) (h x xs)) theorem bUnion_eq_Union (s : set α) (t : α → set β) : (⋃ x ∈ s, t x) = (⋃ x : s, t x.1) := set.ext $ by simp theorem bInter_eq_Inter (s : set α) (t : α → set β) : (⋂ x ∈ s, t x) = (⋂ x : s, t x.1) := set.ext $ by simp theorem bInter_empty (u : α → set β) : (⋂ x ∈ (∅ : set α), u x) = univ := show (⨅x ∈ (∅ : set α), u x) = ⊤, -- simplifier should be able to rewrite x ∈ ∅ to false. from infi_emptyset theorem bInter_univ (u : α → set β) : (⋂ x ∈ @univ α, u x) = ⋂ x, u x := infi_univ -- TODO(Jeremy): here is an artifact of the the encoding of bounded intersection: -- without dsimp, the next theorem fails to type check, because there is a lambda -- in a type that needs to be contracted. Using simp [eq_of_mem_singleton xa] also works. @[simp] theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : set α), s x) = s a := show (⨅ x ∈ ({a} : set α), s x) = s a, by simp theorem bInter_union (s t : set α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := show (⨅ x ∈ s ∪ t, u x) = (⨅ x ∈ s, u x) ⊓ (⨅ x ∈ t, u x), from infi_union -- TODO(Jeremy): simp [insert_eq, bInter_union] doesn't work @[simp] theorem bInter_insert (a : α) (s : set α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := begin rw insert_eq, simp [bInter_union] end -- TODO(Jeremy): another example of where an annotation is needed theorem bInter_pair (a b : α) (s : α → set β) : (⋂ x ∈ ({a, b} : set α), s x) = s a ∩ s b := by simp [inter_comm] theorem bUnion_empty (s : α → set β) : (⋃ x ∈ (∅ : set α), s x) = ∅ := supr_emptyset theorem bUnion_univ (s : α → set β) : (⋃ x ∈ @univ α, s x) = ⋃ x, s x := supr_univ @[simp] theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : set α), s x) = s a := supr_singleton @[simp] theorem bUnion_of_singleton (s : set α) : (⋃ x ∈ s, {x}) = s := ext $ by simp theorem bUnion_union (s t : set α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union -- TODO(Jeremy): once again, simp doesn't do it alone. @[simp] theorem bUnion_insert (a : α) (s : set α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := begin rw [insert_eq], simp [bUnion_union] end theorem bUnion_pair (a b : α) (s : α → set β) : (⋃ x ∈ ({a, b} : set α), s x) = s a ∪ s b := by simp [union_comm] @[simp] -- complete_boolean_algebra theorem compl_bUnion (s : set α) (t : α → set β) : - (⋃ i ∈ s, t i) = (⋂ i ∈ s, - t i) := ext (λ x, by simp) -- classical -- complete_boolean_algebra theorem compl_bInter (s : set α) (t : α → set β) : -(⋂ i ∈ s, t i) = (⋃ i ∈ s, - t i) := ext (λ x, by simp [classical.not_forall]) theorem inter_bUnion (s : set α) (t : α → set β) (u : set β) : u ∩ (⋃ i ∈ s, t i) = ⋃ i ∈ s, u ∩ t i := begin ext x, simp only [exists_prop, mem_Union, mem_inter_eq], exact ⟨λ ⟨hx, ⟨i, is, xi⟩⟩, ⟨i, is, hx, xi⟩, λ ⟨i, is, hx, xi⟩, ⟨hx, ⟨i, is, xi⟩⟩⟩ end theorem bUnion_inter (s : set α) (t : α → set β) (u : set β) : (⋃ i ∈ s, t i) ∩ u = (⋃ i ∈ s, t i ∩ u) := by simp [@inter_comm _ _ u, inter_bUnion] /-- Intersection of a set of sets. -/ @[reducible] def sInter (S : set (set α)) : set α := Inf S prefix `⋂₀`:110 := sInter theorem mem_sUnion_of_mem {x : α} {t : set α} {S : set (set α)} (hx : x ∈ t) (ht : t ∈ S) : x ∈ ⋃₀ S := ⟨t, ⟨ht, hx⟩⟩ theorem mem_sUnion {x : α} {S : set (set α)} : x ∈ ⋃₀ S ↔ ∃t ∈ S, x ∈ t := iff.rfl -- is this theorem really necessary? theorem not_mem_of_not_mem_sUnion {x : α} {t : set α} {S : set (set α)} (hx : x ∉ ⋃₀ S) (ht : t ∈ S) : x ∉ t := λ h, hx ⟨t, ht, h⟩ @[simp] theorem mem_sInter {x : α} {S : set (set α)} : x ∈ ⋂₀ S ↔ ∀ t ∈ S, x ∈ t := iff.rfl theorem sInter_subset_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : ⋂₀ S ⊆ t := Inf_le tS theorem subset_sUnion_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : t ⊆ ⋃₀ S := le_Sup tS lemma subset_sUnion_of_subset {s : set α} (t : set (set α)) (u : set α) (h₁ : s ⊆ u) (h₂ : u ∈ t) : s ⊆ ⋃₀ t := subset.trans h₁ (subset_sUnion_of_mem h₂) theorem sUnion_subset {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t' ⊆ t) : (⋃₀ S) ⊆ t := Sup_le h theorem sUnion_subset_iff {s : set (set α)} {t : set α} : ⋃₀ s ⊆ t ↔ ∀t' ∈ s, t' ⊆ t := ⟨assume h t' ht', subset.trans (subset_sUnion_of_mem ht') h, sUnion_subset⟩ theorem subset_sInter {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t ⊆ t') : t ⊆ (⋂₀ S) := le_Inf h theorem sUnion_subset_sUnion {S T : set (set α)} (h : S ⊆ T) : ⋃₀ S ⊆ ⋃₀ T := sUnion_subset $ λ s hs, subset_sUnion_of_mem (h hs) theorem sInter_subset_sInter {S T : set (set α)} (h : S ⊆ T) : ⋂₀ T ⊆ ⋂₀ S := subset_sInter $ λ s hs, sInter_subset_of_mem (h hs) @[simp] theorem sUnion_empty : ⋃₀ ∅ = (∅ : set α) := Sup_empty @[simp] theorem sInter_empty : ⋂₀ ∅ = (univ : set α) := Inf_empty @[simp] theorem sUnion_singleton (s : set α) : ⋃₀ {s} = s := Sup_singleton @[simp] theorem sInter_singleton (s : set α) : ⋂₀ {s} = s := Inf_singleton theorem sUnion_union (S T : set (set α)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := Sup_union theorem sInter_union (S T : set (set α)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := Inf_union theorem sInter_Union (s : ι → set (set α)) : ⋂₀ (⋃ i, s i) = ⋂ i, ⋂₀ s i := begin ext x, simp only [mem_Union, mem_Inter, mem_sInter, exists_imp_distrib], split ; tauto end @[simp] theorem sUnion_insert (s : set α) (T : set (set α)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T := Sup_insert @[simp] theorem sInter_insert (s : set α) (T : set (set α)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T := Inf_insert theorem sUnion_pair (s t : set α) : ⋃₀ {s, t} = s ∪ t := Sup_pair theorem sInter_pair (s t : set α) : ⋂₀ {s, t} = s ∩ t := Inf_pair @[simp] theorem sUnion_image (f : α → set β) (s : set α) : ⋃₀ (f '' s) = ⋃ x ∈ s, f x := Sup_image @[simp] theorem sInter_image (f : α → set β) (s : set α) : ⋂₀ (f '' s) = ⋂ x ∈ s, f x := Inf_image @[simp] theorem sUnion_range (f : ι → set β) : ⋃₀ (range f) = ⋃ x, f x := Sup_range @[simp] theorem sInter_range (f : ι → set β) : ⋂₀ (range f) = ⋂ x, f x := Inf_range lemma sUnion_eq_univ_iff {c : set (set α)} : ⋃₀ c = @set.univ α ↔ ∀ a, ∃ b ∈ c, a ∈ b := ⟨λ H a, let ⟨b, hm, hb⟩ := mem_sUnion.1 $ by rw H; exact mem_univ a in ⟨b, hm, hb⟩, λ H, set.univ_subset_iff.1 $ λ x hx, let ⟨b, hm, hb⟩ := H x in set.mem_sUnion_of_mem hb hm⟩ theorem compl_sUnion (S : set (set α)) : - ⋃₀ S = ⋂₀ (compl '' S) := set.ext $ assume x, ⟨assume : ¬ (∃s∈S, x ∈ s), assume s h, match s, h with ._, ⟨t, hs, rfl⟩ := assume h, this ⟨t, hs, h⟩ end, assume : ∀s, s ∈ compl '' S → x ∈ s, assume ⟨t, tS, xt⟩, this (compl t) (mem_image_of_mem _ tS) xt⟩ -- classical theorem sUnion_eq_compl_sInter_compl (S : set (set α)) : ⋃₀ S = - ⋂₀ (compl '' S) := by rw [←compl_compl (⋃₀ S), compl_sUnion] -- classical theorem compl_sInter (S : set (set α)) : - ⋂₀ S = ⋃₀ (compl '' S) := by rw [sUnion_eq_compl_sInter_compl, compl_compl_image] -- classical theorem sInter_eq_comp_sUnion_compl (S : set (set α)) : ⋂₀ S = -(⋃₀ (compl '' S)) := by rw [←compl_compl (⋂₀ S), compl_sInter] theorem inter_empty_of_inter_sUnion_empty {s t : set α} {S : set (set α)} (hs : t ∈ S) (h : s ∩ ⋃₀ S = ∅) : s ∩ t = ∅ := eq_empty_of_subset_empty $ by rw ← h; exact inter_subset_inter_right _ (subset_sUnion_of_mem hs) theorem range_sigma_eq_Union_range {γ : α → Type*} (f : sigma γ → β) : range f = ⋃ a, range (λ b, f ⟨a, b⟩) := set.ext $ by simp theorem Union_eq_range_sigma (s : α → set β) : (⋃ i, s i) = range (λ a : Σ i, s i, a.2) := by simp [set.ext_iff] theorem Union_image_preimage_sigma_mk_eq_self {ι : Type*} {σ : ι → Type*} (s : set (sigma σ)) : (⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s)) = s := begin ext x, simp only [mem_Union, mem_image, mem_preimage], split, { rintros ⟨i, a, h, rfl⟩, exact h }, { intro h, cases x with i a, exact ⟨i, a, h, rfl⟩ } end lemma sUnion_mono {s t : set (set α)} (h : s ⊆ t) : (⋃₀ s) ⊆ (⋃₀ t) := sUnion_subset $ assume t' ht', subset_sUnion_of_mem $ h ht' lemma Union_subset_Union {s t : ι → set α} (h : ∀i, s i ⊆ t i) : (⋃i, s i) ⊆ (⋃i, t i) := @supr_le_supr (set α) ι _ s t h lemma Union_subset_Union2 {ι₂ : Sort*} {s : ι → set α} {t : ι₂ → set α} (h : ∀i, ∃j, s i ⊆ t j) : (⋃i, s i) ⊆ (⋃i, t i) := @supr_le_supr2 (set α) ι ι₂ _ s t h lemma Union_subset_Union_const {ι₂ : Sort x} {s : set α} (h : ι → ι₂) : (⋃ i:ι, s) ⊆ (⋃ j:ι₂, s) := @supr_le_supr_const (set α) ι ι₂ _ s h @[simp] lemma Union_of_singleton (α : Type u) : (⋃(x : α), {x}) = @set.univ α := ext $ λ x, ⟨λ h, ⟨⟩, λ h, ⟨{x}, ⟨⟨x, rfl⟩, mem_singleton x⟩⟩⟩ theorem bUnion_subset_Union (s : set α) (t : α → set β) : (⋃ x ∈ s, t x) ⊆ (⋃ x, t x) := Union_subset_Union $ λ i, Union_subset $ λ h, by refl lemma sUnion_eq_bUnion {s : set (set α)} : (⋃₀ s) = (⋃ (i : set α) (h : i ∈ s), i) := set.ext $ by simp lemma sInter_eq_bInter {s : set (set α)} : (⋂₀ s) = (⋂ (i : set α) (h : i ∈ s), i) := set.ext $ by simp lemma sUnion_eq_Union {s : set (set α)} : (⋃₀ s) = (⋃ (i : s), i.1) := set.ext $ λ x, by simp lemma sInter_eq_Inter {s : set (set α)} : (⋂₀ s) = (⋂ (i : s), i.1) := set.ext $ λ x, by simp lemma union_eq_Union {s₁ s₂ : set α} : s₁ ∪ s₂ = ⋃ b : bool, cond b s₁ s₂ := set.ext $ λ x, by simp [bool.exists_bool, or_comm] lemma inter_eq_Inter {s₁ s₂ : set α} : s₁ ∩ s₂ = ⋂ b : bool, cond b s₁ s₂ := set.ext $ λ x, by simp [bool.forall_bool, and_comm] instance : complete_boolean_algebra (set α) := { neg := compl, sub := (\), le_sup_inf := distrib_lattice.le_sup_inf, inf_compl_eq_bot := assume s, ext $ assume x, ⟨assume ⟨h, nh⟩, nh h, false.elim⟩, sup_compl_eq_top := assume s, ext $ assume x, ⟨assume h, trivial, assume _, classical.em $ x ∈ s⟩, sub_eq := assume x y, rfl, infi_sup_le_sup_Inf := assume s t x, show x ∈ (⋂ b ∈ t, s ∪ b) → x ∈ s ∪ (⋂₀ t), by simp; exact assume h, or.imp_right (assume hn : x ∉ s, assume i hi, or.resolve_left (h i hi) hn) (classical.em $ x ∈ s), inf_Sup_le_supr_inf := assume s t x, show x ∈ s ∩ (⋃₀ t) → x ∈ (⋃ b ∈ t, s ∩ b), by simp [-and_imp, and.left_comm], ..set.lattice_set } lemma sInter_union_sInter {S T : set (set α)} : (⋂₀S) ∪ (⋂₀T) = (⋂p ∈ set.prod S T, (p : (set α) × (set α)).1 ∪ p.2) := Inf_sup_Inf lemma sUnion_inter_sUnion {s t : set (set α)} : (⋃₀s) ∩ (⋃₀t) = (⋃p ∈ set.prod s t, (p : (set α) × (set α )).1 ∩ p.2) := Sup_inf_Sup lemma sInter_bUnion {S : set (set α)} {T : set α → set (set α)} (hT : ∀s∈S, s = ⋂₀ T s) : ⋂₀ (⋃s∈S, T s) = ⋂₀ S := begin ext, simp only [and_imp, exists_prop, set.mem_sInter, set.mem_Union, exists_imp_distrib], split, { assume H s sS, rw [hT s sS, mem_sInter], assume t tTs, apply H t s sS tTs }, { assume H t s sS tTs, have xs : x ∈ s := H s sS, have : s ⊆ t, { have Z := hT s sS, rw sInter_eq_bInter at Z, rw Z, apply bInter_subset_of_mem, exact tTs }, exact this xs } end lemma sUnion_bUnion {S : set (set α)} {T : set α → set (set α)} (hT : ∀s∈S, s = ⋃₀ T s) : ⋃₀ (⋃s∈S, T s) = ⋃₀ S := begin ext, simp only [exists_prop, set.mem_Union, set.mem_set_of_eq], split, { rintros ⟨t, ⟨⟨s, ⟨sS, tTs⟩⟩, xt⟩⟩, refine ⟨s, ⟨sS, _⟩⟩, rw hT s sS, exact subset_sUnion_of_mem tTs xt }, { rintros ⟨s, ⟨sS, xs⟩⟩, rw hT s sS at xs, rcases mem_sUnion.1 xs with ⟨t, tTs, xt⟩, exact ⟨t, ⟨⟨s, ⟨sS, tTs⟩⟩, xt⟩⟩ } end lemma Union_range_eq_sUnion {α β : Type*} (C : set (set α)) {f : ∀(s : C), β → s} (hf : ∀(s : C), surjective (f s)) : (⋃(y : β), range (λ(s : C), (f s y).val)) = ⋃₀ C := begin ext x, split, { rintro ⟨s, ⟨y, rfl⟩, ⟨⟨s, hs⟩, rfl⟩⟩, refine ⟨_, hs, _⟩, exact (f ⟨s, hs⟩ y).2 }, { rintro ⟨s, hs, hx⟩, cases hf ⟨s, hs⟩ ⟨x, hx⟩ with y hy, refine ⟨_, ⟨y, rfl⟩, ⟨⟨s, hs⟩, _⟩⟩, exact congr_arg subtype.val hy } end lemma Union_range_eq_Union {ι α β : Type*} (C : ι → set α) {f : ∀(x : ι), β → C x} (hf : ∀(x : ι), surjective (f x)) : (⋃(y : β), range (λ(x : ι), (f x y).val)) = ⋃x, C x := begin ext x, rw [mem_Union, mem_Union], split, { rintro ⟨y, ⟨i, rfl⟩⟩, exact ⟨i, (f i y).2⟩ }, { rintro ⟨i, hx⟩, cases hf i ⟨x, hx⟩ with y hy, refine ⟨y, ⟨i, congr_arg subtype.val hy⟩⟩ } end @[simp] theorem sub_eq_diff (s t : set α) : s - t = s \ t := rfl section variables {p : Prop} {μ : p → set α} @[simp] lemma Inter_pos (hp : p) : (⋂h:p, μ h) = μ hp := infi_pos hp @[simp] lemma Inter_neg (hp : ¬ p) : (⋂h:p, μ h) = univ := infi_neg hp @[simp] lemma Union_pos (hp : p) : (⋃h:p, μ h) = μ hp := supr_pos hp @[simp] lemma Union_neg (hp : ¬ p) : (⋃h:p, μ h) = ∅ := supr_neg hp @[simp] lemma Union_empty {ι : Sort*} : (⋃i:ι, ∅:set α) = ∅ := supr_bot @[simp] lemma Inter_univ {ι : Sort*} : (⋂i:ι, univ:set α) = univ := infi_top end section image lemma image_Union {f : α → β} {s : ι → set α} : f '' (⋃ i, s i) = (⋃i, f '' s i) := begin apply set.ext, intro x, simp [image, exists_and_distrib_right.symm, -exists_and_distrib_right], exact exists_swap end lemma univ_subtype {p : α → Prop} : (univ : set (subtype p)) = (⋃x (h : p x), {⟨x, h⟩}) := set.ext $ assume ⟨x, h⟩, by simp [h] lemma range_eq_Union {ι} (f : ι → α) : range f = (⋃i, {f i}) := set.ext $ assume a, by simp [@eq_comm α a] lemma image_eq_Union (f : α → β) (s : set α) : f '' s = (⋃i∈s, {f i}) := set.ext $ assume b, by simp [@eq_comm β b] @[simp] lemma bUnion_range {f : ι → α} {g : α → set β} : (⋃x ∈ range f, g x) = (⋃y, g (f y)) := by rw [← sUnion_image, ← range_comp, sUnion_range] @[simp] lemma bInter_range {f : ι → α} {g : α → set β} : (⋂x ∈ range f, g x) = (⋂y, g (f y)) := by rw [← sInter_image, ← range_comp, sInter_range] variables {s : set γ} {f : γ → α} {g : α → set β} @[simp] lemma bUnion_image : (⋃x∈ (f '' s), g x) = (⋃y ∈ s, g (f y)) := by rw [← sUnion_image, ← image_comp, sUnion_image] @[simp] lemma bInter_image : (⋂x∈ (f '' s), g x) = (⋂y ∈ s, g (f y)) := by rw [← sInter_image, ← image_comp, sInter_image] end image section preimage theorem monotone_preimage {f : α → β} : monotone (preimage f) := assume a b h, preimage_mono h @[simp] theorem preimage_Union {ι : Sort w} {f : α → β} {s : ι → set β} : preimage f (⋃i, s i) = (⋃i, preimage f (s i)) := set.ext $ by simp [preimage] theorem preimage_bUnion {ι} {f : α → β} {s : set ι} {t : ι → set β} : preimage f (⋃i ∈ s, t i) = (⋃i ∈ s, preimage f (t i)) := by simp @[simp] theorem preimage_sUnion {f : α → β} {s : set (set β)} : preimage f (⋃₀ s) = (⋃t ∈ s, preimage f t) := set.ext $ by simp [preimage] lemma preimage_Inter {ι : Sort*} {s : ι → set β} {f : α → β} : f ⁻¹' (⋂ i, s i) = (⋂ i, f ⁻¹' s i) := by ext; simp lemma preimage_bInter {s : γ → set β} {t : set γ} {f : α → β} : f ⁻¹' (⋂ i∈t, s i) = (⋂ i∈t, f ⁻¹' s i) := by ext; simp end preimage section seq def seq (s : set (α → β)) (t : set α) : set β := {b | ∃f∈s, ∃a∈t, (f : α → β) a = b} lemma seq_def {s : set (α → β)} {t : set α} : seq s t = ⋃f∈s, f '' t := set.ext $ by simp [seq] @[simp] lemma mem_seq_iff {s : set (α → β)} {t : set α} {b : β} : b ∈ seq s t ↔ ∃ (f ∈ s) (a ∈ t), (f : α → β) a = b := iff.rfl lemma seq_subset {s : set (α → β)} {t : set α} {u : set β} : seq s t ⊆ u ↔ (∀f∈s, ∀a∈t, (f : α → β) a ∈ u) := iff.intro (assume h f hf a ha, h ⟨f, hf, a, ha, rfl⟩) (assume h b ⟨f, hf, a, ha, eq⟩, eq ▸ h f hf a ha) lemma seq_mono {s₀ s₁ : set (α → β)} {t₀ t₁ : set α} (hs : s₀ ⊆ s₁) (ht : t₀ ⊆ t₁) : seq s₀ t₀ ⊆ seq s₁ t₁ := assume b ⟨f, hf, a, ha, eq⟩, ⟨f, hs hf, a, ht ha, eq⟩ lemma singleton_seq {f : α → β} {t : set α} : set.seq {f} t = f '' t := set.ext $ by simp lemma seq_singleton {s : set (α → β)} {a : α} : set.seq s {a} = (λf:α→β, f a) '' s := set.ext $ by simp lemma seq_seq {s : set (β → γ)} {t : set (α → β)} {u : set α} : seq s (seq t u) = seq (seq ((∘) '' s) t) u := begin refine set.ext (assume c, iff.intro _ _), { rintros ⟨f, hfs, b, ⟨g, hg, a, hau, rfl⟩, rfl⟩, exact ⟨f ∘ g, ⟨(∘) f, mem_image_of_mem _ hfs, g, hg, rfl⟩, a, hau, rfl⟩ }, { rintros ⟨fg, ⟨fc, ⟨f, hfs, rfl⟩, g, hgt, rfl⟩, a, ha, rfl⟩, exact ⟨f, hfs, g a, ⟨g, hgt, a, ha, rfl⟩, rfl⟩ } end lemma image_seq {f : β → γ} {s : set (α → β)} {t : set α} : f '' seq s t = seq ((∘) f '' s) t := by rw [← singleton_seq, ← singleton_seq, seq_seq, image_singleton] lemma prod_eq_seq {s : set α} {t : set β} : set.prod s t = (prod.mk '' s).seq t := begin ext ⟨a, b⟩, split, { rintros ⟨ha, hb⟩, exact ⟨prod.mk a, ⟨a, ha, rfl⟩, b, hb, rfl⟩ }, { rintros ⟨f, ⟨x, hx, rfl⟩, y, hy, eq⟩, rw ← eq, exact ⟨hx, hy⟩ } end lemma prod_image_seq_comm (s : set α) (t : set β) : (prod.mk '' s).seq t = seq ((λb a, (a, b)) '' t) s := by rw [← prod_eq_seq, ← image_swap_prod, prod_eq_seq, image_seq, ← image_comp] end seq theorem monotone_prod [preorder α] {f : α → set β} {g : α → set γ} (hf : monotone f) (hg : monotone g) : monotone (λx, set.prod (f x) (g x)) := assume a b h, prod_mono (hf h) (hg h) instance : monad set := { pure := λ(α : Type u) a, {a}, bind := λ(α β : Type u) s f, ⋃i∈s, f i, seq := λ(α β : Type u), set.seq, map := λ(α β : Type u), set.image } instance : is_lawful_monad set := { pure_bind := assume α β x f, by simp, bind_assoc := assume α β γ s f g, set.ext $ assume a, by simp [exists_and_distrib_right.symm, -exists_and_distrib_right, exists_and_distrib_left.symm, -exists_and_distrib_left, and_assoc]; exact exists_swap, id_map := assume α, id_map, bind_pure_comp_eq_map := assume α β f s, set.ext $ by simp [set.image, eq_comm], bind_map_eq_seq := assume α β s t, by simp [seq_def] } instance : is_comm_applicative (set : Type u → Type u) := ⟨ assume α β s t, prod_image_seq_comm s t ⟩ section monad variables {α' β' : Type u} {s : set α'} {f : α' → set β'} {g : set (α' → β')} @[simp] lemma bind_def : s >>= f = ⋃i∈s, f i := rfl @[simp] lemma fmap_eq_image (f : α' → β') : f <$> s = f '' s := rfl @[simp] lemma seq_eq_set_seq {α β : Type*} (s : set (α → β)) (t : set α) : s <*> t = s.seq t := rfl @[simp] lemma pure_def (a : α) : (pure a : set α) = {a} := rfl end monad section pi lemma pi_def {α : Type*} {π : α → Type*} (i : set α) (s : Πa, set (π a)) : pi i s = (⋂ a∈i, ((λf:(Πa, π a), f a) ⁻¹' (s a))) := by ext; simp [pi] end pi end set /- disjoint sets -/ namespace set protected theorem disjoint_iff {s t : set α} : disjoint s t ↔ s ∩ t ⊆ ∅ := iff.rfl lemma not_disjoint_iff {s t : set α} : ¬disjoint s t ↔ ∃x, x ∈ s ∧ x ∈ t := (not_congr (set.disjoint_iff.trans subset_empty_iff)).trans ne_empty_iff_nonempty lemma disjoint_left {s t : set α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := show (∀ x, ¬(x ∈ s ∩ t)) ↔ _, from ⟨λ h a, not_and.1 $ h a, λ h a, not_and.2 $ h a⟩ theorem disjoint_right {s t : set α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_diff {a b : set α} : disjoint a (b \ a) := disjoint_iff.2 (inter_diff_self _ _) theorem disjoint_compl (s : set α) : disjoint s (-s) := assume a ⟨h₁, h₂⟩, h₂ h₁ theorem disjoint_singleton_left {a : α} {s : set α} : disjoint {a} s ↔ a ∉ s := by simp [set.disjoint_iff, subset_def]; exact iff.rfl theorem disjoint_singleton_right {a : α} {s : set α} : disjoint s {a} ↔ a ∉ s := by rw [disjoint.comm]; exact disjoint_singleton_left theorem disjoint_image_image {f : β → α} {g : γ → α} {s : set β} {t : set γ} (h : ∀b∈s, ∀c∈t, f b ≠ g c) : disjoint (f '' s) (g '' t) := by rintros a ⟨⟨b, hb, eq⟩, ⟨c, hc, rfl⟩⟩; exact h b hb c hc eq /-- A collection of sets is `pairwise_disjoint`, if any two different sets in this collection are disjoint. -/ def pairwise_disjoint (s : set (set α)) : Prop := pairwise_on s disjoint lemma pairwise_disjoint.subset {s t : set (set α)} (h : s ⊆ t) (ht : pairwise_disjoint t) : pairwise_disjoint s := pairwise_on.mono h ht lemma pairwise_disjoint.range {s : set (set α)} (f : s → set α) (hf : ∀(x : s), f x ⊆ x.1) (ht : pairwise_disjoint s) : pairwise_disjoint (range f) := begin rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy, refine (ht _ x.2 _ y.2 _).mono (hf x) (hf y), intro h, apply hxy, apply congr_arg f, exact subtype.eq h end /- warning: classical -/ lemma pairwise_disjoint.elim {s : set (set α)} (h : pairwise_disjoint s) {x y : set α} (hx : x ∈ s) (hy : y ∈ s) (z : α) (hzx : z ∈ x) (hzy : z ∈ y) : x = y := classical.not_not.1 $ λ h', h x hx y hy h' ⟨hzx, hzy⟩ end set namespace set variables (t : α → set β) def sigma_to_Union (x : Σi, t i) : (⋃i, t i) := ⟨x.2, mem_Union.2 ⟨x.1, x.2.2⟩⟩ lemma surjective_sigma_to_Union : surjective (sigma_to_Union t) | ⟨b, hb⟩ := have ∃a, b ∈ t a, by simpa using hb, let ⟨a, hb⟩ := this in ⟨⟨a, ⟨b, hb⟩⟩, rfl⟩ lemma injective_sigma_to_Union (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : injective (sigma_to_Union t) | ⟨a₁, ⟨b₁, h₁⟩⟩ ⟨a₂, ⟨b₂, h₂⟩⟩ eq := have b_eq : b₁ = b₂, from congr_arg subtype.val eq, have a_eq : a₁ = a₂, from classical.by_contradiction $ assume ne, have b₁ ∈ t a₁ ∩ t a₂, from ⟨h₁, b_eq.symm ▸ h₂⟩, h _ _ ne this, sigma.eq a_eq $ subtype.eq $ by subst b_eq; subst a_eq lemma bijective_sigma_to_Union (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : bijective (sigma_to_Union t) := ⟨injective_sigma_to_Union t h, surjective_sigma_to_Union t⟩ noncomputable def Union_eq_sigma_of_disjoint {t : α → set β} (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : (⋃i, t i) ≃ (Σi, t i) := (equiv.of_bijective $ bijective_sigma_to_Union t h).symm noncomputable def bUnion_eq_sigma_of_disjoint {s : set α} {t : α → set β} (h : pairwise_on s (disjoint on t)) : (⋃i∈s, t i) ≃ (Σi:s, t i.val) := equiv.trans (equiv.set_congr (bUnion_eq_Union _ _)) $ Union_eq_sigma_of_disjoint $ assume ⟨i, hi⟩ ⟨j, hj⟩ ne, h _ hi _ hj $ assume eq, ne $ subtype.eq eq end set
e22836667a36d732ad7e419d4ebd8895878d0f42
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebraic_topology/dold_kan/normalized.lean
e6e55b3f70a4decec8ff4ddacc699e881071aeac
[ "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
5,554
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebraic_topology.dold_kan.functor_n /-! # Comparison with the normalized Moore complex functor TODO (@joelriou) continue adding the various files referenced below In this file, we show that when the category `A` is abelian, there is an isomorphism `N₁_iso_normalized_Moore_complex_comp_to_karoubi` between the functor `N₁ : simplicial_object A ⥤ karoubi (chain_complex A ℕ)` defined in `functor_n.lean` and the composition of `normalized_Moore_complex A` with the inclusion `chain_complex A ℕ ⥤ karoubi (chain_complex A ℕ)`. This isomorphism shall be used in `equivalence.lean` in order to obtain the Dold-Kan equivalence `category_theory.abelian.dold_kan.equivalence : simplicial_object A ≌ chain_complex A ℕ` with a functor (definitionally) equal to `normalized_Moore_complex A`. -/ open category_theory category_theory.category category_theory.limits category_theory.subobject category_theory.idempotents open_locale dold_kan noncomputable theory namespace algebraic_topology namespace dold_kan universe v variables {A : Type*} [category A] [abelian A] {X : simplicial_object A} lemma higher_faces_vanish.inclusion_of_Moore_complex_map (n : ℕ) : higher_faces_vanish (n+1) ((inclusion_of_Moore_complex_map X).f (n+1)) := λ j hj, begin dsimp [inclusion_of_Moore_complex_map], rw [← factor_thru_arrow _ _ (finset_inf_arrow_factors finset.univ _ j (by simp only [finset.mem_univ])), assoc, kernel_subobject_arrow_comp, comp_zero], end lemma factors_normalized_Moore_complex_P_infty (n : ℕ) : subobject.factors (normalized_Moore_complex.obj_X X n) (P_infty.f n) := begin cases n, { apply top_factors, }, { rw [P_infty_f, normalized_Moore_complex.obj_X, finset_inf_factors], intros i hi, apply kernel_subobject_factors, exact (higher_faces_vanish.of_P (n+1) n) i (le_add_self), } end /-- P_infty factors through the normalized Moore complex -/ @[simps] def P_infty_to_normalized_Moore_complex (X : simplicial_object A) : K[X] ⟶ N[X] := chain_complex.of_hom _ _ _ _ _ _ (λ n, factor_thru _ _ (factors_normalized_Moore_complex_P_infty n)) (λ n, begin rw [← cancel_mono (normalized_Moore_complex.obj_X X n).arrow, assoc, assoc, factor_thru_arrow, ← inclusion_of_Moore_complex_map_f, ← normalized_Moore_complex_obj_d, ← (inclusion_of_Moore_complex_map X).comm' (n+1) n rfl, inclusion_of_Moore_complex_map_f, factor_thru_arrow_assoc, ← alternating_face_map_complex_obj_d], exact P_infty.comm' (n+1) n rfl, end) @[simp, reassoc] lemma P_infty_to_normalized_Moore_complex_comp_inclusion_of_Moore_complex_map (X : simplicial_object A) : P_infty_to_normalized_Moore_complex X ≫ inclusion_of_Moore_complex_map X = P_infty := by tidy @[simp, reassoc] lemma P_infty_to_normalized_Moore_complex_naturality {X Y : simplicial_object A} (f : X ⟶ Y) : alternating_face_map_complex.map f ≫ P_infty_to_normalized_Moore_complex Y = P_infty_to_normalized_Moore_complex X ≫ normalized_Moore_complex.map f := by tidy @[simp, reassoc] lemma P_infty_comp_P_infty_to_normalized_Moore_complex (X : simplicial_object A) : P_infty ≫ P_infty_to_normalized_Moore_complex X = P_infty_to_normalized_Moore_complex X := by tidy @[simp, reassoc] lemma inclusion_of_Moore_complex_map_comp_P_infty (X : simplicial_object A) : inclusion_of_Moore_complex_map X ≫ P_infty = inclusion_of_Moore_complex_map X := begin ext n, cases n, { dsimp, simp only [comp_id], }, { exact (higher_faces_vanish.inclusion_of_Moore_complex_map n).comp_P_eq_self, }, end instance : mono (inclusion_of_Moore_complex_map X) := ⟨λ Y f₁ f₂ hf, by { ext n, exact homological_complex.congr_hom hf n, }⟩ /-- `inclusion_of_Moore_complex_map X` is a split mono. -/ def split_mono_inclusion_of_Moore_complex_map (X : simplicial_object A) : split_mono (inclusion_of_Moore_complex_map X) := { retraction := P_infty_to_normalized_Moore_complex X, id' := by simp only [← cancel_mono (inclusion_of_Moore_complex_map X), assoc, id_comp, P_infty_to_normalized_Moore_complex_comp_inclusion_of_Moore_complex_map, inclusion_of_Moore_complex_map_comp_P_infty], } variable (A) /-- When the category `A` is abelian, the functor `N₁ : simplicial_object A ⥤ karoubi (chain_complex A ℕ)` defined using `P_infty` identifies to the composition of the normalized Moore complex functor and the inclusion in the Karoubi envelope. -/ def N₁_iso_normalized_Moore_complex_comp_to_karoubi : N₁ ≅ (normalized_Moore_complex A ⋙ to_karoubi _) := { hom := { app := λ X, { f := P_infty_to_normalized_Moore_complex X, comm := by tidy, }, }, inv := { app := λ X, { f := inclusion_of_Moore_complex_map X, comm := by tidy, }, }, hom_inv_id' := begin ext X : 3, simp only [P_infty_to_normalized_Moore_complex_comp_inclusion_of_Moore_complex_map, nat_trans.comp_app, karoubi.comp, N₁_obj_p, nat_trans.id_app, karoubi.id_eq], end, inv_hom_id' := begin ext X : 3, simp only [← cancel_mono (inclusion_of_Moore_complex_map X), nat_trans.comp_app, karoubi.comp, assoc, nat_trans.id_app, karoubi.id_eq, P_infty_to_normalized_Moore_complex_comp_inclusion_of_Moore_complex_map, inclusion_of_Moore_complex_map_comp_P_infty], dsimp only [functor.comp_obj, to_karoubi], rw id_comp, end } end dold_kan end algebraic_topology
d086290e11116991b24e3ced2cb43ce4ebc80079
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/vector2.lean
6618114fa0a813a86cb02c04b31255a006e01d7b
[ "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
376
lean
namespace Ex open nat inductive vector (A : Type) : nat → Type | vnil : vector nat.zero | vcons : Π {n : nat}, A → vector n → vector (succ n) namespace vector theorem vcons.inj₁ {A : Type} {n : nat} (a₁ a₂ : A) (v₁ v₂ : vector A n) : vcons a₁ v₁ = vcons a₂ v₂ → a₁ = a₂ := assume h, vector.no_confusion h (λ n h t, h) end vector end Ex
2b189a51fe5c69928619228fb789bdccb5f56fb3
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/even_odd2.lean
de89ba850e1c21c6850495d2977c5b6e48412b01
[ "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
489
lean
mutual def even, odd with even : nat → bool | 0 := tt | (a+1) := odd a with odd : nat → bool | 0 := ff | (a+1) := even a using_well_founded {rel_tac := λ f eqns, tactic.trace f >> tactic.trace eqns >> tactic.apply_instance} example (a : nat) : even (a + 1) = odd a := by simp [even] example (a : nat) : odd (a + 1) = even a := by simp [odd] lemma even_eq_not_odd : ∀ a, even a = bnot (odd a) := begin intro a, induction a, simp [even, odd], simp [*, even, odd] end
a95bf23a6a6d4b944b01d6e50f594da80409a74d
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/tests/lean/char_lits.lean
074bdb35ffe965d880c9bd77ced84673ae2809c5
[ "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
193
lean
import system.io open io #check #"a" #eval #"a" #eval #"\n" #eval #"\\" #eval put_str (list.cons #"\\" "aaa") #eval put_str [#"\n"] #eval put_str [#"\n"] #eval put_str (list.cons #"\'" "aaa")
e0aebf642e5661940eb375d98fb455c2c4c7db0e
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/order/field.lean
1b3766df2847dd4ec7408236270a7acdd564b281
[ "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,761
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Mario Carneiro, Floris van Doorn -/ import algebra.field import algebra.group_power.order import algebra.order.ring import tactic.monotonicity.basic /-! # Linear ordered fields A linear ordered field is a field equipped with a linear order such that * addition respects the order: `a ≤ b → c + a ≤ c + b`; * multiplication of positives is positive: `0 < a → 0 < b → 0 < a * b`; * `0 < 1`. ## Main Definitions * `linear_ordered_field`: the class of linear ordered fields. -/ set_option old_structure_cmd true variable {α : Type*} /-- A linear ordered field is a field with a linear order respecting the operations. -/ @[protect_proj] class linear_ordered_field (α : Type*) extends linear_ordered_comm_ring α, field α section linear_ordered_field variables [linear_ordered_field α] {a b c d e : α} section /-- `equiv.mul_left₀` as an order_iso. -/ @[simps {simp_rhs := tt}] def order_iso.mul_left₀ (a : α) (ha : 0 < a) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_left ha, ..equiv.mul_left₀ a ha.ne' } /-- `equiv.mul_right₀` as an order_iso. -/ @[simps {simp_rhs := tt}] def order_iso.mul_right₀ (a : α) (ha : 0 < a) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_right ha, ..equiv.mul_right₀ a ha.ne' } end /-! ### Lemmas about pos, nonneg, nonpos, neg -/ @[simp] lemma inv_pos : 0 < a⁻¹ ↔ 0 < a := suffices ∀ a : α, 0 < a → 0 < a⁻¹, from ⟨λ h, inv_inv₀ a ▸ this _ h, this a⟩, assume a ha, flip lt_of_mul_lt_mul_left ha.le $ by simp [ne_of_gt ha, zero_lt_one] @[simp] lemma inv_nonneg : 0 ≤ a⁻¹ ↔ 0 ≤ a := by simp only [le_iff_eq_or_lt, inv_pos, zero_eq_inv] @[simp] lemma inv_lt_zero : a⁻¹ < 0 ↔ a < 0 := by simp only [← not_le, inv_nonneg] @[simp] lemma inv_nonpos : a⁻¹ ≤ 0 ↔ a ≤ 0 := by simp only [← not_lt, inv_pos] lemma one_div_pos : 0 < 1 / a ↔ 0 < a := inv_eq_one_div a ▸ inv_pos lemma one_div_neg : 1 / a < 0 ↔ a < 0 := inv_eq_one_div a ▸ inv_lt_zero lemma one_div_nonneg : 0 ≤ 1 / a ↔ 0 ≤ a := inv_eq_one_div a ▸ inv_nonneg lemma one_div_nonpos : 1 / a ≤ 0 ↔ a ≤ 0 := inv_eq_one_div a ▸ inv_nonpos lemma div_pos_iff : 0 < a / b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 := by simp [division_def, mul_pos_iff] lemma div_neg_iff : a / b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b := by simp [division_def, mul_neg_iff] lemma div_nonneg_iff : 0 ≤ a / b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0 := by simp [division_def, mul_nonneg_iff] lemma div_nonpos_iff : a / b ≤ 0 ↔ 0 ≤ a ∧ b ≤ 0 ∨ a ≤ 0 ∧ 0 ≤ b := by simp [division_def, mul_nonpos_iff] lemma div_pos (ha : 0 < a) (hb : 0 < b) : 0 < a / b := div_pos_iff.2 $ or.inl ⟨ha, hb⟩ lemma div_pos_of_neg_of_neg (ha : a < 0) (hb : b < 0) : 0 < a / b := div_pos_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a / b < 0 := div_neg_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a / b < 0 := div_neg_iff.2 $ or.inl ⟨ha, hb⟩ lemma div_nonneg (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a / b := div_nonneg_iff.2 $ or.inl ⟨ha, hb⟩ lemma div_nonneg_of_nonpos (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a / b := div_nonneg_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_nonpos_of_nonpos_of_nonneg (ha : a ≤ 0) (hb : 0 ≤ b) : a / b ≤ 0 := div_nonpos_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_nonpos_of_nonneg_of_nonpos (ha : 0 ≤ a) (hb : b ≤ 0) : a / b ≤ 0 := div_nonpos_iff.2 $ or.inl ⟨ha, hb⟩ /-! ### Relating one division with another term. -/ lemma le_div_iff (hc : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨λ h, div_mul_cancel b (ne_of_lt hc).symm ▸ mul_le_mul_of_nonneg_right h hc.le, λ h, calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc).symm ... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right h (one_div_pos.2 hc).le ... = b / c : (div_eq_mul_one_div b c).symm⟩ 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 := ⟨λ h, calc a = a / b * b : by rw (div_mul_cancel _ (ne_of_lt hb).symm) ... ≤ c * b : mul_le_mul_of_nonneg_right h hb.le, λ h, calc a / b = a * (1 / b) : div_eq_mul_one_div a b ... ≤ (c * b) * (1 / b) : mul_le_mul_of_nonneg_right h (one_div_pos.2 hb).le ... = (c * b) / b : (div_eq_mul_one_div (c * b) b).symm ... = c : by refine (div_eq_iff (ne_of_gt hb)).mpr rfl⟩ 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 := lt_iff_lt_of_le_iff_le $ div_le_iff hc lemma lt_div_iff' (hc : 0 < c) : a < b / c ↔ c * a < b := by rw [mul_comm, lt_div_iff hc] 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 inv_mul_le_iff (h : 0 < b) : b⁻¹ * a ≤ c ↔ a ≤ b * c := begin rw [inv_eq_one_div, mul_comm, ← div_eq_mul_one_div], exact div_le_iff' h, end lemma inv_mul_le_iff' (h : 0 < b) : b⁻¹ * a ≤ c ↔ a ≤ c * b := by rw [inv_mul_le_iff h, mul_comm] lemma mul_inv_le_iff (h : 0 < b) : a * b⁻¹ ≤ c ↔ a ≤ b * c := by rw [mul_comm, inv_mul_le_iff h] lemma mul_inv_le_iff' (h : 0 < b) : a * b⁻¹ ≤ c ↔ a ≤ c * b := by rw [mul_comm, inv_mul_le_iff' h] lemma inv_mul_lt_iff (h : 0 < b) : b⁻¹ * a < c ↔ a < b * c := begin rw [inv_eq_one_div, mul_comm, ← div_eq_mul_one_div], exact div_lt_iff' h, end lemma inv_mul_lt_iff' (h : 0 < b) : b⁻¹ * a < c ↔ a < c * b := by rw [inv_mul_lt_iff h, mul_comm] lemma mul_inv_lt_iff (h : 0 < b) : a * b⁻¹ < c ↔ a < b * c := by rw [mul_comm, inv_mul_lt_iff h] lemma mul_inv_lt_iff' (h : 0 < b) : a * b⁻¹ < c ↔ a < c * b := by rw [mul_comm, inv_mul_lt_iff' h] lemma inv_pos_le_iff_one_le_mul (ha : 0 < a) : a⁻¹ ≤ b ↔ 1 ≤ b * a := by { rw [inv_eq_one_div], exact div_le_iff ha } lemma inv_pos_le_iff_one_le_mul' (ha : 0 < a) : a⁻¹ ≤ b ↔ 1 ≤ a * b := by { rw [inv_eq_one_div], exact div_le_iff' ha } lemma inv_pos_lt_iff_one_lt_mul (ha : 0 < a) : a⁻¹ < b ↔ 1 < b * a := by { rw [inv_eq_one_div], exact div_lt_iff ha } lemma inv_pos_lt_iff_one_lt_mul' (ha : 0 < a) : a⁻¹ < b ↔ 1 < a * b := by { rw [inv_eq_one_div], exact div_lt_iff' ha } lemma div_le_iff_of_neg (hc : c < 0) : b / c ≤ a ↔ a * c ≤ b := ⟨λ h, div_mul_cancel b (ne_of_lt hc) ▸ mul_le_mul_of_nonpos_right h hc.le, λ h, calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc) ... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right h (one_div_neg.2 hc).le ... = b / c : (div_eq_mul_one_div b c).symm⟩ lemma div_le_iff_of_neg' (hc : c < 0) : b / c ≤ a ↔ c * a ≤ b := by rw [mul_comm, div_le_iff_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 le_div_iff_of_neg' (hc : c < 0) : a ≤ b / c ↔ b ≤ c * a := by rw [mul_comm, le_div_iff_of_neg hc] lemma div_lt_iff_of_neg (hc : c < 0) : b / c < a ↔ a * c < b := lt_iff_lt_of_le_iff_le $ le_div_iff_of_neg hc lemma div_lt_iff_of_neg' (hc : c < 0) : b / c < a ↔ c * a < b := by rw [mul_comm, div_lt_iff_of_neg hc] lemma lt_div_iff_of_neg (hc : c < 0) : a < b / c ↔ b < a * c := lt_iff_lt_of_le_iff_le $ div_le_iff_of_neg hc lemma lt_div_iff_of_neg' (hc : c < 0) : a < b / c ↔ b < c * a := by rw [mul_comm, lt_div_iff_of_neg hc] /-- One direction of `div_le_iff` where `b` is allowed to be `0` (but `c` must be nonnegative) -/ lemma div_le_of_nonneg_of_le_mul (hb : 0 ≤ b) (hc : 0 ≤ c) (h : a ≤ c * b) : a / b ≤ c := by { rcases eq_or_lt_of_le hb with rfl|hb', simp [hc], rwa [div_le_iff hb'] } lemma div_le_one_of_le (h : a ≤ b) (hb : 0 ≤ b) : a / b ≤ 1 := div_le_of_nonneg_of_le_mul hb zero_le_one $ by rwa one_mul /-! ### Bi-implications of inequalities using inversions -/ lemma inv_le_inv_of_le (ha : 0 < a) (h : a ≤ b) : b⁻¹ ≤ a⁻¹ := by rwa [← one_div a, le_div_iff' ha, ← div_eq_mul_inv, div_le_iff (ha.trans_le h), one_mul] /-- See `inv_le_inv_of_le` for the implication from right-to-left with one fewer assumption. -/ lemma inv_le_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by rw [← one_div, div_le_iff ha, ← div_eq_inv_mul, le_div_iff hb, one_mul] /-- In a linear ordered field, for positive `a` and `b` we have `a⁻¹ ≤ b ↔ b⁻¹ ≤ a`. See also `inv_le_of_inv_le` for a one-sided implication with one fewer assumption. -/ 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 inv_le_of_inv_le (ha : 0 < a) (h : a⁻¹ ≤ b) : b⁻¹ ≤ a := (inv_le ha ((inv_pos.2 ha).trans_le h)).1 h 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 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) /-- In a linear ordered field, for positive `a` and `b` we have `a⁻¹ < b ↔ b⁻¹ < a`. See also `inv_lt_of_inv_lt` for a one-sided implication with one fewer assumption. -/ 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 inv_lt_of_inv_lt (ha : 0 < a) (h : a⁻¹ < b) : b⁻¹ < a := (inv_lt ha ((inv_pos.2 ha).trans h)).1 h 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 inv_le_inv_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by rw [← one_div, div_le_iff_of_neg ha, ← div_eq_inv_mul, div_le_iff_of_neg hb, one_mul] lemma inv_le_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by rw [← inv_le_inv_of_neg hb (inv_lt_zero.2 ha), inv_inv₀] lemma le_inv_of_neg (ha : a < 0) (hb : b < 0) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by rw [← inv_le_inv_of_neg (inv_lt_zero.2 hb) ha, inv_inv₀] lemma inv_lt_inv_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ < b⁻¹ ↔ b < a := lt_iff_lt_of_le_iff_le (inv_le_inv_of_neg hb ha) lemma inv_lt_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ < b ↔ b⁻¹ < a := lt_iff_lt_of_le_iff_le (le_inv_of_neg hb ha) lemma lt_inv_of_neg (ha : a < 0) (hb : b < 0) : a < b⁻¹ ↔ b < a⁻¹ := lt_iff_lt_of_le_iff_le (inv_le_of_neg hb ha) lemma inv_lt_one (ha : 1 < a) : a⁻¹ < 1 := by rwa [inv_lt ((@zero_lt_one α _ _).trans ha) zero_lt_one, inv_one] lemma one_lt_inv (h₁ : 0 < a) (h₂ : a < 1) : 1 < a⁻¹ := by rwa [lt_inv (@zero_lt_one α _ _) h₁, inv_one] lemma inv_le_one (ha : 1 ≤ a) : a⁻¹ ≤ 1 := by rwa [inv_le ((@zero_lt_one α _ _).trans_le ha) zero_lt_one, inv_one] lemma one_le_inv (h₁ : 0 < a) (h₂ : a ≤ 1) : 1 ≤ a⁻¹ := by rwa [le_inv (@zero_lt_one α _ _) h₁, inv_one] lemma inv_lt_one_iff_of_pos (h₀ : 0 < a) : a⁻¹ < 1 ↔ 1 < a := ⟨λ h₁, inv_inv₀ a ▸ one_lt_inv (inv_pos.2 h₀) h₁, inv_lt_one⟩ lemma inv_lt_one_iff : a⁻¹ < 1 ↔ a ≤ 0 ∨ 1 < a := begin cases le_or_lt a 0 with ha ha, { simp [ha, (inv_nonpos.2 ha).trans_lt zero_lt_one] }, { simp only [ha.not_le, false_or, inv_lt_one_iff_of_pos ha] } end lemma one_lt_inv_iff : 1 < a⁻¹ ↔ 0 < a ∧ a < 1 := ⟨λ h, ⟨inv_pos.1 (zero_lt_one.trans h), inv_inv₀ a ▸ inv_lt_one h⟩, and_imp.2 one_lt_inv⟩ lemma inv_le_one_iff : a⁻¹ ≤ 1 ↔ a ≤ 0 ∨ 1 ≤ a := begin rcases em (a = 1) with (rfl|ha), { simp [le_rfl] }, { simp only [ne.le_iff_lt (ne.symm ha), ne.le_iff_lt (mt inv_eq_one₀.1 ha), inv_lt_one_iff] } end lemma one_le_inv_iff : 1 ≤ a⁻¹ ↔ 0 < a ∧ a ≤ 1 := ⟨λ h, ⟨inv_pos.1 (zero_lt_one.trans_le h), inv_inv₀ a ▸ inv_le_one h⟩, and_imp.2 one_le_inv⟩ /-! ### Relating two divisions. -/ @[mono] lemma div_le_div_of_le (hc : 0 ≤ c) (h : a ≤ b) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonneg_right h (one_div_nonneg.2 hc) end -- Not a `mono` lemma b/c `div_le_div` is strictly more general lemma div_le_div_of_le_left (ha : 0 ≤ a) (hc : 0 < c) (h : c ≤ b) : a / b ≤ a / c := begin rw [div_eq_mul_inv, div_eq_mul_inv], exact mul_le_mul_of_nonneg_left ((inv_le_inv (hc.trans_le h) hc).mpr h) ha end lemma div_le_div_of_le_of_nonneg (hab : a ≤ b) (hc : 0 ≤ c) : a / c ≤ b / c := div_le_div_of_le hc hab lemma div_le_div_of_nonpos_of_le (hc : c ≤ 0) (h : b ≤ a) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonpos_right h (one_div_nonpos.2 hc) end lemma div_lt_div_of_lt (hc : 0 < c) (h : a < b) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_pos_right h (one_div_pos.2 hc) end lemma div_lt_div_of_neg_of_lt (hc : c < 0) (h : b < a) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_neg_right h (one_div_neg.2 hc) end lemma div_le_div_right (hc : 0 < c) : a / c ≤ b / c ↔ a ≤ b := ⟨le_imp_le_of_lt_imp_lt $ div_lt_div_of_lt hc, div_le_div_of_le $ hc.le⟩ lemma div_le_div_right_of_neg (hc : c < 0) : a / c ≤ b / c ↔ b ≤ a := ⟨le_imp_le_of_lt_imp_lt $ div_lt_div_of_neg_of_lt hc, div_le_div_of_nonpos_of_le $ hc.le⟩ lemma div_lt_div_right (hc : 0 < c) : a / c < b / c ↔ a < b := lt_iff_lt_of_le_iff_le $ div_le_div_right hc lemma div_lt_div_right_of_neg (hc : c < 0) : a / c < b / c ↔ b < a := lt_iff_lt_of_le_iff_le $ div_le_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 := by simp only [div_eq_mul_inv, mul_lt_mul_left ha, 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] @[mono] lemma div_le_div (hc : 0 ≤ c) (hac : a ≤ c) (hd : 0 < d) (hbd : d ≤ b) : a / b ≤ c / d := by { rw div_le_div_iff (hd.trans_le hbd) hd, exact mul_le_mul hac hbd hd.le hc } lemma div_lt_div (hac : a < c) (hbd : d ≤ b) (c0 : 0 ≤ c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (d0.trans_le 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 (d0.trans hbd) d0).2 (mul_lt_mul' hac hbd d0.le c0) lemma div_lt_div_of_lt_left (hb : 0 < b) (h : b < a) (hc : 0 < c) : c / a < c / b := (div_lt_div_left hc (hb.trans h) hb).mpr h /-! ### Relating one division and involving `1` -/ lemma one_le_div (hb : 0 < b) : 1 ≤ a / b ↔ b ≤ a := by rw [le_div_iff hb, one_mul] lemma div_le_one (hb : 0 < b) : a / b ≤ 1 ↔ a ≤ b := by rw [div_le_iff hb, one_mul] lemma one_lt_div (hb : 0 < b) : 1 < a / b ↔ b < a := by rw [lt_div_iff hb, one_mul] lemma div_lt_one (hb : 0 < b) : a / b < 1 ↔ a < b := by rw [div_lt_iff hb, one_mul] lemma one_le_div_of_neg (hb : b < 0) : 1 ≤ a / b ↔ a ≤ b := by rw [le_div_iff_of_neg hb, one_mul] lemma div_le_one_of_neg (hb : b < 0) : a / b ≤ 1 ↔ b ≤ a := by rw [div_le_iff_of_neg hb, one_mul] lemma one_lt_div_of_neg (hb : b < 0) : 1 < a / b ↔ a < b := by rw [lt_div_iff_of_neg hb, one_mul] lemma div_lt_one_of_neg (hb : b < 0) : a / b < 1 ↔ b < a := by rw [div_lt_iff_of_neg hb, one_mul] lemma one_div_le (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ b ↔ 1 / b ≤ a := by simpa using inv_le ha hb lemma one_div_lt (ha : 0 < a) (hb : 0 < b) : 1 / a < b ↔ 1 / b < a := by simpa using inv_lt ha hb lemma le_one_div (ha : 0 < a) (hb : 0 < b) : a ≤ 1 / b ↔ b ≤ 1 / a := by simpa using le_inv ha hb lemma lt_one_div (ha : 0 < a) (hb : 0 < b) : a < 1 / b ↔ b < 1 / a := by simpa using lt_inv ha hb lemma one_div_le_of_neg (ha : a < 0) (hb : b < 0) : 1 / a ≤ b ↔ 1 / b ≤ a := by simpa using inv_le_of_neg ha hb lemma one_div_lt_of_neg (ha : a < 0) (hb : b < 0) : 1 / a < b ↔ 1 / b < a := by simpa using inv_lt_of_neg ha hb lemma le_one_div_of_neg (ha : a < 0) (hb : b < 0) : a ≤ 1 / b ↔ b ≤ 1 / a := by simpa using le_inv_of_neg ha hb lemma lt_one_div_of_neg (ha : a < 0) (hb : b < 0) : a < 1 / b ↔ b < 1 / a := by simpa using lt_inv_of_neg ha hb lemma one_lt_div_iff : 1 < a / b ↔ 0 < b ∧ b < a ∨ b < 0 ∧ a < b := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, one_lt_div_of_neg] }, { simp [lt_irrefl, zero_le_one] }, { simp [hb, hb.not_lt, one_lt_div] } end lemma one_le_div_iff : 1 ≤ a / b ↔ 0 < b ∧ b ≤ a ∨ b < 0 ∧ a ≤ b := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, one_le_div_of_neg] }, { simp [lt_irrefl, zero_lt_one.not_le, zero_lt_one] }, { simp [hb, hb.not_lt, one_le_div] } end lemma div_lt_one_iff : a / b < 1 ↔ 0 < b ∧ a < b ∨ b = 0 ∨ b < 0 ∧ b < a := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, hb.ne, div_lt_one_of_neg] }, { simp [zero_lt_one], }, { simp [hb, hb.not_lt, div_lt_one, hb.ne.symm] } end lemma div_le_one_iff : a / b ≤ 1 ↔ 0 < b ∧ a ≤ b ∨ b = 0 ∨ b < 0 ∧ b ≤ a := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, hb.ne, div_le_one_of_neg] }, { simp [zero_le_one], }, { simp [hb, hb.not_lt, div_le_one, hb.ne.symm] } end /-! ### Relating two divisions, involving `1` -/ lemma one_div_le_one_div_of_le (ha : 0 < a) (h : a ≤ b) : 1 / b ≤ 1 / a := by simpa using inv_le_inv_of_le ha h lemma one_div_lt_one_div_of_lt (ha : 0 < a) (h : a < b) : 1 / b < 1 / a := by rwa [lt_div_iff' ha, ← div_eq_mul_one_div, div_lt_one (ha.trans h)] lemma one_div_le_one_div_of_neg_of_le (hb : b < 0) (h : a ≤ b) : 1 / b ≤ 1 / a := by rwa [div_le_iff_of_neg' hb, ← div_eq_mul_one_div, div_le_one_of_neg (h.trans_lt hb)] lemma one_div_lt_one_div_of_neg_of_lt (hb : b < 0) (h : a < b) : 1 / b < 1 / a := by rwa [div_lt_iff_of_neg' hb, ← div_eq_mul_one_div, div_lt_one_of_neg (h.trans hb)] lemma le_of_one_div_le_one_div (ha : 0 < a) (h : 1 / a ≤ 1 / b) : b ≤ a := le_imp_le_of_lt_imp_lt (one_div_lt_one_div_of_lt ha) h lemma lt_of_one_div_lt_one_div (ha : 0 < a) (h : 1 / a < 1 / b) : b < a := lt_imp_lt_of_le_imp_le (one_div_le_one_div_of_le ha) h lemma le_of_neg_of_one_div_le_one_div (hb : b < 0) (h : 1 / a ≤ 1 / b) : b ≤ a := le_imp_le_of_lt_imp_lt (one_div_lt_one_div_of_neg_of_lt hb) h lemma lt_of_neg_of_one_div_lt_one_div (hb : b < 0) (h : 1 / a < 1 / b) : b < a := lt_imp_lt_of_le_imp_le (one_div_le_one_div_of_neg_of_le hb) h /-- For the single implications with fewer assumptions, see `one_div_le_one_div_of_le` and `le_of_one_div_le_one_div` -/ lemma one_div_le_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ 1 / b ↔ b ≤ a := div_le_div_left zero_lt_one ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_lt_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a < 1 / b ↔ b < a := div_lt_div_left zero_lt_one ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_neg_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_le_one_div_of_neg (ha : a < 0) (hb : b < 0) : 1 / a ≤ 1 / b ↔ b ≤ a := by simpa [one_div] using inv_le_inv_of_neg ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_lt_one_div_of_neg (ha : a < 0) (hb : b < 0) : 1 / a < 1 / b ↔ b < a := lt_iff_lt_of_le_iff_le (one_div_le_one_div_of_neg hb ha) lemma one_lt_one_div (h1 : 0 < a) (h2 : a < 1) : 1 < 1 / a := by rwa [lt_one_div (@zero_lt_one α _ _) h1, one_div_one] lemma one_le_one_div (h1 : 0 < a) (h2 : a ≤ 1) : 1 ≤ 1 / a := by rwa [le_one_div (@zero_lt_one α _ _) h1, one_div_one] lemma one_div_lt_neg_one (h1 : a < 0) (h2 : -1 < a) : 1 / a < -1 := suffices 1 / a < 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_lt_one_div_of_neg_of_lt h1 h2 lemma one_div_le_neg_one (h1 : a < 0) (h2 : -1 ≤ a) : 1 / a ≤ -1 := suffices 1 / a ≤ 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_le_one_div_of_neg_of_le h1 h2 /-! ### Results about halving. The equalities also hold in fields of characteristic `0`. -/ lemma add_halves (a : α) : a / 2 + a / 2 = a := by rw [div_add_div_same, ← two_mul, mul_div_cancel_left a two_ne_zero] lemma sub_self_div_two (a : α) : a - a / 2 = a / 2 := suffices a / 2 + a / 2 - a / 2 = a / 2, by rwa add_halves at this, by rw [add_sub_cancel] lemma div_two_sub_self (a : α) : a / 2 - a = - (a / 2) := suffices a / 2 - (a / 2 + a / 2) = - (a / 2), by rwa add_halves at this, by rw [sub_add_eq_sub_sub, sub_self, zero_sub] lemma add_self_div_two (a : α) : (a + a) / 2 = a := by rw [← mul_two, mul_div_cancel a two_ne_zero] lemma half_pos (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma one_half_pos : (0:α) < 1 / 2 := half_pos zero_lt_one lemma div_two_lt_of_pos (h : 0 < a) : a / 2 < a := by { rw [div_lt_iff (@zero_lt_two α _ _)], exact lt_mul_of_one_lt_right h one_lt_two } lemma half_lt_self : 0 < a → a / 2 < a := div_two_lt_of_pos lemma half_le_self (ha_nonneg : 0 ≤ a) : a / 2 ≤ a := begin by_cases h0 : a = 0, { simp [h0], }, { rw ← ne.def at h0, exact (half_lt_self (lt_of_le_of_ne ha_nonneg h0.symm)).le, }, end lemma one_half_lt_one : (1 / 2 : α) < 1 := half_lt_self zero_lt_one lemma add_sub_div_two_lt (h : a < b) : a + (b - a) / 2 < b := begin rwa [← div_sub_div_same, sub_eq_add_neg, add_comm (b/2), ← add_assoc, ← sub_eq_add_neg, ← lt_sub_iff_add_lt, sub_self_div_two, sub_self_div_two, div_lt_div_right (@zero_lt_two α _ _)] end lemma left_lt_add_div_two : a < (a + b) / 2 ↔ a < b := by simp [lt_div_iff, mul_two] lemma add_div_two_lt_right : (a + b) / 2 < b ↔ a < b := by simp [div_lt_iff, mul_two] /-- An inequality involving `2`. -/ lemma sub_one_div_inv_le_two (a2 : 2 ≤ a) : (1 - 1 / a)⁻¹ ≤ 2 := begin -- Take inverses on both sides to obtain `2⁻¹ ≤ 1 - 1 / a` refine trans (inv_le_inv_of_le (inv_pos.mpr zero_lt_two) _) (inv_inv₀ (2 : α)).le, -- move `1 / a` to the left and `1 - 1 / 2 = 1 / 2` to the right to obtain `1 / a ≤ ⅟ 2` refine trans ((le_sub_iff_add_le.mpr ((_ : _ + 2⁻¹ = _ ).le))) ((sub_le_sub_iff_left 1).mpr _), { -- show 2⁻¹ + 2⁻¹ = 1 exact trans (two_mul _).symm (mul_inv_cancel two_ne_zero) }, { -- take inverses on both sides and use the assumption `2 ≤ a`. exact (one_div a).le.trans (inv_le_inv_of_le zero_lt_two a2) } end /-! ### Miscellaneous lemmas -/ /-- Pullback a `linear_ordered_field` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_field {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_inv β] [has_div β] [nontrivial β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : linear_ordered_field β := { ..hf.linear_ordered_ring f zero one add mul neg sub, ..hf.field f zero one add mul neg sub inv div} lemma mul_sub_mul_div_mul_neg_iff (hc : c ≠ 0) (hd : d ≠ 0) : (a * d - b * c) / (c * d) < 0 ↔ a / c < b / d := by rw [mul_comm b c, ← div_sub_div _ _ hc hd, sub_lt_zero] alias mul_sub_mul_div_mul_neg_iff ↔ div_lt_div_of_mul_sub_mul_div_neg mul_sub_mul_div_mul_neg lemma mul_sub_mul_div_mul_nonpos_iff (hc : c ≠ 0) (hd : d ≠ 0) : (a * d - b * c) / (c * d) ≤ 0 ↔ a / c ≤ b / d := by rw [mul_comm b c, ← div_sub_div _ _ hc hd, sub_nonpos] alias mul_sub_mul_div_mul_nonpos_iff ↔ div_le_div_of_mul_sub_mul_div_nonpos mul_sub_mul_div_mul_nonpos lemma mul_le_mul_of_mul_div_le (h : a * (b / c) ≤ d) (hc : 0 < c) : b * a ≤ d * c := begin rw [← mul_div_assoc] at h, rwa [mul_comm b, ← div_le_iff hc], end lemma div_mul_le_div_mul_of_div_le_div (h : a / b ≤ c / d) (he : 0 ≤ e) : a / (b * e) ≤ c / (d * e) := begin rw [div_mul_eq_div_mul_one_div, div_mul_eq_div_mul_one_div], exact mul_le_mul_of_nonneg_right h (one_div_nonneg.2 he) end lemma exists_add_lt_and_pos_of_lt (h : b < a) : ∃ c : α, b + c < a ∧ 0 < c := ⟨(a - b) / 2, add_sub_div_two_lt h, div_pos (sub_pos_of_lt h) zero_lt_two⟩ lemma exists_pos_mul_lt {a : α} (h : 0 < a) (b : α) : ∃ c : α, 0 < c ∧ b * c < a := begin have : 0 < a / max (b + 1) 1, from div_pos h (lt_max_iff.2 (or.inr zero_lt_one)), refine ⟨a / max (b + 1) 1, this, _⟩, rw [← lt_div_iff this, div_div_cancel' h.ne'], exact lt_max_iff.2 (or.inl $ lt_add_one _) end lemma le_of_forall_sub_le (h : ∀ ε > 0, b - ε ≤ a) : b ≤ a := begin contrapose! h, simpa only [and_comm ((0 : α) < _), lt_sub_iff_add_lt, gt_iff_lt] using exists_add_lt_and_pos_of_lt h, end lemma monotone.div_const {β : Type*} [preorder β] {f : β → α} (hf : monotone f) {c : α} (hc : 0 ≤ c) : monotone (λ x, (f x) / c) := by simpa only [div_eq_mul_inv] using 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) := by simpa only [div_eq_mul_inv] using hf.mul_const (inv_pos.2 hc) @[priority 100] -- see Note [lower instance priority] instance linear_ordered_field.to_densely_ordered : densely_ordered α := { dense := λ 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 zero_lt_two (add_lt_add_left h _), calc (a₁ + a₂) / 2 < (a₂ + a₂) / 2 : div_lt_div_of_lt zero_lt_two (add_lt_add_right h _) ... = a₂ : add_self_div_two a₂⟩ } lemma mul_self_inj_of_nonneg (a0 : 0 ≤ a) (b0 : 0 ≤ b) : a * a = b * b ↔ a = b := mul_self_eq_mul_self_iff.trans $ or_iff_left_of_imp $ λ h, by { subst a, have : b = 0 := le_antisymm (neg_nonneg.1 a0) b0, rw [this, neg_zero] } lemma min_div_div_right {c : α} (hc : 0 ≤ c) (a b : α) : min (a / c) (b / c) = (min a b) / c := eq.symm $ monotone.map_min (λ x y, div_le_div_of_le hc) lemma max_div_div_right {c : α} (hc : 0 ≤ c) (a b : α) : max (a / c) (b / c) = (max a b) / c := eq.symm $ monotone.map_max (λ x y, div_le_div_of_le hc) lemma min_div_div_right_of_nonpos {c : α} (hc : c ≤ 0) (a b : α) : min (a / c) (b / c) = (max a b) / c := eq.symm $ @monotone.map_max α (order_dual α) _ _ _ _ _ (λ x y, div_le_div_of_nonpos_of_le hc) lemma max_div_div_right_of_nonpos {c : α} (hc : c ≤ 0) (a b : α) : max (a / c) (b / c) = (min a b) / c := eq.symm $ @monotone.map_min α (order_dual α) _ _ _ _ _ (λ x y, div_le_div_of_nonpos_of_le hc) lemma abs_div (a b : α) : |a / b| = |a| / |b| := (abs_hom : monoid_with_zero_hom α α).map_div a b lemma abs_one_div (a : α) : |1 / a| = 1 / |a| := by rw [abs_div, abs_one] lemma abs_inv (a : α) : |a⁻¹| = (|a|)⁻¹ := (abs_hom : monoid_with_zero_hom α α).map_inv a -- TODO: add lemmas with `a⁻¹`. lemma one_div_strict_anti_on : strict_anti_on (λ x : α, 1 / x) (set.Ioi 0) := λ x x1 y y1 xy, (one_div_lt_one_div (set.mem_Ioi.mp y1) (set.mem_Ioi.mp x1)).mpr xy lemma one_div_pow_le_one_div_pow_of_le (a1 : 1 ≤ a) {m n : ℕ} (mn : m ≤ n) : 1 / a ^ n ≤ 1 / a ^ m := by refine (one_div_le_one_div _ _).mpr (pow_le_pow a1 mn); exact pow_pos (zero_lt_one.trans_le a1) _ lemma one_div_pow_lt_one_div_pow_of_lt (a1 : 1 < a) {m n : ℕ} (mn : m < n) : 1 / a ^ n < 1 / a ^ m := by refine (one_div_lt_one_div _ _).mpr (pow_lt_pow a1 mn); exact pow_pos (trans zero_lt_one a1) _ lemma one_div_pow_mono (a1 : 1 ≤ a) : monotone (λ n : ℕ, order_dual.to_dual 1 / a ^ n) := λ m n, one_div_pow_le_one_div_pow_of_le a1 lemma one_div_pow_strict_mono (a1 : 1 < a) : strict_mono (λ n : ℕ, order_dual.to_dual 1 / a ^ n) := λ m n, one_div_pow_lt_one_div_pow_of_lt a1 end linear_ordered_field
992bbfe242830fc430e32e5c7ef7355dfbdd2ee3
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/lift_nested_rec.lean
3a5905064230f131bfd192bab40f571e01118cc1
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
243
lean
definition f : nat → (nat × nat) → nat | 0 m := m.1 | (n+1) m := match m with | (a, b) := (f n (b, a + 1)) + (f n (a, b)) end check @f._main.equations._eqn_1 check @f._main.equations._eqn_2 check @f._match_1.equations._eqn_1
33193ff2f8df258569007ea43c68b66463cbae2c
4a092885406df4e441e9bb9065d9405dacb94cd8
/src/for_mathlib/rings.lean
b9c870a4cc5b1eb64bc13365e592223517503468
[ "Apache-2.0" ]
permissive
semorrison/lean-perfectoid-spaces
78c1572cedbfae9c3e460d8aaf91de38616904d8
bb4311dff45791170bcb1b6a983e2591bee88a19
refs/heads/master
1,588,841,765,494
1,554,805,620,000
1,554,805,620,000
180,353,546
0
1
null
1,554,809,880,000
1,554,809,880,000
null
UTF-8
Lean
false
false
2,517
lean
import ring_theory.ideal_operations data.equiv.algebra import for_mathlib.subtype universes u u₁ u₂ v v₁ w section variables {R : Type*} {S : Type*} [monoid R] [monoid S] lemma mul_left_mul {G : Type*} [semigroup G] (x y : G) : (*) (x * y) = (*) x ∘ (*) y := funext $ λ _, mul_assoc _ _ _ -- It seems that semigroup homs don't exist in mathlib... lemma is_monoid_hom.map_mul_left (f : R → S) [is_monoid_hom f] (x : R) : f ∘ ((*) x) = ((*) (f x)) ∘ f := funext $ λ _, is_monoid_hom.map_mul f end namespace ideal open function variables {R : Type*} {S : Type*} [comm_ring R] [comm_ring S] lemma pow_le_pow (I : ideal R) {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) (lattice.inf_le_left) end -- instance map_is_monoid_hom {f : R → S} [is_ring_hom f] : -- is_monoid_hom (ideal.map f) := -- { map_one := ideal.map_top f, -- map_mul := ideal.map_mul f } lemma span_image {R : Type u} [comm_ring R] {S : Type v} [comm_ring S] (f : R → S) [is_ring_hom f] (X : set R) : span (f '' X) = map f (span X) := le_antisymm (span_mono $ set.image_subset _ $ subset_span) (map_le_iff_le_comap.2 $ span_le.2 $ λ x hx, subset_span $ set.mem_image_of_mem f hx) @[simp] lemma map_quotient_self {R : Type u} [comm_ring R] (I : ideal R) : ideal.map (ideal.quotient.mk I) I = ⊥ := lattice.eq_bot_iff.2 $ ideal.map_le_iff_le_comap.2 $ begin intros x hx, erw submodule.mem_bot I.quotient, exact ideal.quotient.eq_zero_iff_mem.2 hx, apply_instance end lemma eq_bot_or_top {K : Type u} [discrete_field K] (I : ideal K) : I = ⊥ ∨ I = ⊤ := begin rw classical.or_iff_not_imp_right, change _ ≠ _ → _, rw ideal.ne_top_iff_one, intro h1, apply le_antisymm, swap, exact lattice.bot_le, intros r hr, by_cases H : r = 0, simpa, simpa [H, h1] using submodule.smul_mem I r⁻¹ hr, end lemma eq_bot_of_prime {K : Type u} [discrete_field K] (I : ideal K) [h : I.is_prime] : I = ⊥ := classical.or_iff_not_imp_right.mp I.eq_bot_or_top h.1 -- This should just be the conjunction of -- comap f ⊥ = ker f -- ker f = ⊥ (for injective f) lemma comap_bot_of_inj {R : Type u} [comm_ring R] {S : Type v} [comm_ring S] (f : R → S) [is_ring_hom f] (h : injective f) : ideal.comap f ⊥ = ⊥ := lattice.eq_bot_iff.2 $ begin intros r hr, change r ∈ f ⁻¹' {0} at hr, simp at *, apply h, rw hr, symmetry, rw is_ring_hom.map_zero f, end end ideal
c0530e25b1c5a2ded547d0f0b20d1bc703a2d1ee
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/dependencies.lean
9befb337213aaf6fbc9ff27571dc1a905b6e6be6
[ "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
30,423
lean
/- Copyright (c) 2020 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ import meta.rb_map import tactic.core /-! # Tactics About Dependencies This module provides tactics to compute dependencies and reverse dependencies of hypotheses. An expression `e` depends on a hypothesis `h` if `e` would not be valid if `h` were removed from the context. For example, the expression `e := x > 0` depends on `x`. We say that `x` is a dependency of `e` and that `e` is a reverse dependency of `x`. It is sometimes useful to consider *inclusive* dependency: `e` inclusively depends on `h` iff `e` depends on `h` or `e = h` (so inclusive dependency is the reflexive closure of regular dependency). Note that the standard library does not use quite the same terminology: * `kdependencies`/`kdeps` from the standard library compute reverse dependencies, not dependencies. * `kdepends_on` and functions derived from it ignore local definitions and therefore compute a weaker dependency relation (see next section). ## Local Definitions Determining dependencies of hypotheses is usually straightforward: a hypothesis `r : R` depends on another hypothesis `d : D` if `d` occurs in `R`. The implementation is more involved, however, in the presence of local definitions. Consider this context: ```lean n m : ℕ k : ℕ := m o : ℕ := k h : o > 0 ``` `h` depends on `o`, `k` and `m`, but only the dependency on `o` is syntactically obvious. `kdepends_on` ignores this complication and claims that `h` does not depend on `k` or `m`. We do not follow this example but process local definitions properly. This means that if the context contains a local definition, we need to compute the syntactic dependencies of `h`, then their dependencies, and so on. ## Direct Dependencies If you want to ignore local definitions while computing dependencies, this module also provides tactics to find the *direct* dependencies of a hypothesis. These are the hypotheses that syntactically appear in the hypothesis's type (or value, if the hypothesis is a local definition). -/ open native open expr_set (local_set_to_name_set) open name_set (local_list_to_name_set) namespace tactic /-! ### Direct Dependencies -/ /-! #### Checking whether hypotheses directly depend on each other -/ /-- `type_has_local_in_name_set h ns` returns true iff the type of `h` contains a local constant whose unique name appears in `ns`. -/ meta def type_has_local_in_name_set (h : expr) (ns : name_set) : tactic bool := do h_type ← infer_type h, pure $ h_type.has_local_in ns /-- `type_has_local_in_set h hs` returns true iff the type of `h` contains any of the local constants `hs`. -/ meta def type_has_local_in_set (h : expr) (hs : expr_set) : tactic bool := type_has_local_in_name_set h $ local_set_to_name_set hs /-- `type_has_local_in h hs` returns true iff the type of `h` contains any of the local constants `hs`. -/ meta def type_has_local_in (h : expr) (hs : list expr) : tactic bool := type_has_local_in_name_set h $ local_list_to_name_set hs /-- `local_def_value_has_local_in_name_set h ns` returns true iff `h` is a local definition whose value contains a local constant whose unique name appears in `ns`. -/ meta def local_def_value_has_local_in_name_set (h : expr) (ns : name_set) : tactic bool := do (some h_val) ← try_core $ local_def_value h | pure ff, pure $ h_val.has_local_in ns /-- `local_def_value_has_local_in_set h hs` returns true iff `h` is a local definition whose value contains any of the local constants `hs`. -/ meta def local_def_value_has_local_in_set (h : expr) (hs : expr_set) : tactic bool := local_def_value_has_local_in_name_set h $ local_set_to_name_set hs /-- `local_def_value_has_local_in h hs` returns true iff `h` is a local definition whose value contains any of the local constants `hs`. -/ meta def local_def_value_has_local_in (h : expr) (hs : list expr) : tactic bool := local_def_value_has_local_in_name_set h $ local_list_to_name_set hs /-- `hyp_directly_depends_on_local_name_set h ns` is true iff the hypothesis `h` directly depends on a hypothesis whose unique name appears in `ns`. -/ meta def hyp_directly_depends_on_local_name_set (h : expr) (ns : name_set) : tactic bool := list.mbor [ type_has_local_in_name_set h ns, local_def_value_has_local_in_name_set h ns ] /-- `hyp_directly_depends_on_local_set h hs` is true iff the hypothesis `h` directly depends on any of the hypotheses `hs`. -/ meta def hyp_directly_depends_on_local_set (h : expr) (hs : expr_set) : tactic bool := hyp_directly_depends_on_local_name_set h $ local_set_to_name_set hs /-- `hyp_directly_depends_on_locals h hs` is true iff the hypothesis `h` directly depends on any of the hypotheses `hs`. -/ meta def hyp_directly_depends_on_locals (h : expr) (hs : list expr) : tactic bool := hyp_directly_depends_on_local_name_set h $ local_list_to_name_set hs /-- `hyp_directly_depends_on_local_name_set_inclusive h ns` is true iff the hypothesis `h` directly depends on a hypothesis whose unique name appears in `ns` or `h`'s name appears in `ns`. -/ meta def hyp_directly_depends_on_local_name_set_inclusive (h : expr) (ns : name_set) : tactic bool := list.mbor [ pure $ ns.contains h.local_uniq_name , hyp_directly_depends_on_local_name_set h ns ] /-- `hyp_directly_depends_on_local_set_inclusive h ns` is true iff the hypothesis `h` directly depends on any of the hypotheses `hs` or `h` appears in `hs`. -/ meta def hyp_directly_depends_on_local_set_inclusive (h : expr) (hs : expr_set) : tactic bool := hyp_directly_depends_on_local_name_set_inclusive h $ local_set_to_name_set hs /-- `hyp_directly_depends_on_locals_inclusive h ns` is true iff the hypothesis `h` directly depends on any of the hypotheses `hs` or `h` appears in `hs`. -/ meta def hyp_directly_depends_on_locals_inclusive (h : expr) (hs : list expr) : tactic bool := hyp_directly_depends_on_local_name_set_inclusive h $ local_list_to_name_set hs /-! #### Computing the direct dependencies of a hypothesis -/ /-- `direct_dependency_set_of_hyp h` is the set of hypotheses that the hypothesis `h` directly depends on. These are the hypotheses that appear in `h`'s type or value (if `h` is a local definition). -/ meta def direct_dependency_set_of_hyp (h : expr) : tactic expr_set := do t ← infer_type h, let deps := t.list_local_consts', (some val) ← try_core $ local_def_value h | pure deps, let deps := deps.union val.list_local_consts', pure deps /-- `direct_dependency_name_set_of_hyp h` is the set of unique names of hypotheses that the hypothesis `h` directly depends on. These are the hypotheses that appear in `h`'s type or value (if `h` is a local definition). -/ meta def direct_dependency_name_set_of_hyp (h : expr) : tactic name_set := local_set_to_name_set <$> direct_dependency_set_of_hyp h /-- `direct_dependencies_of_hyp h` is the list of hypotheses that the hypothesis `h` directly depends on. These are the hypotheses that appear in `h`'s type or value (if `h` is a local definition). The dependencies are returned in no particular order. -/ meta def direct_dependencies_of_hyp (h : expr) : tactic (list expr) := rb_set.to_list <$> direct_dependency_set_of_hyp h /-- `direct_dependency_set_of_hyp_inclusive h` is the set of hypotheses that the hypothesis `h` directly depends on, plus `h` itself. -/ meta def direct_dependency_set_of_hyp_inclusive (h : expr) : tactic expr_set := do deps ← direct_dependency_set_of_hyp h, pure $ deps.insert h /-- `direct_dependency_name_set_of_hyp_inclusive h` is the set of unique names of hypotheses that the hypothesis `h` directly depends on, plus `h` itself. -/ meta def direct_dependency_name_set_of_hyp_inclusive (h : expr) : tactic name_set := local_set_to_name_set <$> direct_dependency_set_of_hyp_inclusive h /-- `direct_dependencies_of_hyp_inclusive h` is the list of hypotheses that the hypothesis `h` directly depends on, plus `h` itself. The dependencies are returned in no particular order. -/ meta def direct_dependencies_of_hyp_inclusive (h : expr) : tactic (list expr) := rb_set.to_list <$> direct_dependency_set_of_hyp_inclusive h /-! ### Indirect/Transitive Dependencies -/ /-! #### Checking whether hypotheses depend on each other -/ /-- `hyp_depends_on_local_name_set' cache h ns` is true iff `h` depends on any of the hypotheses whose unique names appear in `ns`. `cache` must be a set of hypotheses known *not* to depend (even indirectly) on any of the `ns`. This is a performance optimisation, so you can give an empty cache. The tactic also returns an expanded cache with hypotheses which the tactic has encountered. You probably want to use `tactic.hyp_depends_on_local_name_set` or `tactic.hyps_depend_on_local_name_set` instead of this tactic. -/ meta def hyp_depends_on_local_name_set' : expr_set → expr → name_set → tactic (bool × expr_set) := λ cache h ns, do ff ← pure $ cache.contains h | pure (ff, cache), direct_deps ← direct_dependency_set_of_hyp h, let has_dep := direct_deps.fold ff (λ d b, b || ns.contains d.local_uniq_name), ff ← pure has_dep | pure (tt, cache), (has_dep, cache) ← direct_deps.mfold (ff, cache) $ λ d ⟨b, cache⟩, if b then pure (tt, cache) else hyp_depends_on_local_name_set' cache d ns, if has_dep then pure (tt, cache) else pure (ff, cache.insert h) /-- `hyp_depends_on_local_name_set h ns` is true iff the hypothesis `h` depends on any of the hypotheses whose unique names appear in `ns`. If you need to check dependencies of multiple hypotheses, use `tactic.hyps_depend_on_local_name_set`. -/ meta def hyp_depends_on_local_name_set (h : expr) (ns : name_set) : tactic bool := do ctx_has_local_def ← context_upto_hyp_has_local_def h, if ctx_has_local_def then prod.fst <$> hyp_depends_on_local_name_set' mk_expr_set h ns else hyp_directly_depends_on_local_name_set h ns /-- `hyp_depends_on_local_set h hs` is true iff the hypothesis `h` depends on any of the hypotheses `hs`. If you need to check dependencies of multiple hypotheses, use `tactic.hyps_depend_on_local_set`. -/ meta def hyp_depends_on_local_set (h : expr) (hs : expr_set) : tactic bool := hyp_depends_on_local_name_set h $ local_set_to_name_set hs /-- `hyp_depends_on_locals h hs` is true iff the hypothesis `h` depends on any of the hypotheses `hs`. If you need to check dependencies of multiple hypotheses, use `tactic.hyps_depend_on_locals`. -/ meta def hyp_depends_on_locals (h : expr) (hs : list expr) : tactic bool := hyp_depends_on_local_name_set h $ local_list_to_name_set hs /-- `hyps_depend_on_local_name_set hs ns` returns, for each `h ∈ hs`, whether `h` depends on a hypothesis whose unique name appears in `ns`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_local_name_set` for every `h ∈ hs`. -/ meta def hyps_depend_on_local_name_set (hs : list expr) (ns : name_set) : tactic (list bool) := do ctx_has_local ← context_has_local_def, if ctx_has_local then let go : expr → list bool × expr_set → tactic (list bool × expr_set) := λ h ⟨deps, cache⟩, do { (h_dep, cache) ← hyp_depends_on_local_name_set' cache h ns, pure (h_dep :: deps, cache) } in prod.fst <$> hs.mfoldr go ([], mk_expr_map) else hs.mmap $ λ h, hyp_directly_depends_on_local_name_set h ns /-- `hyps_depend_on_local_set hs is` returns, for each `h ∈ hs`, whether `h` depends on any of the hypotheses `is`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_local_set` for every `h ∈ hs`. -/ meta def hyps_depend_on_local_set (hs : list expr) (is : expr_set) : tactic (list bool) := hyps_depend_on_local_name_set hs $ local_set_to_name_set is /-- `hyps_depend_on_locals hs is` returns, for each `h ∈ hs`, whether `h` depends on any of the hypotheses `is`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_locals` for every `h ∈ hs`. -/ meta def hyps_depend_on_locals (hs is : list expr) : tactic (list bool) := hyps_depend_on_local_name_set hs $ local_list_to_name_set is /-- `hyp_depends_on_local_name_set_inclusive' cache h ns` is true iff the hypothesis `h` inclusively depends on a hypothesis whose unique name appears in `ns`. `cache` must be a set of hypotheses known *not* to depend (even indirectly) on any of the `ns`. This is a performance optimisation, so you can give an empty cache. The tactic also returns an expanded cache with hypotheses which the tactic has encountered. Note that the cache records exclusive, not inclusive dependencies. You probably want to use `tactic.hyp_depends_on_local_name_set_inclusive` or `tactic.hyps_depend_on_local_name_set_inclusive` instead of this tactic. -/ meta def hyp_depends_on_local_name_set_inclusive' (cache : expr_set) (h : expr) (ns : name_set) : tactic (bool × expr_set) := if ns.contains h.local_uniq_name then pure (tt, cache) else hyp_depends_on_local_name_set' cache h ns /-- `hyp_depends_on_local_name_set_inclusive h ns` is true iff the hypothesis `h` inclusively depends on any of the hypotheses whose unique names appear in `ns`. If you need to check the dependencies of multiple hypotheses, use `tactic.hyps_depend_on_local_name_set_inclusive`. -/ meta def hyp_depends_on_local_name_set_inclusive (h : expr) (ns : name_set) : tactic bool := list.mbor [ pure $ ns.contains h.local_uniq_name, hyp_depends_on_local_name_set h ns ] /-- `hyp_depends_on_local_set_inclusive h hs` is true iff the hypothesis `h` inclusively depends on any of the hypotheses `hs`. If you need to check dependencies of multiple hypotheses, use `tactic.hyps_depend_on_local_set_inclusive`. -/ meta def hyp_depends_on_local_set_inclusive (h : expr) (hs : expr_set) : tactic bool := hyp_depends_on_local_name_set_inclusive h $ local_set_to_name_set hs /-- `hyp_depends_on_locals_inclusive h hs` is true iff the hypothesis `h` inclusively depends on any of the hypotheses `hs`. If you need to check dependencies of multiple hypotheses, use `tactic.hyps_depend_on_locals_inclusive`. -/ meta def hyp_depends_on_locals_inclusive (h : expr) (hs : list expr) : tactic bool := hyp_depends_on_local_name_set_inclusive h $ local_list_to_name_set hs /-- `hyps_depend_on_local_name_set_inclusive hs ns` returns, for each `h ∈ hs`, whether `h` inclusively depends on a hypothesis whose unique name appears in `ns`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_local_name_set_inclusive` for every `h ∈ hs`. -/ meta def hyps_depend_on_local_name_set_inclusive (hs : list expr) (ns : name_set) : tactic (list bool) := do ctx_has_local ← context_has_local_def, if ctx_has_local then let go : expr → list bool × expr_set → tactic (list bool × expr_set) := λ h ⟨deps, cache⟩, do { (h_dep, cache) ← hyp_depends_on_local_name_set_inclusive' cache h ns, pure (h_dep :: deps, cache) } in prod.fst <$> hs.mfoldr go ([], mk_expr_map) else hs.mmap $ λ h, hyp_directly_depends_on_local_name_set_inclusive h ns /-- `hyps_depend_on_local_set_inclusive hs is` returns, for each `h ∈ hs`, whether `h` depends inclusively on any of the hypotheses `is`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_local_set_inclusive` for every `h ∈ hs`. -/ meta def hyps_depend_on_local_set_inclusive (hs : list expr) (is : expr_set) : tactic (list bool) := hyps_depend_on_local_name_set_inclusive hs $ local_set_to_name_set is /-- `hyps_depend_on_locals_inclusive hs is` returns, for each `h ∈ hs`, whether `h` depends inclusively on any of the hypotheses `is`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_locals_inclusive` for every `h ∈ hs`. -/ meta def hyps_depend_on_locals_inclusive (hs is : list expr) : tactic (list bool) := hyps_depend_on_local_name_set_inclusive hs $ local_list_to_name_set is /-! #### Computing the dependencies of a hypothesis -/ /-- `dependency_set_of_hyp' cache h` is the set of dependencies of the hypothesis `h`. `cache` is a map from hypotheses to all their dependencies (including indirect dependencies). This is a performance optimisation, so you can give an empty cache. The tactic also returns an expanded cache with hypotheses which the tactic has encountered. You probably want to use `tactic.dependency_set_of_hyp` or `tactic.dependency_sets_of_hyps` instead of this tactic. -/ meta def dependency_set_of_hyp' : expr_map expr_set → expr → tactic (expr_set × expr_map expr_set) := λ cache h, do match cache.find h with | some deps := pure (deps, cache) | none := do direct_deps ← direct_dependency_set_of_hyp h, (deps, cache) ← direct_deps.mfold (direct_deps, cache) $ λ h' ⟨deps, cache⟩, do { (deps', cache) ← dependency_set_of_hyp' cache h', pure (deps.union deps', cache) }, pure (deps, cache.insert h deps) end /-- `dependency_set_of_hyp h` is the set of dependencies of the hypothesis `h`. If you need the dependencies of multiple hypotheses, use `tactic.dependency_sets_of_hyps`. -/ meta def dependency_set_of_hyp (h : expr) : tactic expr_set := do ctx_has_local ← context_upto_hyp_has_local_def h, if ctx_has_local then prod.fst <$> dependency_set_of_hyp' mk_expr_map h else direct_dependency_set_of_hyp h /-- `dependency_name_set_of_hyp h` is the set of unique names of the dependencies of the hypothesis `h`. If you need the dependencies of multiple hypotheses, use `tactic.dependency_name_sets_of_hyps`. -/ meta def dependency_name_set_of_hyp (h : expr) : tactic name_set := local_set_to_name_set <$> dependency_set_of_hyp h /-- `dependencies_of_hyp h` is the list of dependencies of the hypothesis `h`. The dependencies are returned in no particular order. If you need the dependencies of multiple hypotheses, use `tactic.dependencies_of_hyps`. -/ meta def dependencies_of_hyp (h : expr) : tactic (list expr) := rb_set.to_list <$> dependency_set_of_hyp h /-- `dependency_sets_of_hyps hs` returns, for each `h ∈ hs`, the set of dependencies of `h`. This is the same as (but more performant than) using `tactic.dependency_set_of_hyp` on every `h ∈ hs`. -/ meta def dependency_sets_of_hyps (hs : list expr) : tactic (list expr_set) := do ctx_has_def ← context_has_local_def, if ctx_has_def then let go : expr → list expr_set × expr_map expr_set → tactic (list expr_set × expr_map expr_set) := do λ h ⟨deps, cache⟩, do { (h_deps, cache) ← dependency_set_of_hyp' cache h, pure (h_deps :: deps, cache) } in prod.fst <$> hs.mfoldr go ([], mk_expr_map) else hs.mmap direct_dependency_set_of_hyp /-- `dependency_name_sets_of_hyps hs` returns, for each `h ∈ hs`, the set of unique names of the dependencies of `h`. This is the same as (but more performant than) using `tactic.dependency_name_set_of_hyp` on every `h ∈ hs`. -/ meta def dependency_name_sets_of_hyps (hs : list expr) : tactic (list name_set) := list.map local_set_to_name_set <$> dependency_sets_of_hyps hs /-- `dependencies_of_hyps hs` returns, for each `h ∈ hs`, the dependencies of `h`. The dependencies appear in no particular order in the returned lists. This is the same as (but more performant than) using `tactic.dependencies_of_hyp` on every `h ∈ hs`. -/ meta def dependencies_of_hyps (hs : list expr) : tactic (list (list expr)) := list.map rb_set.to_list <$> dependency_sets_of_hyps hs /-- `dependency_set_of_hyp_inclusive' cache h` is the set of dependencies of the hypothesis `h`, plus `h` itself. `cache` is a map from hypotheses to all their dependencies (including indirect dependencies). This is a performance optimisation, so you can give an empty cache. The tactic also returns an expanded cache with hypotheses which the tactic has encountered. Note that the cache records exclusive, not inclusive dependencies. You probably want to use `tactic.dependency_set_of_hyp_inclusive` or `tactic.dependency_sets_of_hyps_inclusive` instead of this tactic. -/ meta def dependency_set_of_hyp_inclusive' (cache : expr_map expr_set) (h : expr) : tactic (expr_set × expr_map expr_set) := do (deps, cache) ← dependency_set_of_hyp' cache h, pure (deps.insert h, cache) /-- `dependency_set_of_hyp_inclusive h` is the set of dependencies of the hypothesis `h`, plus `h` itself. If you need the dependencies of multiple hypotheses, use `tactic.dependency_sets_of_hyps_inclusive`. -/ meta def dependency_set_of_hyp_inclusive (h : expr) : tactic expr_set := do deps ← dependency_set_of_hyp h, pure $ deps.insert h /-- `dependency_name_set_of_hyp_inclusive h` is the set of unique names of the dependencies of the hypothesis `h`, plus the unique name of `h` itself. If you need the dependencies of multiple hypotheses, use `tactic.dependency_name_sets_of_hyps_inclusive`. -/ meta def dependency_name_set_of_hyp_inclusive (h : expr) : tactic name_set := local_set_to_name_set <$> dependency_set_of_hyp_inclusive h /-- `dependencies_of_hyp_inclusive h` is the list of dependencies of the hypothesis `h`, plus `h` itself. The dependencies are returned in no particular order. If you need the dependencies of multiple hypotheses, use `tactic.dependencies_of_hyps_inclusive`. -/ meta def dependencies_of_hyp_inclusive (h : expr) : tactic (list expr) := rb_set.to_list <$> dependency_set_of_hyp_inclusive h /-- `dependency_sets_of_hyps_inclusive hs` returns, for each `h ∈ hs`, the dependencies of `h`, plus `h` itself. This is the same as (but more performant than) using `tactic.dependency_set_of_hyp_inclusive` on every `h ∈ hs`. -/ meta def dependency_sets_of_hyps_inclusive (hs : list expr) : tactic (list expr_set) := do ctx_has_def ← context_has_local_def, if ctx_has_def then let go : expr → list expr_set × expr_map expr_set → tactic (list expr_set × expr_map expr_set) := λ h ⟨deps, cache⟩, do { (h_deps, cache) ← dependency_set_of_hyp_inclusive' cache h, pure (h_deps :: deps, cache) } in prod.fst <$> hs.mfoldr go ([], mk_expr_map) else hs.mmap direct_dependency_set_of_hyp_inclusive /-- `dependency_name_sets_of_hyps_inclusive hs` returns, for each `h ∈ hs`, the unique names of the dependencies of `h`, plus the unique name of `h` itself. This is the same as (but more performant than) using `tactic.dependency_name_set_of_hyp_inclusive` on every `h ∈ hs`. -/ meta def dependency_name_sets_of_hyps_inclusive (hs : list expr) : tactic (list name_set) := list.map local_set_to_name_set <$> dependency_sets_of_hyps_inclusive hs /-- `dependencies_of_hyps_inclusive hs` returns, for each `h ∈ hs`, the dependencies of `h`, plus `h` itself. The dependencies appear in no particular order in the returned lists. This is the same as (but more performant than) using `tactic.dependencies_of_hyp_inclusive` on every `h ∈ hs`. -/ meta def dependencies_of_hyps_inclusive (hs : list expr) : tactic (list (list expr)) := list.map rb_set.to_list <$> dependency_sets_of_hyps_inclusive hs /-! #### Computing the reverse dependencies of a hypothesis -/ private meta def reverse_dependencies_of_hyp_name_set_aux (hs : name_set) : list expr → list expr → name_set → tactic (list expr) | [] revdeps _ := pure revdeps.reverse | (H :: Hs) revdeps ns := do let H_uname := H.local_uniq_name, H_is_revdep ← list.mband [ pure $ ¬ hs.contains H_uname, hyp_directly_depends_on_local_name_set H ns ], if H_is_revdep then reverse_dependencies_of_hyp_name_set_aux Hs (H :: revdeps) (ns.insert H_uname) else reverse_dependencies_of_hyp_name_set_aux Hs revdeps ns /-- `reverse_dependencies_of_hyp_name_set hs` is the list of reverse dependencies of the hypotheses whose unique names appear in `hs`, excluding the `hs` themselves. The reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyp_name_set (hs : name_set) : tactic (list expr) := do ctx ← local_context, let ctx := ctx.after (λ h, hs.contains h.local_uniq_name), reverse_dependencies_of_hyp_name_set_aux hs ctx [] hs /-- `reverse_dependencies_of_hyp_set hs` is the list of reverse dependencies of the hypotheses `hs`, excluding the `hs` themselves. The reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyp_set (hs : expr_set) : tactic (list expr) := reverse_dependencies_of_hyp_name_set $ local_set_to_name_set hs /-- `reverse_dependencies_of_hyps hs` is the list of reverse dependencies of the hypotheses `hs`, excluding the `hs` themselves. The reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyps (hs : list expr) : tactic (list expr) := reverse_dependencies_of_hyp_name_set $ local_list_to_name_set hs private meta def reverse_dependencies_of_hyp_name_set_inclusive_aux : list expr → list expr → name_set → tactic (list expr) | [] revdeps _ := pure revdeps.reverse | (H :: Hs) revdeps ns := do let H_uname := H.local_uniq_name, H_is_revdep ← list.mbor [ pure $ ns.contains H.local_uniq_name, hyp_directly_depends_on_local_name_set H ns ], if H_is_revdep then reverse_dependencies_of_hyp_name_set_inclusive_aux Hs (H :: revdeps) (ns.insert H_uname) else reverse_dependencies_of_hyp_name_set_inclusive_aux Hs revdeps ns /-- `reverse_dependencies_of_hyp_name_set_inclusive hs` is the list of reverse dependencies of the hypotheses whose unique names appear in `hs`, including the `hs` themselves. The reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyp_name_set_inclusive (hs : name_set) : tactic (list expr) := do ctx ← local_context, let ctx := ctx.drop_while (λ h, ¬ hs.contains h.local_uniq_name), reverse_dependencies_of_hyp_name_set_inclusive_aux ctx [] hs /-- `reverse_dependencies_of_hyp_set_inclusive hs` is the list of reverse dependencies of the hypotheses `hs`, including the `hs` themselves. The inclusive reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyp_set_inclusive (hs : expr_set) : tactic (list expr) := reverse_dependencies_of_hyp_name_set_inclusive $ local_set_to_name_set hs /-- `reverse_dependencies_of_hyps_inclusive hs` is the list of reverse dependencies of the hypotheses `hs`, including the `hs` themselves. The reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyps_inclusive (hs : list expr) : tactic (list expr) := reverse_dependencies_of_hyp_name_set_inclusive $ local_list_to_name_set hs /-! ### Reverting a hypothesis and its reverse dependencies -/ /-- `revert_name_set hs` reverts the hypotheses whose unique names appear in `hs`, as well as any hypotheses that depend on them. Returns the number of reverted hypotheses and a list containing these hypotheses. The reverted hypotheses are returned in the order in which they used to appear in the context and are guaranteed to store the correct type (see `tactic.update_type`). -/ meta def revert_name_set (hs : name_set) : tactic (ℕ × list expr) := do to_revert ← reverse_dependencies_of_hyp_name_set_inclusive hs, to_revert_with_types ← to_revert.mmap update_type, num_reverted ← revert_lst to_revert, pure (num_reverted, to_revert_with_types) /-- `revert_set hs` reverts the hypotheses `hs`, as well as any hypotheses that depend on them. Returns the number of reverted hypotheses and a list containing these hypotheses. The reverted hypotheses are returned in the order in which they used to appear in the context and are guaranteed to store the correct type (see `tactic.update_type`). -/ meta def revert_set (hs : expr_set) : tactic (ℕ × list expr) := revert_name_set $ local_set_to_name_set hs /-- `revert_lst' hs` reverts the hypotheses `hs`, as well as any hypotheses that depend on them. Returns the number of reverted hypotheses and a list containing these hypotheses. The reverted hypotheses are returned in the order in which they used to appear in the context and are guaranteed to store the correct type (see `tactic.update_type`). This is a more informative version of `tactic.revert_lst`. -/ meta def revert_lst' (hs : list expr) : tactic (ℕ × list expr) := revert_name_set $ local_list_to_name_set hs /-- `revert_reverse_dependencies_of_hyp h` reverts all the hypotheses that depend on the hypothesis `h`, including the local definitions that have `h` in their value. This fixes a bug in `tactic.revert_kdependencies` that does not revert local definitions for which `h` only appears in the value. Returns the number of reverted hypotheses. -/ /- We cannot implement it as `revert e >> intro1` because that would change the local constant in the context. -/ meta def revert_reverse_dependencies_of_hyp (h : expr) : tactic ℕ := reverse_dependencies_of_hyp_name_set (mk_name_set.insert h.local_uniq_name) >>= revert_lst /-- `revert_reverse_dependencies_of_hyp_name_set hs` reverts all the hypotheses that depend on a hypothesis whose unique name appears in `hs`. The `hs` themselves are not reverted, unless they depend on each other. Returns the number of reverted hypotheses. -/ meta def revert_reverse_dependencies_of_hyp_name_set (hs : name_set) : tactic ℕ := reverse_dependencies_of_hyp_name_set hs >>= revert_lst /-- `revert_reverse_dependencies_of_hyp_set hs` reverts all the hypotheses that depend on a hypothesis in `hs`. The `hs` themselves are not reverted, unless they depend on each other. Returns the number of reverted hypotheses. -/ meta def revert_reverse_dependencies_of_hyp_set (hs : expr_set) : tactic ℕ := reverse_dependencies_of_hyp_set hs >>= revert_lst /-- `revert_reverse_dependencies_of_hyp hs` reverts all the hypotheses that depend on a hypothesis in `hs`. The `hs` themselves are not reverted, unless they depend on each other. Returns the number of reverted hypotheses. -/ meta def revert_reverse_dependencies_of_hyps (hs : list expr) : tactic ℕ := reverse_dependencies_of_hyps hs >>= revert_lst end tactic
dbb3681c66bb5fd2c67722d87d09846b8649e851
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/buffer/parser/basic.lean
e76841f87d0f791b089c5df3b6a57030564e19ea
[ "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
110,139
lean
/- Copyright (c) 2020 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.string.basic import data.buffer.basic import data.nat.digits /-! # Parsers `parser α` is the type that describes a computation that can ingest a `char_buffer` and output, if successful, a term of type `α`. This file expands on the definitions in the core library, proving that all the core library parsers are `mono`. There are also lemmas on the composability of parsers. ## Main definitions * `parse_result.pos` : The position of a `char_buffer` at which a `parser α` has finished. * `parser.mono` : The property that a parser only moves forward within a buffer, in both cases of success or failure. ## Implementation details Lemmas about how parsers are mono are in the `mono` namespace. That allows using projection notation for shorter term proofs that are parallel to the definitions of the parsers in structure. -/ open parser parse_result /-- For some `parse_result α`, give the position at which the result was provided, in either the `done` or the `fail` case. -/ @[simp] def parse_result.pos {α} : parse_result α → ℕ | (done n _) := n | (fail n _) := n namespace parser section defn_lemmas variables {α β : Type} (msgs : thunk (list string)) (msg : thunk string) variables (p q : parser α) (cb : char_buffer) (n n' : ℕ) {err : dlist string} variables {a : α} {b : β} /-- A `p : parser α` is defined to be `mono` if the result `p cb n` it gives, for some `cb : char_buffer` and `n : ℕ`, (whether `done` or `fail`), is always at a `parse_result.pos` that is at least `n`. The `mono` property is used mainly for proper `orelse` behavior. -/ class mono : Prop := (le' : ∀ (cb : char_buffer) (n : ℕ), n ≤ (p cb n).pos) lemma mono.le [p.mono] : n ≤ (p cb n).pos := mono.le' cb n /-- A `parser α` is defined to be `static` if it does not move on success. -/ class static : Prop := (of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n = n') /-- A `parser α` is defined to be `err_static` if it does not move on error. -/ class err_static : Prop := (of_fail : ∀ {cb : char_buffer} {n n' : ℕ} {err : dlist string}, p cb n = fail n' err → n = n') /-- A `parser α` is defined to be `step` if it always moves exactly one char forward on success. -/ class step : Prop := (of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n' = n + 1) /-- A `parser α` is defined to be `prog` if it always moves forward on success. -/ class prog : Prop := (of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n < n') /-- A `parser a` is defined to be `bounded` if it produces a `fail` `parse_result` when it is parsing outside the provided `char_buffer`. -/ class bounded : Prop := (ex' : ∀ {cb : char_buffer} {n : ℕ}, cb.size ≤ n → ∃ (n' : ℕ) (err : dlist string), p cb n = fail n' err) lemma bounded.exists (p : parser α) [p.bounded] {cb : char_buffer} {n : ℕ} (h : cb.size ≤ n) : ∃ (n' : ℕ) (err : dlist string), p cb n = fail n' err := bounded.ex' h /-- A `parser a` is defined to be `unfailing` if it always produces a `done` `parse_result`. -/ class unfailing : Prop := (ex' : ∀ (cb : char_buffer) (n : ℕ), ∃ (n' : ℕ) (a : α), p cb n = done n' a) /-- A `parser a` is defined to be `conditionally_unfailing` if it produces a `done` `parse_result` as long as it is parsing within the provided `char_buffer`. -/ class conditionally_unfailing : Prop := (ex' : ∀ {cb : char_buffer} {n : ℕ}, n < cb.size → ∃ (n' : ℕ) (a : α), p cb n = done n' a) lemma fail_iff : (∀ pos' result, p cb n ≠ done pos' result) ↔ ∃ (pos' : ℕ) (err : dlist string), p cb n = fail pos' err := by cases p cb n; simp lemma success_iff : (∀ pos' err, p cb n ≠ fail pos' err) ↔ ∃ (pos' : ℕ) (result : α), p cb n = done pos' result := by cases p cb n; simp variables {p q cb n n' msgs msg} lemma mono.of_done [p.mono] (h : p cb n = done n' a) : n ≤ n' := by simpa [h] using mono.le p cb n lemma mono.of_fail [p.mono] (h : p cb n = fail n' err) : n ≤ n' := by simpa [h] using mono.le p cb n lemma bounded.of_done [p.bounded] (h : p cb n = done n' a) : n < cb.size := begin contrapose! h, obtain ⟨np, err, hp⟩ := bounded.exists p h, simp [hp] end lemma static.iff : static p ↔ (∀ (cb : char_buffer) (n n' : ℕ) (a : α), p cb n = done n' a → n = n') := ⟨λ h _ _ _ _ hp, by { haveI := h, exact static.of_done hp}, λ h, ⟨h⟩⟩ lemma exists_done (p : parser α) [p.unfailing] (cb : char_buffer) (n : ℕ) : ∃ (n' : ℕ) (a : α), p cb n = done n' a := unfailing.ex' cb n lemma unfailing.of_fail [p.unfailing] (h : p cb n = fail n' err) : false := begin obtain ⟨np, a, hp⟩ := p.exists_done cb n, simpa [hp] using h end @[priority 100] -- see Note [lower instance priority] instance conditionally_unfailing_of_unfailing [p.unfailing] : conditionally_unfailing p := ⟨λ _ _ _, p.exists_done _ _⟩ lemma exists_done_in_bounds (p : parser α) [p.conditionally_unfailing] {cb : char_buffer} {n : ℕ} (h : n < cb.size) : ∃ (n' : ℕ) (a : α), p cb n = done n' a := conditionally_unfailing.ex' h lemma conditionally_unfailing.of_fail [p.conditionally_unfailing] (h : p cb n = fail n' err) (hn : n < cb.size) : false := begin obtain ⟨np, a, hp⟩ := p.exists_done_in_bounds hn, simpa [hp] using h end lemma decorate_errors_fail (h : p cb n = fail n' err) : @decorate_errors α msgs p cb n = fail n ((dlist.lazy_of_list (msgs ()))) := by simp [decorate_errors, h] lemma decorate_errors_success (h : p cb n = done n' a) : @decorate_errors α msgs p cb n = done n' a := by simp [decorate_errors, h] lemma decorate_error_fail (h : p cb n = fail n' err) : @decorate_error α msg p cb n = fail n ((dlist.lazy_of_list ([msg ()]))) := decorate_errors_fail h lemma decorate_error_success (h : p cb n = done n' a) : @decorate_error α msg p cb n = done n' a := decorate_errors_success h @[simp] lemma decorate_errors_eq_done : @decorate_errors α msgs p cb n = done n' a ↔ p cb n = done n' a := by cases h : p cb n; simp [decorate_errors, h] @[simp] lemma decorate_error_eq_done : @decorate_error α msg p cb n = done n' a ↔ p cb n = done n' a := decorate_errors_eq_done @[simp] lemma decorate_errors_eq_fail : @decorate_errors α msgs p cb n = fail n' err ↔ n = n' ∧ err = dlist.lazy_of_list (msgs ()) ∧ ∃ np err', p cb n = fail np err' := by cases h : p cb n; simp [decorate_errors, h, eq_comm] @[simp] lemma decorate_error_eq_fail : @decorate_error α msg p cb n = fail n' err ↔ n = n' ∧ err = dlist.lazy_of_list ([msg ()]) ∧ ∃ np err', p cb n = fail np err' := decorate_errors_eq_fail @[simp] lemma return_eq_pure : (@return parser _ _ a) = pure a := rfl lemma pure_eq_done : (@pure parser _ _ a) = λ _ n, done n a := rfl @[simp] lemma pure_ne_fail : (pure a : parser α) cb n ≠ fail n' err := by simp [pure_eq_done] section bind variable (f : α → parser β) @[simp] lemma bind_eq_bind : p.bind f = p >>= f := rfl variable {f} @[simp] lemma bind_eq_done : (p >>= f) cb n = done n' b ↔ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ f a cb np = done n' b := by cases hp : p cb n; simp [hp, ←bind_eq_bind, parser.bind, and_assoc] @[simp] lemma bind_eq_fail : (p >>= f) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ f a cb np = fail n' err) := by cases hp : p cb n; simp [hp, ←bind_eq_bind, parser.bind, and_assoc] @[simp] lemma and_then_eq_bind {α β : Type} {m : Type → Type} [monad m] (a : m α) (b : m β) : a >> b = a >>= (λ _, b) := rfl lemma and_then_fail : (p >> return ()) cb n = parse_result.fail n' err ↔ p cb n = fail n' err := by simp [pure_eq_done] lemma and_then_success : (p >> return ()) cb n = parse_result.done n' () ↔ ∃ a, p cb n = done n' a:= by simp [pure_eq_done] end bind section map variable {f : α → β} @[simp] lemma map_eq_done : (f <$> p) cb n = done n' b ↔ ∃ (a : α), p cb n = done n' a ∧ f a = b := by cases hp : p cb n; simp [←is_lawful_monad.bind_pure_comp_eq_map, hp, and_assoc, pure_eq_done] @[simp] lemma map_eq_fail : (f <$> p) cb n = fail n' err ↔ p cb n = fail n' err := by simp [←bind_pure_comp_eq_map, pure_eq_done] @[simp] lemma map_const_eq_done {b'} : (b <$ p) cb n = done n' b' ↔ ∃ (a : α), p cb n = done n' a ∧ b = b' := by simp [map_const_eq] @[simp] lemma map_const_eq_fail : (b <$ p) cb n = fail n' err ↔ p cb n = fail n' err := by simp only [map_const_eq, map_eq_fail] lemma map_const_rev_eq_done {b'} : (p $> b) cb n = done n' b' ↔ ∃ (a : α), p cb n = done n' a ∧ b = b' := map_const_eq_done lemma map_rev_const_eq_fail : (p $> b) cb n = fail n' err ↔ p cb n = fail n' err := map_const_eq_fail end map @[simp] lemma orelse_eq_orelse : p.orelse q = (p <|> q) := rfl @[simp] lemma orelse_eq_done : (p <|> q) cb n = done n' a ↔ (p cb n = done n' a ∨ (q cb n = done n' a ∧ ∃ err, p cb n = fail n err)) := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases hn : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, hn, hq, ←orelse_eq_orelse, parser.orelse] }, { rcases lt_trichotomy nq n with H|rfl|H; simp [hp, hn, hq, H, not_lt_of_lt H, lt_irrefl, ←orelse_eq_orelse, parser.orelse] <|> simp [hp, hn, hq, lt_irrefl, ←orelse_eq_orelse, parser.orelse] } }, { simp [hp, hn, ←orelse_eq_orelse, parser.orelse] } } end @[simp] lemma orelse_eq_fail_eq : (p <|> q) cb n = fail n err ↔ (p cb n = fail n err ∧ ∃ (nq errq), n < nq ∧ q cb n = fail nq errq) ∨ (∃ (errp errq), p cb n = fail n errp ∧ q cb n = fail n errq ∧ errp ++ errq = err) := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases hn : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, hn, hq, ←orelse_eq_orelse, parser.orelse] }, { rcases lt_trichotomy nq n with H|rfl|H; simp [hp, hq, hn, ←orelse_eq_orelse, parser.orelse, H, ne_of_gt H, ne_of_lt H, not_lt_of_lt H] <|> simp [hp, hq, hn, ←orelse_eq_orelse, parser.orelse, lt_irrefl] } }, { simp [hp, hn, ←orelse_eq_orelse, parser.orelse] } } end lemma orelse_eq_fail_not_mono_lt (hn : n' < n) : (p <|> q) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (q cb n = fail n' err ∧ (∃ (errp), p cb n = fail n errp)) := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases h : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, h, hn, hq, ne_of_gt hn, ←orelse_eq_orelse, parser.orelse] }, { rcases lt_trichotomy nq n with H|H|H, { simp [hp, hq, h, H, ne_of_gt hn, not_lt_of_lt H, ←orelse_eq_orelse, parser.orelse] }, { simp [hp, hq, h, H, ne_of_gt hn, lt_irrefl, ←orelse_eq_orelse, parser.orelse] }, { simp [hp, hq, h, H, ne_of_gt (hn.trans H), ←orelse_eq_orelse, parser.orelse] } } }, { simp [hp, h, ←orelse_eq_orelse, parser.orelse] } } end lemma orelse_eq_fail_of_mono_ne [q.mono] (hn : n ≠ n') : (p <|> q) cb n = fail n' err ↔ p cb n = fail n' err := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases h : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, h, hn, hq, hn, ←orelse_eq_orelse, parser.orelse] }, { have : n ≤ nq := mono.of_fail hq, rcases eq_or_lt_of_le this with rfl|H, { simp [hp, hq, h, hn, lt_irrefl, ←orelse_eq_orelse, parser.orelse] }, { simp [hp, hq, h, hn, H, ←orelse_eq_orelse, parser.orelse] } } }, { simp [hp, h, ←orelse_eq_orelse, parser.orelse] } }, end @[simp] lemma failure_eq_failure : @parser.failure α = failure := rfl @[simp] lemma failure_def : (failure : parser α) cb n = fail n dlist.empty := rfl lemma not_failure_eq_done : ¬ (failure : parser α) cb n = done n' a := by simp lemma failure_eq_fail : (failure : parser α) cb n = fail n' err ↔ n = n' ∧ err = dlist.empty := by simp [eq_comm] lemma seq_eq_done {f : parser (α → β)} {p : parser α} : (f <*> p) cb n = done n' b ↔ ∃ (nf : ℕ) (f' : α → β) (a : α), f cb n = done nf f' ∧ p cb nf = done n' a ∧ f' a = b := by simp [seq_eq_bind_map] lemma seq_eq_fail {f : parser (α → β)} {p : parser α} : (f <*> p) cb n = fail n' err ↔ (f cb n = fail n' err) ∨ (∃ (nf : ℕ) (f' : α → β), f cb n = done nf f' ∧ p cb nf = fail n' err) := by simp [seq_eq_bind_map] lemma seq_left_eq_done {p : parser α} {q : parser β} : (p <* q) cb n = done n' a ↔ ∃ (np : ℕ) (b : β), p cb n = done np a ∧ q cb np = done n' b := begin have : ∀ (p q : ℕ → α → Prop), (∃ (np : ℕ) (x : α), p np x ∧ q np x ∧ x = a) ↔ ∃ (np : ℕ), p np a ∧ q np a := λ _ _, ⟨λ ⟨np, x, hp, hq, rfl⟩, ⟨np, hp, hq⟩, λ ⟨np, hp, hq⟩, ⟨np, a, hp, hq, rfl⟩⟩, simp [seq_left_eq, seq_eq_done, map_eq_done, this] end lemma seq_left_eq_fail {p : parser α} {q : parser β} : (p <* q) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = fail n' err) := by simp [seq_left_eq, seq_eq_fail] lemma seq_right_eq_done {p : parser α} {q : parser β} : (p *> q) cb n = done n' b ↔ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = done n' b := by simp [seq_right_eq, seq_eq_done, map_eq_done, and.comm, and.assoc] lemma seq_right_eq_fail {p : parser α} {q : parser β} : (p *> q) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = fail n' err) := by simp [seq_right_eq, seq_eq_fail] lemma mmap_eq_done {f : α → parser β} {a : α} {l : list α} {b : β} {l' : list β} : (a :: l).mmap f cb n = done n' (b :: l') ↔ ∃ (np : ℕ), f a cb n = done np b ∧ l.mmap f cb np = done n' l' := by simp [mmap, and.comm, and.assoc, and.left_comm, pure_eq_done] lemma mmap'_eq_done {f : α → parser β} {a : α} {l : list α} : (a :: l).mmap' f cb n = done n' () ↔ ∃ (np : ℕ) (b : β), f a cb n = done np b ∧ l.mmap' f cb np = done n' () := by simp [mmap'] lemma guard_eq_done {p : Prop} [decidable p] {u : unit} : @guard parser _ p _ cb n = done n' u ↔ p ∧ n = n' := by { by_cases hp : p; simp [guard, hp, pure_eq_done] } lemma guard_eq_fail {p : Prop} [decidable p] : @guard parser _ p _ cb n = fail n' err ↔ (¬ p) ∧ n = n' ∧ err = dlist.empty := by { by_cases hp : p; simp [guard, hp, eq_comm, pure_eq_done] } namespace mono variables {sep : parser unit} instance pure : mono (pure a) := ⟨λ _ _, by simp [pure_eq_done]⟩ instance bind {f : α → parser β} [p.mono] [∀ a, (f a).mono] : (p >>= f).mono := begin constructor, intros cb n, cases hx : (p >>= f) cb n, { obtain ⟨n', a, h, h'⟩ := bind_eq_done.mp hx, refine le_trans (of_done h) _, simpa [h'] using of_done h' }, { obtain h | ⟨n', a, h, h'⟩ := bind_eq_fail.mp hx, { simpa [h] using of_fail h }, { refine le_trans (of_done h) _, simpa [h'] using of_fail h' } } end instance and_then {q : parser β} [p.mono] [q.mono] : (p >> q).mono := mono.bind instance map [p.mono] {f : α → β} : (f <$> p).mono := mono.bind instance seq {f : parser (α → β)} [f.mono] [p.mono] : (f <*> p).mono := mono.bind instance mmap : Π {l : list α} {f : α → parser β} [∀ a ∈ l, (f a).mono], (l.mmap f).mono | [] _ _ := mono.pure | (a :: l) f h := begin convert mono.bind, { exact h _ (list.mem_cons_self _ _) }, { intro, convert mono.map, convert mmap, exact (λ _ ha, h _ (list.mem_cons_of_mem _ ha)) } end instance mmap' : Π {l : list α} {f : α → parser β} [∀ a ∈ l, (f a).mono], (l.mmap' f).mono | [] _ _ := mono.pure | (a :: l) f h := begin convert mono.and_then, { exact h _ (list.mem_cons_self _ _) }, { convert mmap', exact (λ _ ha, h _ (list.mem_cons_of_mem _ ha)) } end instance failure : (failure : parser α).mono := ⟨by simp [le_refl]⟩ instance guard {p : Prop} [decidable p] : mono (guard p) := ⟨by { by_cases h : p; simp [h, pure_eq_done, le_refl] }⟩ instance orelse [p.mono] [q.mono] : (p <|> q).mono := begin constructor, intros cb n, cases hx : (p <|> q) cb n with posx resx posx errx, { obtain h | ⟨h, -, -⟩ := orelse_eq_done.mp hx; simpa [h] using of_done h }, { by_cases h : n = posx, { simp [hx, h] }, { simp only [orelse_eq_fail_of_mono_ne h] at hx, exact of_fail hx } } end instance decorate_errors [p.mono] : (@decorate_errors α msgs p).mono := begin constructor, intros cb n, cases h : p cb n, { simpa [decorate_errors, h] using of_done h }, { simp [decorate_errors, h] } end instance decorate_error [p.mono] : (@decorate_error α msg p).mono := mono.decorate_errors instance any_char : mono any_char := begin constructor, intros cb n, by_cases h : n < cb.size; simp [any_char, h], end instance sat {p : char → Prop} [decidable_pred p] : mono (sat p) := begin constructor, intros cb n, simp only [sat], split_ifs; simp end instance eps : mono eps := mono.pure instance ch {c : char} : mono (ch c) := mono.decorate_error instance char_buf {s : char_buffer} : mono (char_buf s) := mono.decorate_error instance one_of {cs : list char} : (one_of cs).mono := mono.decorate_errors instance one_of' {cs : list char} : (one_of' cs).mono := mono.and_then instance str {s : string} : (str s).mono := mono.decorate_error instance remaining : remaining.mono := ⟨λ _ _, le_refl _⟩ instance eof : eof.mono := mono.decorate_error instance foldr_core {f : α → β → β} {b : β} [p.mono] : ∀ {reps : ℕ}, (foldr_core f p b reps).mono | 0 := mono.failure | (reps + 1) := begin convert mono.orelse, { convert mono.bind, { apply_instance }, { exact λ _, @mono.bind _ _ _ _ foldr_core _ } }, { exact mono.pure } end instance foldr {f : α → β → β} [p.mono] : mono (foldr f p b) := ⟨λ _ _, by { convert mono.le (foldr_core f p b _) _ _, exact mono.foldr_core }⟩ instance foldl_core {f : α → β → α} {p : parser β} [p.mono] : ∀ {a : α} {reps : ℕ}, (foldl_core f a p reps).mono | _ 0 := mono.failure | _ (reps + 1) := begin convert mono.orelse, { convert mono.bind, { apply_instance }, { exact λ _, foldl_core } }, { exact mono.pure } end instance foldl {f : α → β → α} {p : parser β} [p.mono] : mono (foldl f a p) := ⟨λ _ _, by { convert mono.le (foldl_core f a p _) _ _, exact mono.foldl_core }⟩ instance many [p.mono] : p.many.mono := mono.foldr instance many_char {p : parser char} [p.mono] : p.many_char.mono := mono.map instance many' [p.mono] : p.many'.mono := mono.and_then instance many1 [p.mono] : p.many1.mono := mono.seq instance many_char1 {p : parser char} [p.mono] : p.many_char1.mono := mono.map instance sep_by1 [p.mono] [sep.mono] : mono (sep_by1 sep p) := mono.seq instance sep_by [p.mono] [hs : sep.mono] : mono (sep_by sep p) := mono.orelse lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.mono → (F p).mono) : ∀ (max_depth : ℕ), mono (fix_core F max_depth) | 0 := mono.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.mono := mono.decorate_error instance nat : nat.mono := mono.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.mono → (F p).mono) : mono (fix F) := ⟨λ _ _, by { convert mono.le (parser.fix_core F _) _ _, exact fix_core hF _ }⟩ end mono @[simp] lemma orelse_pure_eq_fail : (p <|> pure a) cb n = fail n' err ↔ p cb n = fail n' err ∧ n ≠ n' := begin by_cases hn : n = n', { simp [hn, pure_eq_done] }, { simp [orelse_eq_fail_of_mono_ne, hn] } end end defn_lemmas section done variables {α β : Type} {cb : char_buffer} {n n' : ℕ} {a a' : α} {b : β} {c : char} {u : unit} {err : dlist string} lemma any_char_eq_done : any_char cb n = done n' c ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := begin simp_rw [any_char], split_ifs with h; simp [h, eq_comm] end lemma any_char_eq_fail : any_char cb n = fail n' err ↔ n = n' ∧ err = dlist.empty ∧ cb.size ≤ n := begin simp_rw [any_char], split_ifs with h; simp [←not_lt, h, eq_comm] end lemma sat_eq_done {p : char → Prop} [decidable_pred p] : sat p cb n = done n' c ↔ ∃ (hn : n < cb.size), p c ∧ n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := begin by_cases hn : n < cb.size, { by_cases hp : p (cb.read ⟨n, hn⟩), { simp only [sat, hn, hp, dif_pos, if_true, exists_prop_of_true], split, { rintro ⟨rfl, rfl⟩, simp [hp] }, { rintro ⟨-, rfl, rfl⟩, simp } }, { simp only [sat, hn, hp, dif_pos, false_iff, not_and, exists_prop_of_true, if_false], rintro H - rfl, exact hp H } }, { simp [sat, hn] } end lemma sat_eq_fail {p : char → Prop} [decidable_pred p] : sat p cb n = fail n' err ↔ n = n' ∧ err = dlist.empty ∧ ∀ (h : n < cb.size), ¬ p (cb.read ⟨n, h⟩) := begin dsimp only [sat], split_ifs; simp [*, eq_comm] end lemma eps_eq_done : eps cb n = done n' u ↔ n = n' := by simp [eps, pure_eq_done] lemma ch_eq_done : ch c cb n = done n' u ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := by simp [ch, eps_eq_done, sat_eq_done, and.comm, @eq_comm _ n'] lemma char_buf_eq_done {cb' : char_buffer} : char_buf cb' cb n = done n' u ↔ n + cb'.size = n' ∧ cb'.to_list <+: (cb.to_list.drop n) := begin simp only [char_buf, decorate_error_eq_done, ne.def, ←buffer.length_to_list], induction cb'.to_list with hd tl hl generalizing cb n n', { simp [pure_eq_done, mmap'_eq_done, -buffer.length_to_list, list.nil_prefix] }, { simp only [ch_eq_done, and.comm, and.assoc, and.left_comm, hl, mmap', and_then_eq_bind, bind_eq_done, list.length, exists_and_distrib_left, exists_const], split, { rintro ⟨np, h, rfl, rfl, hn, rfl⟩, simp only [add_comm, add_left_comm, h, true_and, eq_self_iff_true, and_true], have : n < cb.to_list.length := by simpa using hn, rwa [←buffer.nth_le_to_list _ this, ←list.cons_nth_le_drop_succ this, list.prefix_cons_inj] }, { rintro ⟨h, rfl⟩, by_cases hn : n < cb.size, { have : n < cb.to_list.length := by simpa using hn, rw [←list.cons_nth_le_drop_succ this, list.cons_prefix_iff] at h, use [n + 1, h.right], simpa [buffer.nth_le_to_list, add_comm, add_left_comm, add_assoc, hn] using h.left.symm }, { have : cb.to_list.length ≤ n := by simpa using hn, rw list.drop_eq_nil_of_le this at h, simpa using h } } } end lemma one_of_eq_done {cs : list char} : one_of cs cb n = done n' c ↔ ∃ (hn : n < cb.size), c ∈ cs ∧ n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := by simp [one_of, sat_eq_done] lemma one_of'_eq_done {cs : list char} : one_of' cs cb n = done n' u ↔ ∃ (hn : n < cb.size), cb.read ⟨n, hn⟩ ∈ cs ∧ n' = n + 1 := begin simp only [one_of', one_of_eq_done, eps_eq_done, and.comm, and_then_eq_bind, bind_eq_done, exists_eq_left, exists_and_distrib_left], split, { rintro ⟨c, hc, rfl, hn, rfl⟩, exact ⟨rfl, hn, hc⟩ }, { rintro ⟨rfl, hn, hc⟩, exact ⟨cb.read ⟨n, hn⟩, hc, rfl, hn, rfl⟩ } end lemma str_eq_char_buf (s : string) : str s = char_buf s.to_list.to_buffer := begin ext cb n, rw [str, char_buf], congr, { simp [buffer.to_string, string.as_string_inv_to_list] }, { simp } end lemma str_eq_done {s : string} : str s cb n = done n' u ↔ n + s.length = n' ∧ s.to_list <+: (cb.to_list.drop n) := by simp [str_eq_char_buf, char_buf_eq_done] lemma remaining_eq_done {r : ℕ} : remaining cb n = done n' r ↔ n = n' ∧ cb.size - n = r := by simp [remaining] lemma remaining_ne_fail : remaining cb n ≠ fail n' err := by simp [remaining] lemma eof_eq_done {u : unit} : eof cb n = done n' u ↔ n = n' ∧ cb.size ≤ n := by simp [eof, guard_eq_done, remaining_eq_done, nat.sub_eq_zero_iff_le, and_comm, and_assoc] @[simp] lemma foldr_core_zero_eq_done {f : α → β → β} {p : parser α} {b' : β} : foldr_core f p b 0 cb n ≠ done n' b' := by simp [foldr_core] lemma foldr_core_eq_done {f : α → β → β} {p : parser α} {reps : ℕ} {b' : β} : foldr_core f p b (reps + 1) cb n = done n' b' ↔ (∃ (np : ℕ) (a : α) (xs : β), p cb n = done np a ∧ foldr_core f p b reps cb np = done n' xs ∧ f a xs = b') ∨ (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b reps cb np = fail n err)) := by simp [foldr_core, and.comm, and.assoc, pure_eq_done] @[simp] lemma foldr_core_zero_eq_fail {f : α → β → β} {p : parser α} {err : dlist string} : foldr_core f p b 0 cb n = fail n' err ↔ n = n' ∧ err = dlist.empty := by simp [foldr_core, eq_comm] lemma foldr_core_succ_eq_fail {f : α → β → β} {p : parser α} {reps : ℕ} {err : dlist string} : foldr_core f p b (reps + 1) cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b reps cb np = fail n' err) := by simp [foldr_core, and_comm] lemma foldr_eq_done {f : α → β → β} {p : parser α} {b' : β} : foldr f p b cb n = done n' b' ↔ ((∃ (np : ℕ) (a : α) (x : β), p cb n = done np a ∧ foldr_core f p b (cb.size - n) cb np = done n' x ∧ f a x = b') ∨ (n = n' ∧ b = b' ∧ (∃ (err), p cb n = parse_result.fail n err ∨ ∃ (np : ℕ) (x : α), p cb n = done np x ∧ foldr_core f p b (cb.size - n) cb np = fail n err))) := by simp [foldr, foldr_core_eq_done] lemma foldr_eq_fail_iff_mono_at_end {f : α → β → β} {p : parser α} {err : dlist string} [p.mono] (hc : cb.size ≤ n) : foldr f p b cb n = fail n' err ↔ n < n' ∧ (p cb n = fail n' err ∨ ∃ (a : α), p cb n = done n' a ∧ err = dlist.empty) := begin have : cb.size - n = 0 := nat.sub_eq_zero_of_le hc, simp only [foldr, foldr_core_succ_eq_fail, this, and.left_comm, foldr_core_zero_eq_fail, ne_iff_lt_iff_le, exists_and_distrib_right, exists_eq_left, and.congr_left_iff, exists_and_distrib_left], rintro (h | ⟨⟨a, h⟩, rfl⟩), { exact mono.of_fail h }, { exact mono.of_done h } end lemma foldr_eq_fail {f : α → β → β} {p : parser α} {err : dlist string} : foldr f p b cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b (cb.size - n) cb np = fail n' err) := by simp [foldr, foldr_core_succ_eq_fail] @[simp] lemma foldl_core_zero_eq_done {f : β → α → β} {p : parser α} {b' : β} : foldl_core f b p 0 cb n = done n' b' ↔ false := by simp [foldl_core] lemma foldl_core_eq_done {f : β → α → β} {p : parser α} {reps : ℕ} {b' : β} : foldl_core f b p (reps + 1) cb n = done n' b' ↔ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = done n' b') ∨ (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = fail n err)) := by simp [foldl_core, and.assoc, pure_eq_done] @[simp] lemma foldl_core_zero_eq_fail {f : β → α → β} {p : parser α} {err : dlist string} : foldl_core f b p 0 cb n = fail n' err ↔ n = n' ∧ err = dlist.empty := by simp [foldl_core, eq_comm] lemma foldl_core_succ_eq_fail {f : β → α → β} {p : parser α} {reps : ℕ} {err : dlist string} : foldl_core f b p (reps + 1) cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = fail n' err) := by simp [foldl_core, and_comm] lemma foldl_eq_done {f : β → α → β} {p : parser α} {b' : β} : foldl f b p cb n = done n' b' ↔ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p (cb.size - n) cb np = done n' b') ∨ (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p (cb.size - n) cb np = fail n err)) := by simp [foldl, foldl_core_eq_done] lemma foldl_eq_fail {f : β → α → β} {p : parser α} {err : dlist string} : foldl f b p cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p (cb.size - n) cb np = fail n' err) := by simp [foldl, foldl_core_succ_eq_fail] lemma foldl_eq_fail_iff_mono_at_end {f : β → α → β} {p : parser α} {err : dlist string} [p.mono] (hc : cb.size ≤ n) : foldl f b p cb n = fail n' err ↔ n < n' ∧ (p cb n = fail n' err ∨ ∃ (a : α), p cb n = done n' a ∧ err = dlist.empty) := begin have : cb.size - n = 0 := nat.sub_eq_zero_of_le hc, simp only [foldl, foldl_core_succ_eq_fail, this, and.left_comm, ne_iff_lt_iff_le, exists_eq_left, exists_and_distrib_right, and.congr_left_iff, exists_and_distrib_left, foldl_core_zero_eq_fail], rintro (h | ⟨⟨a, h⟩, rfl⟩), { exact mono.of_fail h }, { exact mono.of_done h } end lemma many_eq_done_nil {p : parser α} : many p cb n = done n' (@list.nil α) ↔ n = n' ∧ ∃ (err), p cb n = fail n err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core list.cons p [] (cb.size - n) cb np = fail n err := by simp [many, foldr_eq_done] lemma many_eq_done {p : parser α} {x : α} {xs : list α} : many p cb n = done n' (x :: xs) ↔ ∃ (np : ℕ), p cb n = done np x ∧ foldr_core list.cons p [] (cb.size - n) cb np = done n' xs := by simp [many, foldr_eq_done, and.comm, and.assoc, and.left_comm] lemma many_eq_fail {p : parser α} {err : dlist string} : many p cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core list.cons p [] (cb.size - n) cb np = fail n' err) := by simp [many, foldr_eq_fail] lemma many_char_eq_done_empty {p : parser char} : many_char p cb n = done n' string.empty ↔ n = n' ∧ ∃ (err), p cb n = fail n err ∨ ∃ (np : ℕ) (c : char), p cb n = done np c ∧ foldr_core list.cons p [] (cb.size - n) cb np = fail n err := by simp [many_char, many_eq_done_nil, map_eq_done, list.as_string_eq] lemma many_char_eq_done_not_empty {p : parser char} {s : string} (h : s ≠ "") : many_char p cb n = done n' s ↔ ∃ (np : ℕ), p cb n = done np s.head ∧ foldr_core list.cons p list.nil (buffer.size cb - n) cb np = done n' (s.popn 1).to_list := by simp [many_char, list.as_string_eq, string.to_list_nonempty h, many_eq_done] lemma many_char_eq_many_of_to_list {p : parser char} {s : string} : many_char p cb n = done n' s ↔ many p cb n = done n' s.to_list := by simp [many_char, list.as_string_eq] lemma many'_eq_done {p : parser α} : many' p cb n = done n' u ↔ many p cb n = done n' [] ∨ ∃ (np : ℕ) (a : α) (l : list α), many p cb n = done n' (a :: l) ∧ p cb n = done np a ∧ foldr_core list.cons p [] (buffer.size cb - n) cb np = done n' l := begin simp only [many', eps_eq_done, many, foldr, and_then_eq_bind, exists_and_distrib_right, bind_eq_done, exists_eq_right], split, { rintro ⟨_ | ⟨hd, tl⟩, hl⟩, { exact or.inl hl }, { have hl2 := hl, simp only [foldr_core_eq_done, or_false, exists_and_distrib_left, and_false, false_and, exists_eq_right_right] at hl, obtain ⟨np, hp, h⟩ := hl, refine or.inr ⟨np, _, _, hl2, hp, h⟩ } }, { rintro (h | ⟨np, a, l, hp, h⟩), { exact ⟨[], h⟩ }, { refine ⟨a :: l, hp⟩ } } end @[simp] lemma many1_ne_done_nil {p : parser α} : many1 p cb n ≠ done n' [] := by simp [many1, seq_eq_done] lemma many1_eq_done {p : parser α} {l : list α} : many1 p cb n = done n' (a :: l) ↔ ∃ (np : ℕ), p cb n = done np a ∧ many p cb np = done n' l := by simp [many1, seq_eq_done, map_eq_done] lemma many1_eq_fail {p : parser α} {err : dlist string} : many1 p cb n = fail n' err ↔ p cb n = fail n' err ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ many p cb np = fail n' err) := by simp [many1, seq_eq_fail] @[simp] lemma many_char1_ne_empty {p : parser char} : many_char1 p cb n ≠ done n' "" := by simp [many_char1, ←string.nil_as_string_eq_empty] lemma many_char1_eq_done {p : parser char} {s : string} (h : s ≠ "") : many_char1 p cb n = done n' s ↔ ∃ (np : ℕ), p cb n = done np s.head ∧ many_char p cb np = done n' (s.popn 1) := by simp [many_char1, list.as_string_eq, string.to_list_nonempty h, many1_eq_done, many_char_eq_many_of_to_list] @[simp] lemma sep_by1_ne_done_nil {sep : parser unit} {p : parser α} : sep_by1 sep p cb n ≠ done n' [] := by simp [sep_by1, seq_eq_done] lemma sep_by1_eq_done {sep : parser unit} {p : parser α} {l : list α} : sep_by1 sep p cb n = done n' (a :: l) ↔ ∃ (np : ℕ), p cb n = done np a ∧ (sep >> p).many cb np = done n' l := by simp [sep_by1, seq_eq_done] lemma sep_by_eq_done_nil {sep : parser unit} {p : parser α} : sep_by sep p cb n = done n' [] ↔ n = n' ∧ ∃ (err), sep_by1 sep p cb n = fail n err := by simp [sep_by, pure_eq_done] @[simp] lemma fix_core_ne_done_zero {F : parser α → parser α} : fix_core F 0 cb n ≠ done n' a := by simp [fix_core] lemma fix_core_eq_done {F : parser α → parser α} {max_depth : ℕ} : fix_core F (max_depth + 1) cb n = done n' a ↔ F (fix_core F max_depth) cb n = done n' a := by simp [fix_core] lemma digit_eq_done {k : ℕ} : digit cb n = done n' k ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ k ≤ 9 ∧ (cb.read ⟨n, hn⟩).to_nat - '0'.to_nat = k ∧ '0' ≤ cb.read ⟨n, hn⟩ ∧ cb.read ⟨n, hn⟩ ≤ '9' := begin have c9 : '9'.to_nat - '0'.to_nat = 9 := rfl, have l09 : '0'.to_nat ≤ '9'.to_nat := dec_trivial, have le_iff_le : ∀ {c c' : char}, c ≤ c' ↔ c.to_nat ≤ c'.to_nat := λ _ _, iff.rfl, split, { simp only [digit, sat_eq_done, pure_eq_done, decorate_error_eq_done, bind_eq_done, ←c9], rintro ⟨np, c, ⟨hn, ⟨ge0, le9⟩, rfl, rfl⟩, rfl, rfl⟩, simpa [hn, ge0, le9, true_and, and_true, eq_self_iff_true, exists_prop_of_true, nat.sub_le_sub_right_iff, l09] using (le_iff_le.mp le9) }, { simp only [digit, sat_eq_done, pure_eq_done, decorate_error_eq_done, bind_eq_done, ←c9, le_iff_le], rintro ⟨hn, rfl, -, rfl, ge0, le9⟩, use [n + 1, cb.read ⟨n, hn⟩], simp [hn, ge0, le9] } end lemma digit_eq_fail : digit cb n = fail n' err ↔ n = n' ∧ err = dlist.of_list ["<digit>"] ∧ ∀ (h : n < cb.size), ¬ ((λ c, '0' ≤ c ∧ c ≤ '9') (cb.read ⟨n, h⟩)) := by simp [digit, sat_eq_fail] end done namespace static variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma not_of_ne (h : p cb n = done n' a) (hne : n ≠ n') : ¬ static p := by { introI, exact hne (of_done h) } instance pure : static (pure a) := ⟨λ _ _ _ _, by { simp_rw pure_eq_done, rw [and.comm], simp }⟩ instance bind {f : α → parser β} [p.static] [∀ a, (f a).static] : (p >>= f).static := ⟨λ _ _ _ _, by { rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, exact trans (of_done hp) (of_done hf) }⟩ instance and_then {q : parser β} [p.static] [q.static] : (p >> q).static := static.bind instance map [p.static] {f : α → β} : (f <$> p).static := ⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩ instance seq {f : parser (α → β)} [f.static] [p.static] : (f <*> p).static := static.bind instance mmap : Π {l : list α} {f : α → parser β} [∀ a, (f a).static], (l.mmap f).static | [] _ _ := static.pure | (a :: l) _ h := begin convert static.bind, { exact h _ }, { intro, convert static.bind, { convert mmap, exact h }, { exact λ _, static.pure } } end instance mmap' : Π {l : list α} {f : α → parser β} [∀ a, (f a).static], (l.mmap' f).static | [] _ _ := static.pure | (a :: l) _ h := begin convert static.and_then, { exact h _ }, { convert mmap', exact h } end instance failure : @parser.static α failure := ⟨λ _ _ _ _, by simp⟩ instance guard {p : Prop} [decidable p] : static (guard p) := ⟨λ _ _ _ _, by simp [guard_eq_done]⟩ instance orelse [p.static] [q.static] : (p <|> q).static := ⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩ instance decorate_errors [p.static] : (@decorate_errors α msgs p).static := ⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩ instance decorate_error [p.static] : (@decorate_error α msg p).static := static.decorate_errors lemma any_char : ¬ static any_char := begin have : any_char "s".to_char_buffer 0 = done 1 's', { have : 0 < "s".to_char_buffer.size := dec_trivial, simpa [any_char_eq_done, this] }, exact not_of_ne this zero_ne_one end lemma sat_iff {p : char → Prop} [decidable_pred p] : static (sat p) ↔ ∀ c, ¬ p c := begin split, { introI, intros c hc, have : sat p [c].to_buffer 0 = done 1 c := by simp [sat_eq_done, hc], exact zero_ne_one (of_done this) }, { contrapose!, simp only [iff, sat_eq_done, and_imp, exists_prop, exists_and_distrib_right, exists_and_distrib_left, exists_imp_distrib, not_forall], rintros _ _ _ a h hne rfl hp -, exact ⟨a, hp⟩ } end instance sat : static (sat (λ _, false)) := by { apply sat_iff.mpr, simp } instance eps : static eps := static.pure lemma ch (c : char) : ¬ static (ch c) := begin have : ch c [c].to_buffer 0 = done 1 (), { have : 0 < [c].to_buffer.size := dec_trivial, simp [ch_eq_done, this] }, exact not_of_ne this zero_ne_one end lemma char_buf_iff {cb' : char_buffer} : static (char_buf cb') ↔ cb' = buffer.nil := begin rw ←buffer.size_eq_zero_iff, have : char_buf cb' cb' 0 = done cb'.size () := by simp [char_buf_eq_done], cases hc : cb'.size with n, { simp only [eq_self_iff_true, iff_true], exact ⟨λ _ _ _ _ h, by simpa [hc] using (char_buf_eq_done.mp h).left⟩ }, { rw hc at this, simpa [nat.succ_ne_zero] using not_of_ne this (nat.succ_ne_zero n).symm } end lemma one_of_iff {cs : list char} : static (one_of cs) ↔ cs = [] := begin cases cs with hd tl, { simp [one_of, static.decorate_errors] }, { have : one_of (hd :: tl) (hd :: tl).to_buffer 0 = done 1 hd, { simp [one_of_eq_done] }, simpa using not_of_ne this zero_ne_one } end instance one_of : static (one_of []) := by { apply one_of_iff.mpr, refl } lemma one_of'_iff {cs : list char} : static (one_of' cs) ↔ cs = [] := begin cases cs with hd tl, { simp [one_of', static.bind], }, { have : one_of' (hd :: tl) (hd :: tl).to_buffer 0 = done 1 (), { simp [one_of'_eq_done] }, simpa using not_of_ne this zero_ne_one } end instance one_of' : static (one_of []) := by { apply one_of_iff.mpr, refl } lemma str_iff {s : string} : static (str s) ↔ s = "" := by simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff] instance remaining : remaining.static := ⟨λ _ _ _ _ h, (remaining_eq_done.mp h).left⟩ instance eof : eof.static := static.decorate_error instance foldr_core {f : α → β → β} [p.static] : ∀ {b : β} {reps : ℕ}, (foldr_core f p b reps).static | _ 0 := static.failure | _ (reps + 1) := begin simp_rw parser.foldr_core, convert static.orelse, { convert static.bind, { apply_instance }, { intro, convert static.bind, { exact foldr_core }, { apply_instance } } }, { exact static.pure } end instance foldr {f : α → β → β} [p.static] : static (foldr f p b) := ⟨λ _ _ _ _, by { dsimp [foldr], exact of_done }⟩ instance foldl_core {f : α → β → α} {p : parser β} [p.static] : ∀ {a : α} {reps : ℕ}, (foldl_core f a p reps).static | _ 0 := static.failure | _ (reps + 1) := begin convert static.orelse, { convert static.bind, { apply_instance }, { exact λ _, foldl_core } }, { exact static.pure } end instance foldl {f : α → β → α} {p : parser β} [p.static] : static (foldl f a p) := ⟨λ _ _ _ _, by { dsimp [foldl], exact of_done }⟩ instance many [p.static] : p.many.static := static.foldr instance many_char {p : parser char} [p.static] : p.many_char.static := static.map instance many' [p.static] : p.many'.static := static.and_then instance many1 [p.static] : p.many1.static := static.seq instance many_char1 {p : parser char} [p.static] : p.many_char1.static := static.map instance sep_by1 [p.static] [sep.static] : static (sep_by1 sep p) := static.seq instance sep_by [p.static] [sep.static] : static (sep_by sep p) := static.orelse lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.static → (F p).static) : ∀ (max_depth : ℕ), static (fix_core F max_depth) | 0 := static.failure | (max_depth + 1) := hF _ (fix_core _) lemma digit : ¬ digit.static := begin have : digit "1".to_char_buffer 0 = done 1 1, { have : 0 < "s".to_char_buffer.size := dec_trivial, simpa [this] }, exact not_of_ne this zero_ne_one end lemma nat : ¬ nat.static := begin have : nat "1".to_char_buffer 0 = done 1 1, { have : 0 < "s".to_char_buffer.size := dec_trivial, simpa [this] }, exact not_of_ne this zero_ne_one end lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.static → (F p).static) : static (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact static.of_done h }⟩ end static namespace bounded variables {α β : Type} {msgs : thunk (list string)} {msg : thunk string} variables {p q : parser α} {cb : char_buffer} {n n' : ℕ} {err : dlist string} variables {a : α} {b : β} lemma done_of_unbounded (h : ¬p.bounded) : ∃ (cb : char_buffer) (n n' : ℕ) (a : α), p cb n = done n' a ∧ cb.size ≤ n := begin contrapose! h, constructor, intros cb n hn, cases hp : p cb n, { exact absurd hn (h _ _ _ _ hp).not_le }, { simp [hp] } end lemma pure : ¬ bounded (pure a) := begin introI, have : (pure a : parser α) buffer.nil 0 = done 0 a := by simp [pure_eq_done], exact absurd (bounded.of_done this) (lt_irrefl _) end instance bind {f : α → parser β} [p.bounded] : (p >>= f).bounded := begin constructor, intros cb n hn, obtain ⟨_, _, hp⟩ := bounded.exists p hn, simp [hp] end instance and_then {q : parser β} [p.bounded] : (p >> q).bounded := bounded.bind instance map [p.bounded] {f : α → β} : (f <$> p).bounded := bounded.bind instance seq {f : parser (α → β)} [f.bounded] : (f <*> p).bounded := bounded.bind instance mmap {a : α} {l : list α} {f : α → parser β} [∀ a, (f a).bounded] : ((a :: l).mmap f).bounded := bounded.bind instance mmap' {a : α} {l : list α} {f : α → parser β} [∀ a, (f a).bounded] : ((a :: l).mmap' f).bounded := bounded.and_then instance failure : @parser.bounded α failure := ⟨by simp⟩ lemma guard_iff {p : Prop} [decidable p] : bounded (guard p) ↔ ¬ p := by simpa [guard, apply_ite bounded, pure, failure] using λ _, bounded.failure instance orelse [p.bounded] [q.bounded] : (p <|> q).bounded := begin constructor, intros cb n hn, cases hx : (p <|> q) cb n with posx resx posx errx, { obtain h | ⟨h, -, -⟩ := orelse_eq_done.mp hx; exact absurd hn (of_done h).not_le }, { simp } end instance decorate_errors [p.bounded] : (@decorate_errors α msgs p).bounded := begin constructor, intros _ _, simpa using bounded.exists p end lemma decorate_errors_iff : (@parser.decorate_errors α msgs p).bounded ↔ p.bounded := begin split, { introI, constructor, intros _ _ hn, obtain ⟨_, _, h⟩ := bounded.exists (@parser.decorate_errors α msgs p) hn, simp [decorate_errors_eq_fail] at h, exact h.right.right }, { introI, constructor, intros _ _ hn, obtain ⟨_, _, h⟩ := bounded.exists p hn, simp [h] } end instance decorate_error [p.bounded] : (@decorate_error α msg p).bounded := bounded.decorate_errors lemma decorate_error_iff : (@parser.decorate_error α msg p).bounded ↔ p.bounded := decorate_errors_iff instance any_char : bounded any_char := ⟨λ cb n hn, by simp [any_char, hn]⟩ instance sat {p : char → Prop} [decidable_pred p] : bounded (sat p) := ⟨λ cb n hn, by simp [sat, hn]⟩ lemma eps : ¬ bounded eps := pure instance ch {c : char} : bounded (ch c) := bounded.decorate_error lemma char_buf_iff {cb' : char_buffer} : bounded (char_buf cb') ↔ cb' ≠ buffer.nil := begin have : cb' ≠ buffer.nil ↔ cb'.to_list ≠ [] := not_iff_not_of_iff ⟨λ h, by simp [h], λ h, by simpa using congr_arg list.to_buffer h⟩, rw [char_buf, decorate_error_iff, this], cases cb'.to_list, { simp [pure, ch] }, { simp only [iff_true, ne.def, not_false_iff], apply_instance } end instance one_of {cs : list char} : (one_of cs).bounded := bounded.decorate_errors instance one_of' {cs : list char} : (one_of' cs).bounded := bounded.and_then lemma str_iff {s : string} : (str s).bounded ↔ s ≠ "" := begin rw [str, decorate_error_iff], cases hs : s.to_list, { have : s = "", { cases s, rw [string.to_list] at hs, simpa [hs] }, simp [pure, this] }, { have : s ≠ "", { intro H, simpa [H] using hs }, simp only [this, iff_true, ne.def, not_false_iff], apply_instance } end lemma remaining : ¬ remaining.bounded := begin introI, have : remaining buffer.nil 0 = done 0 0 := by simp [remaining_eq_done], exact absurd (bounded.of_done this) (lt_irrefl _) end lemma eof : ¬ eof.bounded := begin introI, have : eof buffer.nil 0 = done 0 () := by simp [eof_eq_done], exact absurd (bounded.of_done this) (lt_irrefl _) end section fold instance foldr_core_zero {f : α → β → β} : (foldr_core f p b 0).bounded := bounded.failure instance foldl_core_zero {f : β → α → β} {b : β} : (foldl_core f b p 0).bounded := bounded.failure variables {reps : ℕ} [hpb : p.bounded] (he : ∀ cb n n' err, p cb n = fail n' err → n ≠ n') include hpb he lemma foldr_core {f : α → β → β} : (foldr_core f p b reps).bounded := begin cases reps, { exact bounded.foldr_core_zero }, constructor, intros cb n hn, obtain ⟨np, errp, hp⟩ := bounded.exists p hn, simpa [foldr_core_succ_eq_fail, hp] using he cb n np errp, end lemma foldr {f : α → β → β} : bounded (foldr f p b) := begin constructor, intros cb n hn, haveI : (parser.foldr_core f p b (cb.size - n + 1)).bounded := foldr_core he, obtain ⟨np, errp, hp⟩ := bounded.exists (parser.foldr_core f p b (cb.size - n + 1)) hn, simp [foldr, hp] end lemma foldl_core {f : β → α → β} : (foldl_core f b p reps).bounded := begin cases reps, { exact bounded.foldl_core_zero }, constructor, intros cb n hn, obtain ⟨np, errp, hp⟩ := bounded.exists p hn, simpa [foldl_core_succ_eq_fail, hp] using he cb n np errp, end lemma foldl {f : β → α → β} : bounded (foldl f b p) := begin constructor, intros cb n hn, haveI : (parser.foldl_core f b p (cb.size - n + 1)).bounded := foldl_core he, obtain ⟨np, errp, hp⟩ := bounded.exists (parser.foldl_core f b p (cb.size - n + 1)) hn, simp [foldl, hp] end lemma many : p.many.bounded := foldr he omit hpb lemma many_char {pc : parser char} [pc.bounded] (he : ∀ cb n n' err, pc cb n = fail n' err → n ≠ n'): pc.many_char.bounded := by { convert bounded.map, exact many he } include hpb lemma many' : p.many'.bounded := by { convert bounded.and_then, exact many he } end fold instance many1 [p.bounded] : p.many1.bounded := bounded.seq instance many_char1 {p : parser char} [p.bounded] : p.many_char1.bounded := bounded.map instance sep_by1 {sep : parser unit} [p.bounded] : bounded (sep_by1 sep p) := bounded.seq lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.bounded → (F p).bounded) : ∀ (max_depth : ℕ), bounded (fix_core F max_depth) | 0 := bounded.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.bounded := bounded.decorate_error instance nat : nat.bounded := bounded.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.bounded → (F p).bounded) : bounded (fix F) := begin constructor, intros cb n hn, haveI : (parser.fix_core F (cb.size - n + 1)).bounded := fix_core hF _, obtain ⟨np, errp, hp⟩ := bounded.exists (parser.fix_core F (cb.size - n + 1)) hn, simp [fix, hp] end end bounded namespace unfailing variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma of_bounded [p.bounded] : ¬ unfailing p := begin introI, cases h : p buffer.nil 0, { simpa [lt_irrefl] using bounded.of_done h }, { exact of_fail h } end instance pure : unfailing (pure a) := ⟨λ _ _, by simp [pure_eq_done]⟩ instance bind {f : α → parser β} [p.unfailing] [∀ a, (f a).unfailing] : (p >>= f).unfailing := ⟨λ cb n, begin obtain ⟨np, a, hp⟩ := exists_done p cb n, simpa [hp, and.comm, and.left_comm, and.assoc] using exists_done (f a) cb np end⟩ instance and_then {q : parser β} [p.unfailing] [q.unfailing] : (p >> q).unfailing := unfailing.bind instance map [p.unfailing] {f : α → β} : (f <$> p).unfailing := unfailing.bind instance seq {f : parser (α → β)} [f.unfailing] [p.unfailing] : (f <*> p).unfailing := unfailing.bind instance mmap {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] : (l.mmap f).unfailing := begin constructor, induction l with hd tl hl, { intros, simp [pure_eq_done] }, { intros, obtain ⟨np, a, hp⟩ := exists_done (f hd) cb n, obtain ⟨n', b, hf⟩ := hl cb np, simp [hp, hf, and.comm, and.left_comm, and.assoc, pure_eq_done] } end instance mmap' {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] : (l.mmap' f).unfailing := begin constructor, induction l with hd tl hl, { intros, simp [pure_eq_done] }, { intros, obtain ⟨np, a, hp⟩ := exists_done (f hd) cb n, obtain ⟨n', b, hf⟩ := hl cb np, simp [hp, hf, and.comm, and.left_comm, and.assoc, pure_eq_done] } end lemma failure : ¬ @parser.unfailing α failure := begin introI h, have : (failure : parser α) buffer.nil 0 = fail 0 dlist.empty := by simp, exact of_fail this end instance guard_true : unfailing (guard true) := unfailing.pure lemma guard : ¬ unfailing (guard false) := unfailing.failure instance orelse [p.unfailing] : (p <|> q).unfailing := ⟨λ cb n, by { obtain ⟨_, _, h⟩ := p.exists_done cb n, simp [success_iff, h] }⟩ instance decorate_errors [p.unfailing] : (@decorate_errors α msgs p).unfailing := ⟨λ cb n, by { obtain ⟨_, _, h⟩ := p.exists_done cb n, simp [success_iff, h] }⟩ instance decorate_error [p.unfailing] : (@decorate_error α msg p).unfailing := unfailing.decorate_errors instance any_char : conditionally_unfailing any_char := ⟨λ _ _ hn, by simp [success_iff, any_char_eq_done, hn]⟩ lemma sat : conditionally_unfailing (sat (λ _, true)) := ⟨λ _ _ hn, by simp [success_iff, sat_eq_done, hn]⟩ instance eps : unfailing eps := unfailing.pure instance remaining : remaining.unfailing := ⟨λ _ _, by simp [success_iff, remaining_eq_done]⟩ lemma foldr_core_zero {f : α → β → β} {b : β} : ¬ (foldr_core f p b 0).unfailing := unfailing.failure instance foldr_core_of_static {f : α → β → β} {b : β} {reps : ℕ} [p.static] [p.unfailing] : (foldr_core f p b (reps + 1)).unfailing := begin induction reps with reps hr, { constructor, intros cb n, obtain ⟨np, a, h⟩ := p.exists_done cb n, simpa [foldr_core_eq_done, h] using (static.of_done h).symm }, { constructor, haveI := hr, intros cb n, obtain ⟨np, a, h⟩ := p.exists_done cb n, have : n = np := static.of_done h, subst this, obtain ⟨np, b', hf⟩ := exists_done (foldr_core f p b (reps + 1)) cb n, have : n = np := static.of_done hf, subst this, refine ⟨n, f a b', _⟩, rw foldr_core_eq_done, simp [h, hf, and.comm, and.left_comm, and.assoc] } end instance foldr_core_one_of_err_static {f : α → β → β} {b : β} [p.static] [p.err_static] : (foldr_core f p b 1).unfailing := begin constructor, intros cb n, cases h : p cb n, { simpa [foldr_core_eq_done, h] using (static.of_done h).symm }, { simpa [foldr_core_eq_done, h] using (err_static.of_fail h).symm } end -- TODO: add foldr and foldl, many, etc, fix_core lemma digit : ¬ digit.unfailing := of_bounded lemma nat : ¬ nat.unfailing := of_bounded end unfailing namespace err_static variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma not_of_ne (h : p cb n = fail n' err) (hne : n ≠ n') : ¬ err_static p := by { introI, exact hne (of_fail h) } instance pure : err_static (pure a) := ⟨λ _ _ _ _, by { simp [pure_eq_done] }⟩ instance bind {f : α → parser β} [p.static] [p.err_static] [∀ a, (f a).err_static] : (p >>= f).err_static := ⟨λ cb n n' err, begin rw bind_eq_fail, rintro (hp | ⟨_, _, hp, hf⟩), { exact of_fail hp }, { exact trans (static.of_done hp) (of_fail hf) } end⟩ instance bind_of_unfailing {f : α → parser β} [p.err_static] [∀ a, (f a).unfailing] : (p >>= f).err_static := ⟨λ cb n n' err, begin rw bind_eq_fail, rintro (hp | ⟨_, _, hp, hf⟩), { exact of_fail hp }, { exact false.elim (unfailing.of_fail hf) } end⟩ instance and_then {q : parser β} [p.static] [p.err_static] [q.err_static] : (p >> q).err_static := err_static.bind instance and_then_of_unfailing {q : parser β} [p.err_static] [q.unfailing] : (p >> q).err_static := err_static.bind_of_unfailing instance map [p.err_static] {f : α → β} : (f <$> p).err_static := ⟨λ _ _ _ _, by { rw map_eq_fail, exact of_fail }⟩ instance seq {f : parser (α → β)} [f.static] [f.err_static] [p.err_static] : (f <*> p).err_static := err_static.bind instance seq_of_unfailing {f : parser (α → β)} [f.err_static] [p.unfailing] : (f <*> p).err_static := err_static.bind_of_unfailing instance mmap : Π {l : list α} {f : α → parser β} [∀ a, (f a).static] [∀ a, (f a).err_static], (l.mmap f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.bind, { exact h _ }, { exact h' _ }, { intro, convert err_static.bind, { convert static.mmap, exact h }, { apply mmap, { exact h }, { exact h' } }, { exact λ _, err_static.pure } } end instance mmap_of_unfailing : Π {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] [∀ a, (f a).err_static], (l.mmap f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.bind_of_unfailing, { exact h' _ }, { intro, convert unfailing.bind, { convert unfailing.mmap, exact h }, { exact λ _, unfailing.pure } } end instance mmap' : Π {l : list α} {f : α → parser β} [∀ a, (f a).static] [∀ a, (f a).err_static], (l.mmap' f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.and_then, { exact h _ }, { exact h' _ }, { convert mmap', { exact h }, { exact h' } } end instance mmap'_of_unfailing : Π {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] [∀ a, (f a).err_static], (l.mmap' f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.and_then_of_unfailing, { exact h' _ }, { convert unfailing.mmap', exact h } end instance failure : @parser.err_static α failure := ⟨λ _ _ _ _ h, (failure_eq_fail.mp h).left⟩ instance guard {p : Prop} [decidable p] : err_static (guard p) := ⟨λ _ _ _ _ h, (guard_eq_fail.mp h).right.left⟩ instance orelse [p.err_static] [q.mono] : (p <|> q).err_static := ⟨λ _ n n' _, begin by_cases hn : n = n', { exact λ _, hn }, { rw orelse_eq_fail_of_mono_ne hn, { exact of_fail }, { apply_instance } } end⟩ instance decorate_errors : (@decorate_errors α msgs p).err_static := ⟨λ _ _ _ _ h, (decorate_errors_eq_fail.mp h).left⟩ instance decorate_error : (@decorate_error α msg p).err_static := err_static.decorate_errors instance any_char : err_static any_char := ⟨λ _ _ _ _, by { rw [any_char_eq_fail, and.comm], simp }⟩ instance sat_iff {p : char → Prop} [decidable_pred p] : err_static (sat p) := ⟨λ _ _ _ _ h, (sat_eq_fail.mp h).left⟩ instance eps : err_static eps := err_static.pure instance ch (c : char) : err_static (ch c) := err_static.decorate_error instance char_buf {cb' : char_buffer} : err_static (char_buf cb') := err_static.decorate_error instance one_of {cs : list char} : err_static (one_of cs) := err_static.decorate_errors instance one_of' {cs : list char} : err_static (one_of' cs) := err_static.and_then_of_unfailing instance str {s : string} : err_static (str s) := err_static.decorate_error instance remaining : remaining.err_static := ⟨λ _ _ _ _, by simp [remaining_ne_fail]⟩ instance eof : eof.err_static := err_static.decorate_error -- TODO: add foldr and foldl, many, etc, fix_core lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.err_static → (F p).err_static) : ∀ (max_depth : ℕ), err_static (fix_core F max_depth) | 0 := err_static.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.err_static := err_static.decorate_error instance nat : nat.err_static := err_static.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.err_static → (F p).err_static) : err_static (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact err_static.of_fail h }⟩ end err_static namespace step variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma not_step_of_static_done [static p] (h : ∃ cb n n' a, p cb n = done n' a) : ¬ step p := begin introI, rcases h with ⟨cb, n, n', a, h⟩, have hs := static.of_done h, simpa [←hs] using of_done h end lemma pure (a : α) : ¬ step (pure a) := begin apply not_step_of_static_done, simp [pure_eq_done] end instance bind {f : α → parser β} [p.step] [∀ a, (f a).static] : (p >>= f).step := ⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, exact (static.of_done hf) ▸ (of_done hp) }⟩ instance bind' {f : α → parser β} [p.static] [∀ a, (f a).step] : (p >>= f).step := ⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, rw static.of_done hp, exact of_done hf }⟩ instance and_then {q : parser β} [p.step] [q.static] : (p >> q).step := step.bind instance and_then' {q : parser β} [p.static] [q.step] : (p >> q).step := step.bind' instance map [p.step] {f : α → β} : (f <$> p).step := ⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩ instance seq {f : parser (α → β)} [f.step] [p.static] : (f <*> p).step := step.bind instance seq' {f : parser (α → β)} [f.static] [p.step] : (f <*> p).step := step.bind' instance mmap {f : α → parser β} [(f a).step] : ([a].mmap f).step := begin convert step.bind, { apply_instance }, { intro, convert static.bind, { exact static.pure }, { exact λ _, static.pure } } end instance mmap' {f : α → parser β} [(f a).step] : ([a].mmap' f).step := begin convert step.and_then, { apply_instance }, { exact static.pure } end instance failure : @parser.step α failure := ⟨λ _ _ _ _, by simp⟩ lemma guard_true : ¬ step (guard true) := pure _ instance guard : step (guard false) := step.failure instance orelse [p.step] [q.step] : (p <|> q).step := ⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩ lemma decorate_errors_iff : (@parser.decorate_errors α msgs p).step ↔ p.step := begin split, { introI, constructor, intros cb n n' a h, have : (@parser.decorate_errors α msgs p) cb n = done n' a := by simpa using h, exact of_done this }, { introI, constructor, intros _ _ _ _ h, rw decorate_errors_eq_done at h, exact of_done h } end instance decorate_errors [p.step] : (@decorate_errors α msgs p).step := ⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩ lemma decorate_error_iff : (@parser.decorate_error α msg p).step ↔ p.step := decorate_errors_iff instance decorate_error [p.step] : (@decorate_error α msg p).step := step.decorate_errors instance any_char : step any_char := begin constructor, intros cb n, simp_rw [any_char_eq_done], rintro _ _ ⟨_, rfl, -⟩, simp end instance sat {p : char → Prop} [decidable_pred p] : step (sat p) := begin constructor, intros cb n, simp_rw [sat_eq_done], rintro _ _ ⟨_, _, rfl, -⟩, simp end lemma eps : ¬ step eps := step.pure () instance ch {c : char} : step (ch c) := step.decorate_error lemma char_buf_iff {cb' : char_buffer} : (char_buf cb').step ↔ cb'.size = 1 := begin have : char_buf cb' cb' 0 = done cb'.size () := by simp [char_buf_eq_done], split, { introI, simpa using of_done this }, { intro h, constructor, intros cb n n' _, rw [char_buf_eq_done, h], rintro ⟨rfl, -⟩, refl } end instance one_of {cs : list char} : (one_of cs).step := step.decorate_errors instance one_of' {cs : list char} : (one_of' cs).step := step.and_then lemma str_iff {s : string} : (str s).step ↔ s.length = 1 := by simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff] lemma remaining : ¬ remaining.step := begin apply not_step_of_static_done, simp [remaining_eq_done] end lemma eof : ¬ eof.step := begin apply not_step_of_static_done, simp only [eof_eq_done, exists_eq_left', exists_const], use [buffer.nil, 0], simp end -- TODO: add foldr and foldl, many, etc, fix_core lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.step → (F p).step) : ∀ (max_depth : ℕ), step (fix_core F max_depth) | 0 := step.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.step := step.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.step → (F p).step) : step (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact of_done h }⟩ end step section step variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma many1_eq_done_iff_many_eq_done [p.step] [p.bounded] {x : α} {xs : list α} : many1 p cb n = done n' (x :: xs) ↔ many p cb n = done n' (x :: xs) := begin induction hx : (x :: xs) with hd tl IH generalizing x xs n n', { simpa using hx }, split, { simp only [many1_eq_done, and_imp, exists_imp_distrib], intros np hp hm, have : np = n + 1 := step.of_done hp, have hn : n < cb.size := bounded.of_done hp, subst this, obtain ⟨k, hk⟩ : ∃ k, cb.size - n = k + 1 := nat.exists_eq_succ_of_ne_zero (ne_of_gt (nat.sub_pos_of_lt hn)), cases k, { cases tl; simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, cases tl with hd' tl', { simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, { rw ←@IH hd' tl' at hm, swap, refl, simp only [many1_eq_done, many, foldr] at hm, obtain ⟨np, hp', hf⟩ := hm, have : np = n + 1 + 1 := step.of_done hp', subst this, simpa [nat.sub_succ, many_eq_done, hp, hk, foldr_core_eq_done, hp'] using hf } }, { simp only [many_eq_done, many1_eq_done, and_imp, exists_imp_distrib], intros np hp hm, have : np = n + 1 := step.of_done hp, have hn : n < cb.size := bounded.of_done hp, subst this, obtain ⟨k, hk⟩ : ∃ k, cb.size - n = k + 1 := nat.exists_eq_succ_of_ne_zero (ne_of_gt (nat.sub_pos_of_lt hn)), cases k, { cases tl; simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, cases tl with hd' tl', { simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, { simp [hp], rw ←@IH hd' tl' (n + 1) n', swap, refl, rw [hk, foldr_core_eq_done, or.comm] at hm, obtain (hm | ⟨np, hd', tl', hp', hf, hm⟩) := hm, { simpa using hm }, simp only at hm, obtain ⟨rfl, rfl⟩ := hm, have : np = n + 1 + 1 := step.of_done hp', subst this, simp [nat.sub_succ, many, many1_eq_done, hp, hk, foldr_core_eq_done, hp', ←hf, foldr] } } end end step namespace prog variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} @[priority 100] -- see Note [lower instance priority] instance of_step [step p] : prog p := ⟨λ _ _ _ _ h, by { rw step.of_done h, exact nat.lt_succ_self _ }⟩ lemma pure (a : α) : ¬ prog (pure a) := begin introI h, have : (pure a : parser α) buffer.nil 0 = done 0 a := by simp [pure_eq_done], replace this : 0 < 0 := prog.of_done this, exact (lt_irrefl _) this end instance bind {f : α → parser β} [p.prog] [∀ a, (f a).mono] : (p >>= f).prog := ⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, exact lt_of_lt_of_le (of_done hp) (mono.of_done hf) }⟩ instance and_then {q : parser β} [p.prog] [q.mono] : (p >> q).prog := prog.bind instance map [p.prog] {f : α → β} : (f <$> p).prog := ⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩ instance seq {f : parser (α → β)} [f.prog] [p.mono] : (f <*> p).prog := prog.bind instance mmap {l : list α} {f : α → parser β} [(f a).prog] [∀ a, (f a).mono] : ((a :: l).mmap f).prog := begin constructor, simp only [and_imp, bind_eq_done, return_eq_pure, mmap, exists_imp_distrib, pure_eq_done], rintro _ _ _ _ _ _ h _ _ hp rfl rfl, exact lt_of_lt_of_le (of_done h) (mono.of_done hp) end instance mmap' {l : list α} {f : α → parser β} [(f a).prog] [∀ a, (f a).mono] : ((a :: l).mmap' f).prog := begin constructor, simp only [and_imp, bind_eq_done, mmap', exists_imp_distrib, and_then_eq_bind], intros _ _ _ _ _ _ h hm, exact lt_of_lt_of_le (of_done h) (mono.of_done hm) end instance failure : @parser.prog α failure := prog.of_step lemma guard_true : ¬ prog (guard true) := pure _ instance guard : prog (guard false) := prog.failure instance orelse [p.prog] [q.prog] : (p <|> q).prog := ⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩ lemma decorate_errors_iff : (@parser.decorate_errors α msgs p).prog ↔ p.prog := begin split, { introI, constructor, intros cb n n' a h, have : (@parser.decorate_errors α msgs p) cb n = done n' a := by simpa using h, exact of_done this }, { introI, constructor, intros _ _ _ _ h, rw decorate_errors_eq_done at h, exact of_done h } end instance decorate_errors [p.prog] : (@decorate_errors α msgs p).prog := ⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩ lemma decorate_error_iff : (@parser.decorate_error α msg p).prog ↔ p.prog := decorate_errors_iff instance decorate_error [p.prog] : (@decorate_error α msg p).prog := prog.decorate_errors instance any_char : prog any_char := prog.of_step instance sat {p : char → Prop} [decidable_pred p] : prog (sat p) := prog.of_step lemma eps : ¬ prog eps := prog.pure () instance ch {c : char} : prog (ch c) := prog.of_step lemma char_buf_iff {cb' : char_buffer} : (char_buf cb').prog ↔ cb' ≠ buffer.nil := begin have : cb' ≠ buffer.nil ↔ cb'.to_list ≠ [] := not_iff_not_of_iff ⟨λ h, by simp [h], λ h, by simpa using congr_arg list.to_buffer h⟩, rw [char_buf, this, decorate_error_iff], cases cb'.to_list, { simp [pure] }, { simp only [iff_true, ne.def, not_false_iff], apply_instance } end instance one_of {cs : list char} : (one_of cs).prog := prog.decorate_errors instance one_of' {cs : list char} : (one_of' cs).prog := prog.and_then lemma str_iff {s : string} : (str s).prog ↔ s ≠ "" := by simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff] lemma remaining : ¬ remaining.prog := begin introI h, have : remaining buffer.nil 0 = done 0 0 := by simp [remaining_eq_done], replace this : 0 < 0 := prog.of_done this, exact (lt_irrefl _) this end lemma eof : ¬ eof.prog := begin introI h, have : eof buffer.nil 0 = done 0 () := by simpa [remaining_eq_done], replace this : 0 < 0 := prog.of_done this, exact (lt_irrefl _) this end -- TODO: add foldr and foldl, many, etc, fix_core instance many1 [p.mono] [p.prog] : p.many1.prog := begin constructor, rintro cb n n' (_ | ⟨hd, tl⟩), { simp }, { rw many1_eq_done, rintro ⟨np, hp, h⟩, exact (of_done hp).trans_le (mono.of_done h) } end lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.prog → (F p).prog) : ∀ (max_depth : ℕ), prog (fix_core F max_depth) | 0 := prog.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.prog := prog.of_step instance nat : nat.prog := prog.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.prog → (F p).prog) : prog (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact of_done h }⟩ end prog variables {α β : Type} {msgs : thunk (list string)} {msg : thunk string} variables {p q : parser α} {cb : char_buffer} {n n' : ℕ} {err : dlist string} variables {a : α} {b : β} section many -- TODO: generalize to p.prog instead of p.step lemma many_sublist_of_done [p.step] [p.bounded] {l : list α} (h : p.many cb n = done n' l) : ∀ k < n' - n, p.many cb (n + k) = done n' (l.drop k) := begin induction l with hd tl hl generalizing n, { rw many_eq_done_nil at h, simp [h.left] }, intros m hm, cases m, { exact h }, rw [list.drop, nat.add_succ, ←nat.succ_add], apply hl, { rw [←many1_eq_done_iff_many_eq_done, many1_eq_done] at h, obtain ⟨_, hp, h⟩ := h, convert h, exact (step.of_done hp).symm }, { exact nat.lt_pred_iff.mpr hm }, end lemma many_eq_nil_of_done [p.step] [p.bounded] {l : list α} (h : p.many cb n = done n' l) : p.many cb n' = done n' [] := begin induction l with hd tl hl generalizing n, { convert h, rw many_eq_done_nil at h, exact h.left.symm }, { rw [←many1_eq_done_iff_many_eq_done, many1_eq_done] at h, obtain ⟨_, -, h⟩ := h, exact hl h } end lemma many_eq_nil_of_out_of_bound [p.bounded] {l : list α} (h : p.many cb n = done n' l) (hn : cb.size < n) : n' = n ∧ l = [] := begin cases l, { rw many_eq_done_nil at h, exact ⟨h.left.symm, rfl⟩ }, { rw many_eq_done at h, obtain ⟨np, hp, -⟩ := h, exact absurd (bounded.of_done hp) hn.not_lt } end lemma many1_length_of_done [p.mono] [p.step] [p.bounded] {l : list α} (h : many1 p cb n = done n' l) : l.length = n' - n := begin induction l with hd tl hl generalizing n n', { simpa using h }, { obtain ⟨k, hk⟩ : ∃ k, n' = n + k + 1 := nat.exists_eq_add_of_lt (prog.of_done h), subst hk, simp only [many1_eq_done] at h, obtain ⟨_, hp, h⟩ := h, have := step.of_done hp, subst this, cases tl, { simp only [many_eq_done_nil, add_left_inj, exists_and_distrib_right, self_eq_add_right] at h, rcases h with ⟨rfl, -⟩, simp }, rw ←many1_eq_done_iff_many_eq_done at h, specialize hl h, simp [hl, add_comm, add_assoc, nat.sub_succ] } end lemma many1_bounded_of_done [p.step] [p.bounded] {l : list α} (h : many1 p cb n = done n' l) : n' ≤ cb.size := begin induction l with hd tl hl generalizing n n', { simpa using h }, { simp only [many1_eq_done] at h, obtain ⟨np, hp, h⟩ := h, have := step.of_done hp, subst this, cases tl, { simp only [many_eq_done_nil, exists_and_distrib_right] at h, simpa [←h.left] using bounded.of_done hp }, { rw ←many1_eq_done_iff_many_eq_done at h, exact hl h } } end end many section nat /-- The `val : ℕ` produced by a successful parse of a `cb : char_buffer` is the numerical value represented by the string of decimal digits (possibly padded with 0s on the left) starting from the parsing position `n` and ending at position `n'`. The number of characters parsed in is necessarily `n' - n`. This is one of the directions of `nat_eq_done`. -/ lemma nat_of_done {val : ℕ} (h : nat cb n = done n' val) : val = (nat.of_digits 10 ((((cb.to_list.drop n).take (n' - n)).reverse.map (λ c, c.to_nat - '0'.to_nat)))) := begin /- The parser `parser.nat` that generates a decimal number from a string of digit characters does several things. First it ingests in as many digits as it can with `many1 digit`. Then, it folds over the resulting `list ℕ` using a helper function that keeps track of both the running sum an and the magnitude so far, using a `(sum, magnitude) : (ℕ × ℕ)` pair. The final sum is extracted using a `prod.fst`. To prove that the value that `parser.nat` produces, after moving precisely `n' - n` steps, is precisely what `nat.of_digits` would give, if supplied the string that is in the ingested `char_buffer` (modulo conversion from `char` to `ℕ ), we need to induct over the length `n' - n` of `cb : char_buffer` ingested, and prove that the parser must have terminated due to hitting either the end of the `char_buffer` or a non-digit character. The statement of the lemma is phrased using a combination of `list.drop` and `list.map` because there is no currently better way to extract an "interval" from a `char_buffer`. Additionally, the statement uses a `list.reverse` because `nat.of_digits` is little-endian. We try to stop referring to the `cb : char_buffer` as soon as possible, so that we can instead regard a `list char` instead, which lends itself better to proofs via induction. -/ /- We first prove some helper lemmas about the definition of `parser.nat`. Since it is defined in core, we have to work with how it is defined instead of changing its definition. In its definition, the function that folds over the parsed in digits is defined internally, as a lambda with anonymous destructor syntax, which leads to an unpleasant `nat._match_1` term when rewriting the definition of `parser.nat` away. Since we know exactly what the function is, we have a `rfl`-like lemma here to rewrite it back into a readable form. -/ have natm : nat._match_1 = (λ (d : ℕ) p, ⟨p.1 + d * p.2, p.2 * 10⟩), { ext1, ext1 ⟨⟩, refl }, -- We also have to prove what is the `prod.snd` of the result of the fold of a `list (ℕ × ℕ)` with -- the function above. We use this lemma later when we finish our inductive case. have hpow : ∀ l, (list.foldr (λ (digit : ℕ) (x : ℕ × ℕ), (x.fst + digit * x.snd, x.snd * 10)) (0, 1) l).snd = 10 ^ l.length, { intro l, induction l with hd tl hl, { simp }, { simp [hl, pow_succ, mul_comm] } }, -- We convert the hypothesis that `parser.nat` has succeeded into an existential that there is -- some list of digits that it has parsed in, and that those digits, when folded over by the -- function above, give the value at hand. simp only [nat, pure_eq_done, natm, decorate_error_eq_done, bind_eq_done] at h, obtain ⟨n', l, hp, rfl, rfl⟩ := h, -- We now want to stop working with the `cb : char_buffer` and parse positions `n` and `n'`, -- and just deal with the parsed digit list `l : list ℕ`. To do so, we have to show that -- this is precisely the list that could have been parsed in, no smaller and no greater. induction l with lhd ltl IH generalizing n n' cb, { -- Base case: we parsed in no digits whatsoever. But this is impossible because `parser.many1` -- must produce a list that is not `list.nil`, by `many1_ne_done_nil`. simpa using hp }, -- Inductive case: -- We must prove that the first digit parsed in `lhd : ℕ` is precisely the digit that is -- represented by the character at position `n` in `cb : char_buffer`. -- We will also prove the the correspondence between the subsequent digits `ltl : list ℕ` and the -- remaining characters past position `n` up to position `n'`. cases hx : (list.drop n (buffer.to_list cb)) with chd ctl, { -- Are there even characters left to parse, at position `n` in the `cb : char_buffer`? In other -- words, are we already out of bounds, and thus could not have parsed in any value -- successfully. But this must be a contradiction because `parser.digit` is a `bounded` parser, -- (due to its being defined via `parser.decorate_error`), which means it only succeeds -- in-bounds, and the `many1` parser combinator retains that property. have : cb.size ≤ n := by simpa using list.drop_eq_nil_iff_le.mp hx, exact absurd (bounded.of_done hp) this.not_lt }, -- We prove that the first digit parsed in is precisely the digit that is represented by the -- character at position `n`, which we now call `chd : char`. have chdh : chd.to_nat - '0'.to_nat = lhd, { simp only [many1_eq_done] at hp, -- We know that `parser.digit` succeeded, so it has moved to a possibly different position. -- In fact, we know that this new position is `n + 1`, by the `step` property of -- `parser.digit`. obtain ⟨_, hp, -⟩ := hp, have := step.of_done hp, subst this, -- We now unfold what it means for `parser.digit` to succeed, which means that the character -- parsed in was "numeric" (for some definition of that property), and, more importantly, -- that the `n`th character of `cb`, let's say `c`, when converted to a `ℕ` via -- `char.to_nat c - '0'.to_nat`, must be equal to the resulting value, `lhd` in our case. simp only [digit_eq_done, buffer.read_eq_nth_le_to_list, hx, buffer.length_to_list, true_and, add_left_inj, list.length, list.nth_le, eq_self_iff_true, exists_and_distrib_left, fin.coe_mk] at hp, rcases hp with ⟨_, hn, rfl, _, _⟩, -- But we already know the list corresponding to `cb : char_buffer` from position `n` and on -- is equal to `(chd :: ctl) : list char`, so our `c` above must satisfy `c = chd`. have hn' : n < cb.to_list.length := by simpa using hn, rw ←list.cons_nth_le_drop_succ hn' at hx, -- We can ignore proving any correspondence of `ctl : list char` to the other portions of the -- `cb : char_buffer`. simp only at hx, simp [hx] }, -- We know that we parsed in more than one character because of the `prog` property of -- `parser.digit`, which the `many1` parser combinator retains. In other words, we know that -- `n < n'`, and so, the list of digits `ltl` must correspond to the list of digits that -- `digit.many1 cb (n + 1)` would produce. We know that the shift of `1` in `n ↦ n + 1` holds -- due to the `step` property of `parser.digit`. -- We also get here `k : ℕ` which will indicate how many characters we parsed in past position -- `n`. We will prove later that this must be the number of digits we produced as well in `ltl`. obtain ⟨k, hk⟩ : ∃ k, n' = n + k + 1 := nat.exists_eq_add_of_lt (prog.of_done hp), have hdm : ltl = [] ∨ digit.many1 cb (n + 1) = done n' ltl, { cases ltl, { simp }, { rw many1_eq_done at hp, obtain ⟨_, hp, hp'⟩ := hp, simpa [step.of_done hp, many1_eq_done_iff_many_eq_done] using hp' } }, -- Now we case on the two possibilities, that there was only a single digit parsed in, and -- `ltl = []`, or, had we started parsing at `n + 1` instead, we'd parse in the value associated -- with `ltl`. -- We prove that the LHS, which is a fold over a `list ℕ` is equal to the RHS, which is that -- the `val : ℕ` that `nat.of_digits` produces when supplied a `list ℕ that has been produced -- via mapping a `list char` using `char.to_nat`. Specifically, that `list char` are the -- characters in the `cb : char_buffer`, from position `n` to position `n'` (excluding `n'`), -- in reverse. rcases hdm with rfl|hdm, { -- Case that `ltl = []`. simp only [many1_eq_done, many_eq_done_nil, exists_and_distrib_right] at hp, -- This means we must have failed parsing with `parser.digit` at some other position, -- which we prove must be `n + 1` via the `step` property. obtain ⟨_, hp, rfl, hp'⟩ := hp, have := step.of_done hp, subst this, -- Now we rely on the simplifier, which simplfies the LHS, which is a fold over a singleton -- list. On the RHS, `list.take (n + 1 - n)` also produces a singleton list, which, when -- reversed, is the same list. `nat.of_digits` of a singleton list is precisely the value in -- the list. And we already have that `chd.to_nat - '0'.to_nat = lhd`. simp [chdh] }, -- We now have to deal with the case where we parsed in more than one digit, and thus -- `n + 1 < n'`, which means `ctl` has one or more elements. Similarly, `ltl` has one or more -- elements. -- We finish ridding ourselves of references to `cb : char_buffer`, by relying on the fact that -- our `ctl : list char` must be the appropriate portion of `cb` once enough elements have been -- dropped and taken. have rearr : list.take (n + (k + 1) - (n + 1)) (list.drop (n + 1) (buffer.to_list cb)) = ctl.take k, { simp [←list.tail_drop, hx, nat.sub_succ, hk] }, -- We have to prove that the number of digits produced (given by `ltl`) is equal to the number -- of characters parsed in, as given by `ctl.take k`, and that this is precisely `k`. We phrase it -- in the statement using `min`, because lemmas about `list.length (list.take ...)` simplify to -- a statement that uses `min`. The `list.length` term appears from the reduction of the folding -- function, as proven above. have ltll : min k ctl.length = ltl.length, { -- Here is an example of how statements about the `list.length` of `list.take` simplify. have : (ctl.take k).length = min k ctl.length := by simp, -- We bring back the underlying definition of `ctl` as the result of a sequence of `list.take` -- and `list.drop`, so that lemmas about `list.length` of those can fire. rw [←this, ←rearr, many1_length_of_done hdm], -- Likewise, we rid ourselves of the `k` we generated earlier. have : k = n' - n - 1, { simp [hk, add_assoc] }, subst this, simp only [nat.sub_succ, add_comm, ←nat.pred_sub, buffer.length_to_list, nat.pred_one_add, min_eq_left_iff, list.length_drop, nat.add_sub_cancel_left, list.length_take, nat.sub_zero], -- We now have a goal of proving an inequality dealing with `nat` subtraction and `nat.pred`, -- both of which require special care to provide positivity hypotheses. rw [nat.sub_le_sub_right_iff, nat.pred_le_iff], { -- We know that `n' ≤ cb.size` because of the `bounded` property, that a parser will not -- produce a `done` result at a position farther than the size of the underlying -- `char_buffer`. convert many1_bounded_of_done hp, -- What is now left to prove is that `0 < cb.size`, which can be rephrased -- as proving that it is nonempty. cases hc : cb.size, { -- Proof by contradiction. Let's say that `cb.size = 0`. But we know that we succeeded -- parsing in at position `n` using a `bounded` parser, so we must have that -- `n < cb.size`. have := bounded.of_done hp, rw hc at this, -- But then `n < 0`, a contradiction. exact absurd n.zero_le this.not_le }, { simp } }, { -- Here, we use the same result as above, that `n < cb.size`, and relate it to -- `n ≤ cb.size.pred`. exact nat.le_pred_of_lt (bounded.of_done hp) } }, -- Finally, we simplify. On the LHS, we have a fold over `lhd :: ltl`, which simplifies to -- the operation of the summing folding function on `lhd` and the fold over `ltl`. To that we can -- apply the induction hypothesis, because we know that our parser would have succeeded had we -- started at position `n + 1`. We replace mentions of `cb : char_buffer` with the appropriate -- `chd :: ctl`, replace `lhd` with the appropriate statement of how it is calculated from `chd`, -- and use the lemmas describing the length of `ltl` and how it is associated with `k`. We also -- remove mentions of `n'` and replace with an expression using solely `n + k + 1`. -- We use the lemma we proved above about how the folding function produces the -- `prod.snd` value, which is `10` to the power of the length of the list provided to the fold. -- Finally, we rely on `nat.of_digits_append` for the related statement of how digits given -- are used in the `nat.of_digits` calculation, which also involves `10 ^ list.length ...`. -- The `list.append` operation appears due to the `list.reverse (chd :: ctl)`. -- We include some addition and multiplication lemmas to help the simplifier rearrange terms. simp [IH _ hdm, hx, hk, rearr, ←chdh, ←ltll, hpow, add_assoc, nat.of_digits_append, mul_comm] end /-- If we know that `parser.nat` was successful, starting at position `n` and ending at position `n'`, then it must be the case that for all `k : ℕ`, `n ≤ k`, `k < n'`, the character at the `k`th position in `cb : char_buffer` is "numeric", that is, is between `'0'` and `'9'` inclusive. This is a necessary part of proving one of the directions of `nat_eq_done`. -/ lemma nat_of_done_as_digit {val : ℕ} (h : nat cb n = done n' val) : ∀ (hn : n' ≤ cb.size) k (hk : k < n'), n ≤ k → '0' ≤ cb.read ⟨k, hk.trans_le hn⟩ ∧ cb.read ⟨k, hk.trans_le hn⟩ ≤ '9' := begin -- The properties to be shown for the characters involved rely solely on the success of -- `parser.digit` at the relevant positions, and not on the actual value `parser.nat` produced. -- We break done the success of `parser.nat` into the `parser.digit` success and throw away -- the resulting value given by `parser.nat`, and focus solely on the `list ℕ` generated by -- `parser.digit.many1`. simp only [nat, pure_eq_done, and.left_comm, decorate_error_eq_done, bind_eq_done, exists_eq_left, exists_and_distrib_left] at h, obtain ⟨xs, h, -⟩ := h, -- We want to avoid having to make statements about the `cb : char_buffer` itself. Instead, we -- induct on the `xs : list ℕ` that `parser.digit.many1` produced. induction xs with hd tl hl generalizing n n', { -- Base case: `xs` is empty. But this is a contradiction because `many1` always produces a -- nonempty list, as proven by `many1_ne_done_nil`. simpa using h }, -- Inductive case: we prove that the `parser.digit.many1` produced a valid `(hd :: tl) : list ℕ`, -- by showing that is the case for the character at position `n`, which gave `hd`, and use the -- induction hypothesis on the remaining `tl`. -- We break apart a `many1` success into a success of the underlying `parser.digit` to give `hd` -- and a `parser.digit.many` which gives `tl`. We first deal with the `hd`. rw many1_eq_done at h, -- Right away, we can throw away the information about the "new" position that `parser.digit` -- ended on because we will soon prove that it must have been `n + 1`. obtain ⟨_, hp, h⟩ := h, -- The main lemma here is `digit_eq_done`, which already proves the necessary conditions about -- the character at hand. What is left to do is properly unpack the information. simp only [digit_eq_done, and.comm, and.left_comm, digit_eq_fail, true_and, exists_eq_left, eq_self_iff_true, exists_and_distrib_left, exists_and_distrib_left] at hp, obtain ⟨rfl, -, hn, ge0, le9, rfl⟩ := hp, -- Let's now consider a position `k` between `n` and `n'`, excluding `n'`. intros hn k hk hk', -- What if we are at `n`? What if we are past `n`? We case on the `n ≤ k`. rcases hk'.eq_or_lt with rfl|hk', { -- The `n = k` case. But this is exactly what we know already, so we provide the -- relevant hypotheses. exact ⟨ge0, le9⟩ }, -- The `n < k` case. First, we check if there would have even been digits parsed in. So, we -- case on `tl : list ℕ` cases tl, { -- Case where `tl = []`. But that means `many` gave us a `[]` so either the character at -- position `k` was not "numeric" or we are out of bounds. More importantly, when `many` -- successfully produces a `[]`, it does not progress the parser head, so we have that -- `n + 1 = n'`. This will lead to a contradiction because now we have `n < k` and `k < n + 1`. simp only [many_eq_done_nil, exists_and_distrib_right] at h, -- Extract out just the `n + 1 = n'`. obtain ⟨rfl, -⟩ := h, -- Form the contradictory hypothesis, and discharge the goal. have : k < k := hk.trans_le (nat.succ_le_of_lt hk'), exact absurd this (lt_irrefl _) }, { -- Case where `tl ≠ []`. But that means that `many` produced a nonempty list as a result, so -- `many1` would have successfully parsed at this position too. We use this statement to -- rewrite our hypothesis into something that works with the induction hypothesis, and apply it. rw ←many1_eq_done_iff_many_eq_done at h, apply hl h, -- All that is left to prove is that our `k` is at least our new "lower bound" `n + 1`, which -- we have from our original split of the `n ≤ k`, since we are now on the `n < k` case. exact nat.succ_le_of_lt hk' } end /-- If we know that `parser.nat` was successful, starting at position `n` and ending at position `n'`, then it must be the case that for the ending position `n'`, either it is beyond the end of the `cb : char_buffer`, or the character at that position is not "numeric", that is, between `'0'` and `'9'` inclusive. This is a necessary part of proving one of the directions of `nat_eq_done`. -/ lemma nat_of_done_bounded {val : ℕ} (h : nat cb n = done n' val) : ∀ (hn : n' < cb.size), '0' ≤ cb.read ⟨n', hn⟩ → '9' < cb.read ⟨n', hn⟩ := begin -- The properties to be shown for the characters involved rely solely on the success of -- `parser.digit` at the relevant positions, and not on the actual value `parser.nat` produced. -- We break done the success of `parser.nat` into the `parser.digit` success and throw away -- the resulting value given by `parser.nat`, and focus solely on the `list ℕ` generated by -- `parser.digit.many1`. -- We deal with the case of `n'` is "out-of-bounds" right away by requiring that -- `∀ (hn : n' < cb.size)`. Thus we only have to prove the lemma for the cases where `n'` is still -- "in-bounds". simp only [nat, pure_eq_done, and.left_comm, decorate_error_eq_done, bind_eq_done, exists_eq_left, exists_and_distrib_left] at h, obtain ⟨xs, h, -⟩ := h, -- We want to avoid having to make statements about the `cb : char_buffer` itself. Instead, we -- induct on the `xs : list ℕ` that `parser.digit.many1` produced. induction xs with hd tl hl generalizing n n', { -- Base case: `xs` is empty. But this is a contradiction because `many1` always produces a -- nonempty list, as proven by `many1_ne_done_nil`. simpa using h }, -- Inductive case: at least one character has been parsed in, starting at position `n`. -- We know that the size of `cb : char_buffer` must be at least `n + 1` because -- `parser.digit.many1` is `bounded` (`n < cb.size`). -- We show that either we parsed in just that one character, or we use the inductive hypothesis. obtain ⟨k, hk⟩ : ∃ k, cb.size = n + k + 1 := nat.exists_eq_add_of_lt (bounded.of_done h), cases tl, { -- Case where `tl = []`, so we parsed in only `hd`. That must mean that `parser.digit` failed -- at `n + 1`. simp only [many1_eq_done, many_eq_done_nil, and.left_comm, exists_and_distrib_right, exists_eq_left] at h, -- We throw away the success information of what happened at position `n`, and we do not need -- the "error" value that the failure produced. obtain ⟨-, _, h⟩ := h, -- If `parser.digit` failed at `n + 1`, then either we hit a non-numeric character, or -- we are out of bounds. `digit_eq_fail` provides us with those two cases. simp only [digit_eq_done, and.comm, and.left_comm, digit_eq_fail, true_and, exists_eq_left, eq_self_iff_true, exists_and_distrib_left] at h, obtain (⟨rfl, h⟩ | ⟨h, -⟩) := h, { -- First case: we are still in bounds, but the character is not numeric. We must prove -- that we are still in bounds. But we know that from our initial requirement. intro hn, simpa using h hn }, { -- Second case: we are out of bounds, and somehow the fold that `many1` relied on failed. -- But we know that `parser.digit` is mono, that is, it never goes backward in position, -- in neither success nor in failure. We also have that `foldr_core` respects `mono`. -- But in this case, `foldr_core` is starting at position `n' + 1` but failing at -- position `n'`, which is a contradiction, because otherwise we would have `n' + 1 ≤ n'`. simpa using mono.of_fail h } }, { -- Case where `tl ≠ []`. But that means that `many` produced a nonempty list as a result, so -- `many1` would have successfully parsed at this position too. We use this statement to -- rewrite our hypothesis into something that works with the induction hypothesis, and apply it. rw many1_eq_done at h, obtain ⟨_, -, h⟩ := h, rw ←many1_eq_done_iff_many_eq_done at h, exact hl h } end /-- The `val : ℕ` produced by a successful parse of a `cb : char_buffer` is the numerical value represented by the string of decimal digits (possibly padded with 0s on the left) starting from the parsing position `n` and ending at position `n'`, where `n < n'`. The number of characters parsed in is necessarily `n' - n`. Additionally, all of the characters in the `cb` starting at position `n` (inclusive) up to position `n'` (exclusive) are "numeric", in that they are between `'0'` and `'9'` inclusive. Such a `char_buffer` would produce the `ℕ` value encoded by its decimal characters. -/ lemma nat_eq_done {val : ℕ} : nat cb n = done n' val ↔ ∃ (hn : n < n'), val = (nat.of_digits 10 ((((cb.to_list.drop n).take (n' - n)).reverse.map (λ c, c.to_nat - '0'.to_nat)))) ∧ (∀ (hn' : n' < cb.size), ('0' ≤ cb.read ⟨n', hn'⟩ → '9' < cb.read ⟨n', hn'⟩)) ∧ ∃ (hn'' : n' ≤ cb.size), (∀ k (hk : k < n'), n ≤ k → '0' ≤ cb.read ⟨k, hk.trans_le hn''⟩ ∧ cb.read ⟨k, hk.trans_le hn''⟩ ≤ '9') := begin -- To prove this iff, we have most of the way in the forward direction, using the lemmas proven -- above. First, we must use that `parser.nat` is `prog`, which means that on success, it must -- move forward. We also have to prove the statement that a success means the parsed in -- characters were properly "numeric". It involves first generating ane existential witness -- that the parse was completely "in-bounds". -- For the reverse direction, we first discharge the goals that deal with proving that our parser -- succeeded because it encountered characters with the proper "numeric" properties, was -- "in-bounds" and hit a nonnumeric character. The more difficult portion is proving that the -- list of characters from positions `n` to `n'`, when folded over by the function defined inside -- `parser.nat` gives exactly the same value as `nat.of_digits` when supplied with the same -- (modulo rearrangement) list. To reach this goal, we try to remove any reliance on the -- underlying `cb : char_buffer` or parsers as soon as possible, via a cased-induction. refine ⟨λ h, ⟨prog.of_done h, nat_of_done h, nat_of_done_bounded h, _⟩, _⟩, { -- To provide the existential witness that `n'` is within the bounds of the `cb : char_buffer`, -- we rely on the fact that `parser.nat` is primarily a `parser.digit.many1`, and that `many1`, -- must finish with the bounds of the `cb`, as long as the underlying parser is `step` and -- `bounded`, which `digit` is. We do not prove this as a separate lemma about `parser.nat` -- because it would almost always be only relevant in this larger theorem. -- We clone the success hypothesis `h` so that we can supply it back later. have H := h, -- We unwrap the `parser.nat` success down to the `many1` success, throwing away other info. rw [nat] at h, simp only [decorate_error_eq_done, bind_eq_done, pure_eq_done, and.left_comm, exists_eq_left, exists_and_distrib_left] at h, obtain ⟨_, h, -⟩ := h, -- Now we get our existential witness that `n' ≤ cb.size`. replace h := many1_bounded_of_done h, -- With that, we can use the lemma proved above that our characters are "numeric" exact ⟨h, nat_of_done_as_digit H h⟩ }, -- We now prove that given the `cb : char_buffer` with characters within the `n ≤ k < n'` interval -- properly "numeric" and such that their `nat.of_digits` generates the `val : ℕ`, `parser.nat` -- of that `cb`, when starting at `n`, will finish at `n'` and produce the same `val`. -- We first introduce the relevant hypotheses, including the fact that we have a valid interval -- where `n < n'` and that characters at `n'` and beyond are no longer numeric. rintro ⟨hn, hv, hb, hn', ho⟩, -- We first unwrap the `parser.nat` definition to the underlying `parser.digit.many1` success -- and the fold function of the digits. rw nat, simp only [and.left_comm, pure_eq_done, hv, decorate_error_eq_done, list.map_reverse, bind_eq_done, exists_eq_left, exists_and_distrib_left], -- We won't actually need the `val : ℕ` itself, since it is entirely characterized by the -- underlying characters. Instead, we will induct over the `list char` of characters from -- position `n` onwards, showing that if we could have provided a list at `n`, we could have -- provided a valid list of characters at `n + 1` too. clear hv val, /- We first prove some helper lemmas about the definition of `parser.nat`. Since it is defined in core, we have to work with how it is defined instead of changing its definition. In its definition, the function that folds over the parsed in digits is defined internally, as a lambda with anonymous destructor syntax, which leads to an unpleasant `nat._match_1` term when rewriting the definition of `parser.nat` away. Since we know exactly what the function is, we have a `rfl`-like lemma here to rewrite it back into a readable form. -/ have natm : nat._match_1 = (λ (d : ℕ) p, ⟨p.1 + d * p.2, p.2 * 10⟩), { ext1, ext1 ⟨⟩, refl }, -- We induct over the characters available at position `n` and onwards. Because `cb` is used -- in other expressions, we utilize the `induction H : ...` tactic to induct separately from -- destructing `cb` itself. induction H : (cb.to_list.drop n) with hd tl IH generalizing n, { -- Base case: there are no characters at position `n` or onwards, which means that -- `cb.size ≤ n`. But this is a contradiction, since we have `n < n' ≤ cb.size`. rw list.drop_eq_nil_iff_le at H, refine absurd ((lt_of_le_of_lt H hn).trans_le hn') _, simp }, { -- Inductive case: we prove that if we could have parsed from `n + 1`, we could have also parsed -- from `n`, if there was a valid numerical character at `n`. Most of the body -- of this inductive case is generating the appropriate conditions for use of the inductive -- hypothesis. specialize @IH (n + 1), -- We have, by the inductive case, that there is at least one character `hd` at position `n`, -- with the rest at `tl`. We rearrange our inductive case to make `tl` be expressed as -- list.drop (n + 1), which fits out induction hypothesis conditions better. To use the -- rearranging lemma, we must prove that we are "dropping" in bounds, which we supply on-the-fly simp only [←list.cons_nth_le_drop_succ (show n < cb.to_list.length, by simpa using hn.trans_le hn')] at H, -- We prove that parsing our `n`th character, `hd`, would have resulted in a success from -- `parser.digit`, with the appropriate `ℕ` success value. We use this later to simplify the -- unwrapped fold, since `hd` is our head character. have hdigit : digit cb n = done (n + 1) (hd.to_nat - '0'.to_nat), { -- By our necessary condition, we know that `n` is in bounds, and that the `n`th character -- has the necessary "numeric" properties. specialize ho n hn (le_refl _), -- We prove an additional result that the conversion of `hd : char` to a `ℕ` would give a -- value `x ≤ 9`, since that is part of the iff statement in the `digit_eq_done` lemma. have : (buffer.read cb ⟨n, hn.trans_le hn'⟩).to_nat - '0'.to_nat ≤ 9, { -- We rewrite the statement to be a statement about characters instead, and split the -- inequality into the case that our hypotheses prove, and that `'0' ≤ '9'`, which -- is true by computation, handled by `dec_trivial`. rw [show 9 = '9'.to_nat - '0'.to_nat, from dec_trivial, nat.sub_le_sub_right_iff], { exact ho.right }, { dec_trivial } }, -- We rely on the simplifier, mostly powered by `digit_eq_done`, and supply all the -- necessary conditions of bounds and identities about `hd`. simp [digit_eq_done, this, ←H.left, buffer.nth_le_to_list, hn.trans_le hn', ho] }, -- We now case on whether we've moved to the end of our parse or not. We phrase this as -- casing on either `n + 1 < n` or `n ≤ n + 1`. The more difficult goal comes first. cases lt_or_ge (n + 1) n' with hn'' hn'', { -- Case `n + 1 < n'`. We can directly supply this to our induction hypothesis. -- We now have to prove, for the induction hypothesis, that the characters at positions `k`, -- `n + 1 ≤ k < n'` are "numeric". We already had this for `n ≤ k < n`, so we just rearrange -- the hypotheses we already have. specialize IH hn'' _ H.right, { intros k hk hk', apply ho, exact nat.le_of_succ_le hk' }, -- With the induction hypothesis conditions satisfier, we can extract out a list that -- `parser.digit.many1` would have generated from position `n + 1`, as well as the associated -- property of the list, that it folds into what `nat.of_digits` generates from the -- characters in `cb : char_buffer`, now known as `hd :: tl`. obtain ⟨l, hdl, hvl⟩ := IH, -- Of course, the parsed in list from position `n` would be `l` prepended with the result -- of parsing in `hd`, which is provided explicitly. use (hd.to_nat - '0'.to_nat) :: l, -- We case on `l : list ℕ` so that we can make statements about the fold on `l` cases l with lhd ltl, { -- As before, if `l = []` then `many1` produced a `[]` success, which is a contradiction. simpa using hdl }, -- Case `l = lhd :: ltl`. We can rewrite the fold of the function inside `parser.nat` on -- `lhd :: ltl`, which will be used to rewrite in the goal. simp only [natm, list.foldr] at hvl, -- We also expand the fold in the goal, using the expanded fold from our hypothesis, powered -- by `many1_eq_done` to proceed in the parsing. We know exactly what the next `many` will -- produce from `many1_eq_done_iff_many_eq_done.mp` of our `hdl` hypothesis. Finally, -- we also use `hdigit` to express what the single `parser.digit` result would be at `n`. simp only [natm, hvl, many1_eq_done, hdigit, many1_eq_done_iff_many_eq_done.mp hdl, true_and, and_true, eq_self_iff_true, list.foldr, exists_eq_left'], -- Now our goal is solely about the equality of two different folding functions, one from the -- function defined inside `parser.nat` and the other as `nat.of_digits`, when applied to -- similar list inputs. -- First, we rid ourselves of `n'` by replacing with `n + m + 1`, which allows us to -- simplify the term of how many elements we are keeping using a `list.take`. obtain ⟨m, rfl⟩ : ∃ m, n' = n + m + 1 := nat.exists_eq_add_of_lt hn, -- The following rearrangement lemma is to simplify the `list.take (n' - n)` expression we had have : n + m + 1 - n = m + 1, { rw [add_assoc, nat.sub_eq_iff_eq_add, add_comm], exact nat.le_add_right _ _ }, -- We also have to prove what is the `prod.snd` of the result of the fold of a `list (ℕ × ℕ)` -- with the function above. We use this lemma to finish our inductive case. have hpow : ∀ l, (list.foldr (λ (digit : ℕ) (x : ℕ × ℕ), (x.fst + digit * x.snd, x.snd * 10)) (0, 1) l).snd = 10 ^ l.length, { intro l, induction l with hd tl hl, { simp }, { simp [hl, pow_succ, mul_comm] } }, -- We prove that the parsed list of digits `(lhd :: ltl) : list ℕ` must be of length `m` -- which is used later when the `parser.nat` fold places `ltl.length` in the exponent. have hml : ltl.length + 1 = m := by simpa using many1_length_of_done hdl, -- A simplified `list.length (list.take ...)` expression refers to the minimum of the -- underlying length and the amount of elements taken. We know that `m ≤ tl.length`, so -- we provide this auxiliary lemma so that the simplified "take-length" can simplify further have ltll : min m tl.length = m, { -- On the way to proving this, we have to actually show that `m ≤ tl.length`, by showing -- that since `tl` was a subsequence in `cb`, and was retrieved from `n + 1` to `n + m + 1`, -- then since `n + m + 1 ≤ cb.size`, we have that `tl` must be at least `m` in length. simpa [←H.right, ←nat.add_le_to_le_sub _ (hn''.trans_le hn').le, add_comm, add_assoc, add_left_comm] using hn' }, -- Finally, we rely on the simplifier. We already expressions of `nat.of_digits` on both -- the LHS and RHS. All that is left to do is to prove that the summand on the LHS is produced -- by the fold of `nat.of_digits` on the RHS of `hd :: tl`. The `nat.of_digits_append` is used -- because of the append that forms from the included `list.reverse`. The lengths of the lists -- are placed in the exponents with `10` as a base, and are combined using `←pow_succ 10`. -- Any complicated expression about list lengths is further simplified by the auxiliary -- lemmas we just proved. Finally, we assist the simplifier by rearranging terms with our -- `n + m + 1 - n = m + 1` proof and `mul_comm`. simp [this, hpow, nat.of_digits_append, mul_comm, ←pow_succ 10, hml, ltll] }, { -- Consider the case that `n' ≤ n + 1`. But then since `n < n' ≤ n + 1`, `n' = n + 1`. have : n' = n + 1 := le_antisymm hn'' (nat.succ_le_of_lt hn), subst this, -- This means we have only parsed in a single character, so the resulting parsed in list -- is explicitly formed from an expression we can construct from `hd`. use [[hd.to_nat - '0'.to_nat]], -- Our list expression simplifies nicely because it is a fold over a singleton, so we -- do not have to supply any auxiliary lemmas for it, other than what we already know about -- `hd` and the function defined in `parser.nat`. However, we will have to prove that our -- parse ended because of a good reason: either we are out of bounds or we hit a nonnumeric -- character. simp only [many1_eq_done, many_eq_done_nil, digit_eq_fail, natm, and.comm, and.left_comm, hdigit, true_and, mul_one, nat.of_digits_singleton, list.take, exists_eq_left, exists_and_distrib_right, nat.add_sub_cancel_left, eq_self_iff_true, list.reverse_singleton, zero_add, list.foldr, list.map], -- We take the route of proving that we hit a nonnumeric character, since we already have -- a hypothesis that says that characters at `n'` and past it are nonnumeric. (Note, by now -- we have substituted `n + 1` for `n'. -- We are also asked to provide the error value that our failed parse would report. But -- `digit_eq_fail` already knows what it is, so we can discharge that with an inline `rfl`. refine ⟨_, or.inl ⟨rfl, _⟩⟩, -- The nonnumeric condition looks almost exactly like the hypothesis we already have, so -- we let the simplifier align them for us simpa using hb } } end end nat end parser
d627a2af5a7e613222c2c097e19ebe27bcfce6dc
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/limits/shapes/wide_equalizers.lean
afb10a6c18cd079c9970912862e435595b9534ad
[ "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
27,925
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.epi_mono import category_theory.limits.has_limits import category_theory.limits.shapes.equalizers /-! # Wide equalizers and wide coequalizers This file defines wide (co)equalizers as special cases of (co)limits. A wide equalizer for the family of morphisms `X ⟶ Y` indexed by `J` is the categorical generalization of the subobject `{a ∈ A | ∀ j₁ j₂, f(j₁, a) = f(j₂, a)}`. Note that if `J` has fewer than two morphisms this condition is trivial, so some lemmas and definitions assume `J` is nonempty. ## Main definitions * `walking_parallel_family` is the indexing category used for wide (co)equalizer diagrams * `parallel_family` is a functor from `walking_parallel_family` to our category `C`. * a `trident` is a cone over a parallel family. * there is really only one interesting morphism in a trident: the arrow from the vertex of the trident to the domain of f and g. It is called `trident.ι`. * a `wide_equalizer` is now just a `limit (parallel_family f)` Each of these has a dual. ## Main statements * `wide_equalizer.ι_mono` states that every wide_equalizer map is a monomorphism * `is_iso_limit_cone_parallel_family_of_self` states that the identity on the domain of `f` is an equalizer of `f` and `f`. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. ## References * [F. Borceux, *Handbook of Categorical Algebra 1*][borceux-vol1] -/ noncomputable theory namespace category_theory.limits open category_theory universes w v u u₂ variables {J : Type w} /-- The type of objects for the diagram indexing a wide (co)equalizer. -/ inductive walking_parallel_family (J : Type w) : Type w | zero : walking_parallel_family | one : walking_parallel_family open walking_parallel_family instance : decidable_eq (walking_parallel_family J) | zero zero := is_true rfl | zero one := is_false (λ t, walking_parallel_family.no_confusion t) | one zero := is_false (λ t, walking_parallel_family.no_confusion t) | one one := is_true rfl instance : inhabited (walking_parallel_family J) := ⟨zero⟩ /-- The type family of morphisms for the diagram indexing a wide (co)equalizer. -/ @[derive decidable_eq] inductive walking_parallel_family.hom (J : Type w) : walking_parallel_family J → walking_parallel_family J → Type w | id : Π X : walking_parallel_family.{w} J, walking_parallel_family.hom X X | line : Π (j : J), walking_parallel_family.hom zero one /-- Satisfying the inhabited linter -/ instance (J : Type v) : inhabited (walking_parallel_family.hom J zero zero) := { default := hom.id _ } open walking_parallel_family.hom /-- Composition of morphisms in the indexing diagram for wide (co)equalizers. -/ def walking_parallel_family.hom.comp : Π (X Y Z : walking_parallel_family J) (f : walking_parallel_family.hom J X Y) (g : walking_parallel_family.hom J Y Z), walking_parallel_family.hom J X Z | _ _ _ (id _) h := h | _ _ _ (line j) (id one) := line j. local attribute [tidy] tactic.case_bash instance walking_parallel_family.category : small_category (walking_parallel_family J) := { hom := walking_parallel_family.hom J, id := walking_parallel_family.hom.id, comp := walking_parallel_family.hom.comp } @[simp] lemma walking_parallel_family.hom_id (X : walking_parallel_family J) : walking_parallel_family.hom.id X = 𝟙 X := rfl variables {C : Type u} [category.{v} C] variables {X Y : C} (f : J → (X ⟶ Y)) /-- `parallel_family f` is the diagram in `C` consisting of the given family of morphisms, each with common domain and codomain. -/ def parallel_family : walking_parallel_family J ⥤ C := { obj := λ x, walking_parallel_family.cases_on x X Y, map := λ x y h, match x, y, h with | _, _, (id _) := 𝟙 _ | _, _, (line j) := f j end, map_comp' := begin rintro _ _ _ ⟨⟩ ⟨⟩; { unfold_aux, simp; refl }, end } @[simp] lemma parallel_family_obj_zero : (parallel_family f).obj zero = X := rfl @[simp] lemma parallel_family_obj_one : (parallel_family f).obj one = Y := rfl @[simp] lemma parallel_family_map_left {j : J} : (parallel_family f).map (line j) = f j := rfl /-- Every functor indexing a wide (co)equalizer is naturally isomorphic (actually, equal) to a `parallel_family` -/ @[simps] def diagram_iso_parallel_family (F : walking_parallel_family J ⥤ C) : F ≅ parallel_family (λ j, F.map (line j)) := nat_iso.of_components (λ j, eq_to_iso $ by cases j; tidy) $ by tidy /-- `walking_parallel_pair` as a category is equivalent to a special case of `walking_parallel_family`. -/ @[simps] def walking_parallel_family_equiv_walking_parallel_pair : walking_parallel_family.{w} (ulift bool) ≌ walking_parallel_pair := { functor := parallel_family (λ p, cond p.down walking_parallel_pair_hom.left walking_parallel_pair_hom.right), inverse := parallel_pair (line (ulift.up tt)) (line (ulift.up ff)), unit_iso := nat_iso.of_components (λ X, eq_to_iso (by cases X; refl)) (by tidy), counit_iso := nat_iso.of_components (λ X, eq_to_iso (by cases X; refl)) (by tidy) } /-- A trident on `f` is just a `cone (parallel_family f)`. -/ abbreviation trident := cone (parallel_family f) /-- A cotrident on `f` and `g` is just a `cocone (parallel_family f)`. -/ abbreviation cotrident := cocone (parallel_family f) variables {f} /-- A trident `t` on the parallel family `f : J → (X ⟶ Y)` consists of two morphisms `t.π.app zero : t.X ⟶ X` and `t.π.app one : t.X ⟶ Y`. Of these, only the first one is interesting, and we give it the shorter name `trident.ι t`. -/ abbreviation trident.ι (t : trident f) := t.π.app zero /-- A cotrident `t` on the parallel family `f : J → (X ⟶ Y)` consists of two morphisms `t.ι.app zero : X ⟶ t.X` and `t.ι.app one : Y ⟶ t.X`. Of these, only the second one is interesting, and we give it the shorter name `cotrident.π t`. -/ abbreviation cotrident.π (t : cotrident f) := t.ι.app one @[simp] lemma trident.ι_eq_app_zero (t : trident f) : t.ι = t.π.app zero := rfl @[simp] lemma cotrident.π_eq_app_one (t : cotrident f) : t.π = t.ι.app one := rfl @[simp, reassoc] lemma trident.app_zero (s : trident f) (j : J) : s.π.app zero ≫ f j = s.π.app one := by rw [←s.w (line j), parallel_family_map_left] @[simp, reassoc] lemma cotrident.app_one (s : cotrident f) (j : J) : f j ≫ s.ι.app one = s.ι.app zero := by rw [←s.w (line j), parallel_family_map_left] /-- A trident on `f : J → (X ⟶ Y)` is determined by the morphism `ι : P ⟶ X` satisfying `∀ j₁ j₂, ι ≫ f j₁ = ι ≫ f j₂`. -/ @[simps] def trident.of_ι [nonempty J] {P : C} (ι : P ⟶ X) (w : ∀ j₁ j₂, ι ≫ f j₁ = ι ≫ f j₂) : trident f := { X := P, π := { app := λ X, walking_parallel_family.cases_on X ι (ι ≫ f (classical.arbitrary J)), naturality' := λ i j f, begin dsimp, cases f with _ k, { simp }, { simp [w (classical.arbitrary J) k] }, end } } /-- A cotrident on `f : J → (X ⟶ Y)` is determined by the morphism `π : Y ⟶ P` satisfying `∀ j₁ j₂, f j₁ ≫ π = f j₂ ≫ π`. -/ @[simps] def cotrident.of_π [nonempty J] {P : C} (π : Y ⟶ P) (w : ∀ j₁ j₂, f j₁ ≫ π = f j₂ ≫ π) : cotrident f := { X := P, ι := { app := λ X, walking_parallel_family.cases_on X (f (classical.arbitrary J) ≫ π) π, naturality' := λ i j f, begin dsimp, cases f with _ k, { simp }, { simp [w (classical.arbitrary J) k] } end } } -- See note [dsimp, simp] lemma trident.ι_of_ι [nonempty J] {P : C} (ι : P ⟶ X) (w : ∀ j₁ j₂, ι ≫ f j₁ = ι ≫ f j₂) : (trident.of_ι ι w).ι = ι := rfl lemma cotrident.π_of_π [nonempty J] {P : C} (π : Y ⟶ P) (w : ∀ j₁ j₂, f j₁ ≫ π = f j₂ ≫ π) : (cotrident.of_π π w).π = π := rfl @[reassoc] lemma trident.condition (j₁ j₂ : J) (t : trident f) : t.ι ≫ f j₁ = t.ι ≫ f j₂ := by rw [t.app_zero, t.app_zero] @[reassoc] lemma cotrident.condition (j₁ j₂ : J) (t : cotrident f) : f j₁ ≫ t.π = f j₂ ≫ t.π := by rw [t.app_one, t.app_one] /-- To check whether two maps are equalized by both maps of a trident, it suffices to check it for the first map -/ lemma trident.equalizer_ext [nonempty J] (s : trident f) {W : C} {k l : W ⟶ s.X} (h : k ≫ s.ι = l ≫ s.ι) : ∀ (j : walking_parallel_family J), k ≫ s.π.app j = l ≫ s.π.app j | zero := h | one := by rw [←s.app_zero (classical.arbitrary J), reassoc_of h] /-- To check whether two maps are coequalized by both maps of a cotrident, it suffices to check it for the second map -/ lemma cotrident.coequalizer_ext [nonempty J] (s : cotrident f) {W : C} {k l : s.X ⟶ W} (h : s.π ≫ k = s.π ≫ l) : ∀ (j : walking_parallel_family J), s.ι.app j ≫ k = s.ι.app j ≫ l | zero := by rw [←s.app_one (classical.arbitrary J), category.assoc, category.assoc, h] | one := h lemma trident.is_limit.hom_ext [nonempty J] {s : trident f} (hs : is_limit s) {W : C} {k l : W ⟶ s.X} (h : k ≫ s.ι = l ≫ s.ι) : k = l := hs.hom_ext $ trident.equalizer_ext _ h lemma cotrident.is_colimit.hom_ext [nonempty J] {s : cotrident f} (hs : is_colimit s) {W : C} {k l : s.X ⟶ W} (h : s.π ≫ k = s.π ≫ l) : k = l := hs.hom_ext $ cotrident.coequalizer_ext _ h /-- If `s` is a limit trident over `f`, then a morphism `k : W ⟶ X` satisfying `∀ j₁ j₂, k ≫ f j₁ = k ≫ f j₂` induces a morphism `l : W ⟶ s.X` such that `l ≫ trident.ι s = k`. -/ def trident.is_limit.lift' [nonempty J] {s : trident f} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : ∀ j₁ j₂, k ≫ f j₁ = k ≫ f j₂) : {l : W ⟶ s.X // l ≫ trident.ι s = k} := ⟨hs.lift $ trident.of_ι _ h, hs.fac _ _⟩ /-- If `s` is a colimit cotrident over `f`, then a morphism `k : Y ⟶ W` satisfying `∀ j₁ j₂, f j₁ ≫ k = f j₂ ≫ k` induces a morphism `l : s.X ⟶ W` such that `cotrident.π s ≫ l = k`. -/ def cotrident.is_colimit.desc' [nonempty J] {s : cotrident f} (hs : is_colimit s) {W : C} (k : Y ⟶ W) (h : ∀ j₁ j₂, f j₁ ≫ k = f j₂ ≫ k) : {l : s.X ⟶ W // cotrident.π s ≫ l = k} := ⟨hs.desc $ cotrident.of_π _ h, hs.fac _ _⟩ /-- This is a slightly more convenient method to verify that a trident is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def trident.is_limit.mk [nonempty J] (t : trident f) (lift : Π (s : trident f), s.X ⟶ t.X) (fac : ∀ (s : trident f), lift s ≫ t.ι = s.ι) (uniq : ∀ (s : trident f) (m : s.X ⟶ t.X) (w : ∀ j : walking_parallel_family J, m ≫ t.π.app j = s.π.app j), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, walking_parallel_family.cases_on j (fac s) (by rw [←t.w (line (classical.arbitrary J)), reassoc_of fac, s.w]), uniq' := uniq } /-- This is another convenient method to verify that a trident is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def trident.is_limit.mk' [nonempty J] (t : trident f) (create : Π (s : trident f), {l // l ≫ t.ι = s.ι ∧ ∀ {m}, m ≫ t.ι = s.ι → m = l}) : is_limit t := trident.is_limit.mk t (λ s, (create s).1) (λ s, (create s).2.1) (λ s m w, (create s).2.2 (w zero)) /-- This is a slightly more convenient method to verify that a cotrident is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def cotrident.is_colimit.mk [nonempty J] (t : cotrident f) (desc : Π (s : cotrident f), t.X ⟶ s.X) (fac : ∀ (s : cotrident f), t.π ≫ desc s = s.π) (uniq : ∀ (s : cotrident f) (m : t.X ⟶ s.X) (w : ∀ j : walking_parallel_family J, t.ι.app j ≫ m = s.ι.app j), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, walking_parallel_family.cases_on j (by rw [←t.w_assoc (line (classical.arbitrary J)), fac, s.w]) (fac s), uniq' := uniq } /-- This is another convenient method to verify that a cotrident is a colimit cocone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def cotrident.is_colimit.mk' [nonempty J] (t : cotrident f) (create : Π (s : cotrident f), {l : t.X ⟶ s.X // t.π ≫ l = s.π ∧ ∀ {m}, t.π ≫ m = s.π → m = l}) : is_colimit t := cotrident.is_colimit.mk t (λ s, (create s).1) (λ s, (create s).2.1) (λ s m w, (create s).2.2 (w one)) /-- Given a limit cone for the family `f : J → (X ⟶ Y)`, for any `Z`, morphisms from `Z` to its point are in bijection with morphisms `h : Z ⟶ X` such that `∀ j₁ j₂, h ≫ f j₁ = h ≫ f j₂`. Further, this bijection is natural in `Z`: see `trident.is_limit.hom_iso_natural`. -/ @[simps] def trident.is_limit.hom_iso [nonempty J] {t : trident f} (ht : is_limit t) (Z : C) : (Z ⟶ t.X) ≃ {h : Z ⟶ X // ∀ j₁ j₂, h ≫ f j₁ = h ≫ f j₂} := { to_fun := λ k, ⟨k ≫ t.ι, by simp⟩, inv_fun := λ h, (trident.is_limit.lift' ht _ h.prop).1, left_inv := λ k, trident.is_limit.hom_ext ht (trident.is_limit.lift' _ _ _).prop, right_inv := λ h, subtype.ext (trident.is_limit.lift' ht _ _).prop } /-- The bijection of `trident.is_limit.hom_iso` is natural in `Z`. -/ lemma trident.is_limit.hom_iso_natural [nonempty J] {t : trident f} (ht : is_limit t) {Z Z' : C} (q : Z' ⟶ Z) (k : Z ⟶ t.X) : (trident.is_limit.hom_iso ht _ (q ≫ k) : Z' ⟶ X) = q ≫ (trident.is_limit.hom_iso ht _ k : Z ⟶ X) := category.assoc _ _ _ /-- Given a colimit cocone for the family `f : J → (X ⟶ Y)`, for any `Z`, morphisms from the cocone point to `Z` are in bijection with morphisms `h : Z ⟶ X` such that `∀ j₁ j₂, f j₁ ≫ h = f j₂ ≫ h`. Further, this bijection is natural in `Z`: see `cotrident.is_colimit.hom_iso_natural`. -/ @[simps] def cotrident.is_colimit.hom_iso [nonempty J] {t : cotrident f} (ht : is_colimit t) (Z : C) : (t.X ⟶ Z) ≃ {h : Y ⟶ Z // ∀ j₁ j₂, f j₁ ≫ h = f j₂ ≫ h} := { to_fun := λ k, ⟨t.π ≫ k, by simp⟩, inv_fun := λ h, (cotrident.is_colimit.desc' ht _ h.prop).1, left_inv := λ k, cotrident.is_colimit.hom_ext ht (cotrident.is_colimit.desc' _ _ _).prop, right_inv := λ h, subtype.ext (cotrident.is_colimit.desc' ht _ _).prop } /-- The bijection of `cotrident.is_colimit.hom_iso` is natural in `Z`. -/ lemma cotrident.is_colimit.hom_iso_natural [nonempty J] {t : cotrident f} {Z Z' : C} (q : Z ⟶ Z') (ht : is_colimit t) (k : t.X ⟶ Z) : (cotrident.is_colimit.hom_iso ht _ (k ≫ q) : Y ⟶ Z') = (cotrident.is_colimit.hom_iso ht _ k : Y ⟶ Z) ≫ q := (category.assoc _ _ _).symm /-- This is a helper construction that can be useful when verifying that a category has certain wide equalizers. Given `F : walking_parallel_family ⥤ C`, which is really the same as `parallel_family (λ j, F.map (line j))`, and a trident on `λ j, F.map (line j)`, we get a cone on `F`. If you're thinking about using this, have a look at `has_wide_equalizers_of_has_limit_parallel_family`, which you may find to be an easier way of achieving your goal. -/ def cone.of_trident {F : walking_parallel_family J ⥤ C} (t : trident (λ j, F.map (line j))) : cone F := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy), naturality' := λ j j' g, by { cases g; { dsimp, simp } } } } /-- This is a helper construction that can be useful when verifying that a category has all coequalizers. Given `F : walking_parallel_family ⥤ C`, which is really the same as `parallel_family (λ j, F.map (line j))`, and a cotrident on `λ j, F.map (line j)` we get a cocone on `F`. If you're thinking about using this, have a look at `has_wide_coequalizers_of_has_colimit_parallel_family`, which you may find to be an easier way of achieving your goal. -/ def cocone.of_cotrident {F : walking_parallel_family J ⥤ C} (t : cotrident (λ j, F.map (line j))) : cocone F := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X, naturality' := λ j j' g, by { cases g; dsimp; simp [cotrident.app_one t] } } } @[simp] lemma cone.of_trident_π {F : walking_parallel_family J ⥤ C} (t : trident (λ j, F.map (line j))) (j) : (cone.of_trident t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl @[simp] lemma cocone.of_cotrident_ι {F : walking_parallel_family J ⥤ C} (t : cotrident (λ j, F.map (line j))) (j) : (cocone.of_cotrident t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl /-- Given `F : walking_parallel_family ⥤ C`, which is really the same as `parallel_family (λ j, F.map (line j))` and a cone on `F`, we get a trident on `λ j, F.map (line j)`. -/ def trident.of_cone {F : walking_parallel_family J ⥤ C} (t : cone F) : trident (λ j, F.map (line j)) := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy) } } /-- Given `F : walking_parallel_family ⥤ C`, which is really the same as `parallel_family (F.map left) (F.map right)` and a cocone on `F`, we get a cotrident on `λ j, F.map (line j)`. -/ def cotrident.of_cocone {F : walking_parallel_family J ⥤ C} (t : cocone F) : cotrident (λ j, F.map (line j)) := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X } } @[simp] lemma trident.of_cone_π {F : walking_parallel_family J ⥤ C} (t : cone F) (j) : (trident.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl @[simp] lemma cotrident.of_cocone_ι {F : walking_parallel_family J ⥤ C} (t : cocone F) (j) : (cotrident.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl /-- Helper function for constructing morphisms between wide equalizer tridents. -/ @[simps] def trident.mk_hom [nonempty J] {s t : trident f} (k : s.X ⟶ t.X) (w : k ≫ t.ι = s.ι) : s ⟶ t := { hom := k, w' := begin rintro ⟨_|_⟩, { exact w }, { simpa using w =≫ f (classical.arbitrary J) }, end } /-- To construct an isomorphism between tridents, it suffices to give an isomorphism between the cone points and check that it commutes with the `ι` morphisms. -/ @[simps] def trident.ext [nonempty J] {s t : trident f} (i : s.X ≅ t.X) (w : i.hom ≫ t.ι = s.ι) : s ≅ t := { hom := trident.mk_hom i.hom w, inv := trident.mk_hom i.inv (by rw [← w, iso.inv_hom_id_assoc]) } /-- Helper function for constructing morphisms between coequalizer cotridents. -/ @[simps] def cotrident.mk_hom [nonempty J] {s t : cotrident f} (k : s.X ⟶ t.X) (w : s.π ≫ k = t.π) : s ⟶ t := { hom := k, w' := begin rintro ⟨_|_⟩, { simpa using f (classical.arbitrary J) ≫= w }, { exact w }, end } /-- To construct an isomorphism between cotridents, it suffices to give an isomorphism between the cocone points and check that it commutes with the `π` morphisms. -/ def cotrident.ext [nonempty J] {s t : cotrident f} (i : s.X ≅ t.X) (w : s.π ≫ i.hom = t.π) : s ≅ t := { hom := cotrident.mk_hom i.hom w, inv := cotrident.mk_hom i.inv (by rw [iso.comp_inv_eq, w]) } variables (f) section /-- `has_wide_equalizer f` represents a particular choice of limiting cone for the parallel family of morphisms `f`. -/ abbreviation has_wide_equalizer := has_limit (parallel_family f) variables [has_wide_equalizer f] /-- If a wide equalizer of `f` exists, we can access an arbitrary choice of such by saying `wide_equalizer f`. -/ abbreviation wide_equalizer : C := limit (parallel_family f) /-- If a wide equalizer of `f` exists, we can access the inclusion `wide_equalizer f ⟶ X` by saying `wide_equalizer.ι f`. -/ abbreviation wide_equalizer.ι : wide_equalizer f ⟶ X := limit.π (parallel_family f) zero /-- A wide equalizer cone for a parallel family `f`. -/ abbreviation wide_equalizer.trident : trident f := limit.cone (parallel_family f) @[simp] lemma wide_equalizer.trident_ι : (wide_equalizer.trident f).ι = wide_equalizer.ι f := rfl @[simp] lemma wide_equalizer.trident_π_app_zero : (wide_equalizer.trident f).π.app zero = wide_equalizer.ι f := rfl @[reassoc] lemma wide_equalizer.condition (j₁ j₂ : J) : wide_equalizer.ι f ≫ f j₁ = wide_equalizer.ι f ≫ f j₂ := trident.condition j₁ j₂ $ limit.cone $ parallel_family f /-- The wide_equalizer built from `wide_equalizer.ι f` is limiting. -/ def wide_equalizer_is_wide_equalizer [nonempty J] : is_limit (trident.of_ι (wide_equalizer.ι f) (wide_equalizer.condition f)) := is_limit.of_iso_limit (limit.is_limit _) (trident.ext (iso.refl _) (by tidy)) variables {f} /-- A morphism `k : W ⟶ X` satisfying `∀ j₁ j₂, k ≫ f j₁ = k ≫ f j₂` factors through the wide equalizer of `f` via `wide_equalizer.lift : W ⟶ wide_equalizer f`. -/ abbreviation wide_equalizer.lift [nonempty J] {W : C} (k : W ⟶ X) (h : ∀ j₁ j₂, k ≫ f j₁ = k ≫ f j₂) : W ⟶ wide_equalizer f := limit.lift (parallel_family f) (trident.of_ι k h) @[simp, reassoc] lemma wide_equalizer.lift_ι [nonempty J] {W : C} (k : W ⟶ X) (h : ∀ j₁ j₂, k ≫ f j₁ = k ≫ f j₂) : wide_equalizer.lift k h ≫ wide_equalizer.ι f = k := limit.lift_π _ _ /-- A morphism `k : W ⟶ X` satisfying `∀ j₁ j₂, k ≫ f j₁ = k ≫ f j₂` induces a morphism `l : W ⟶ wide_equalizer f` satisfying `l ≫ wide_equalizer.ι f = k`. -/ def wide_equalizer.lift' [nonempty J] {W : C} (k : W ⟶ X) (h : ∀ j₁ j₂, k ≫ f j₁ = k ≫ f j₂) : {l : W ⟶ wide_equalizer f // l ≫ wide_equalizer.ι f = k} := ⟨wide_equalizer.lift k h, wide_equalizer.lift_ι _ _⟩ /-- Two maps into a wide equalizer are equal if they are are equal when composed with the wide equalizer map. -/ @[ext] lemma wide_equalizer.hom_ext [nonempty J] {W : C} {k l : W ⟶ wide_equalizer f} (h : k ≫ wide_equalizer.ι f = l ≫ wide_equalizer.ι f) : k = l := trident.is_limit.hom_ext (limit.is_limit _) h /-- A wide equalizer morphism is a monomorphism -/ instance wide_equalizer.ι_mono [nonempty J] : mono (wide_equalizer.ι f) := { right_cancellation := λ Z h k w, wide_equalizer.hom_ext w } end section variables {f} /-- The wide equalizer morphism in any limit cone is a monomorphism. -/ lemma mono_of_is_limit_parallel_family [nonempty J] {c : cone (parallel_family f)} (i : is_limit c) : mono (trident.ι c) := { right_cancellation := λ Z h k w, trident.is_limit.hom_ext i w } end section /-- `has_wide_coequalizer f g` represents a particular choice of colimiting cocone for the parallel family of morphisms `f`. -/ abbreviation has_wide_coequalizer := has_colimit (parallel_family f) variables [has_wide_coequalizer f] /-- If a wide coequalizer of `f`, we can access an arbitrary choice of such by saying `wide_coequalizer f`. -/ abbreviation wide_coequalizer : C := colimit (parallel_family f) /-- If a wide_coequalizer of `f` exists, we can access the corresponding projection by saying `wide_coequalizer.π f`. -/ abbreviation wide_coequalizer.π : Y ⟶ wide_coequalizer f := colimit.ι (parallel_family f) one /-- An arbitrary choice of coequalizer cocone for a parallel family `f`. -/ abbreviation wide_coequalizer.cotrident : cotrident f := colimit.cocone (parallel_family f) @[simp] lemma wide_coequalizer.cotrident_π : (wide_coequalizer.cotrident f).π = wide_coequalizer.π f := rfl @[simp] lemma wide_coequalizer.cotrident_ι_app_one : (wide_coequalizer.cotrident f).ι.app one = wide_coequalizer.π f := rfl @[reassoc] lemma wide_coequalizer.condition (j₁ j₂ : J) : f j₁ ≫ wide_coequalizer.π f = f j₂ ≫ wide_coequalizer.π f := cotrident.condition j₁ j₂ $ colimit.cocone $ parallel_family f /-- The cotrident built from `wide_coequalizer.π f` is colimiting. -/ def wide_coequalizer_is_wide_coequalizer [nonempty J] : is_colimit (cotrident.of_π (wide_coequalizer.π f) (wide_coequalizer.condition f)) := is_colimit.of_iso_colimit (colimit.is_colimit _) (cotrident.ext (iso.refl _) (by tidy)) variables {f} /-- Any morphism `k : Y ⟶ W` satisfying `∀ j₁ j₂, f j₁ ≫ k = f j₂ ≫ k` factors through the wide coequalizer of `f` via `wide_coequalizer.desc : wide_coequalizer f ⟶ W`. -/ abbreviation wide_coequalizer.desc [nonempty J] {W : C} (k : Y ⟶ W) (h : ∀ j₁ j₂, f j₁ ≫ k = f j₂ ≫ k) : wide_coequalizer f ⟶ W := colimit.desc (parallel_family f) (cotrident.of_π k h) @[simp, reassoc] lemma wide_coequalizer.π_desc [nonempty J] {W : C} (k : Y ⟶ W) (h : ∀ j₁ j₂, f j₁ ≫ k = f j₂ ≫ k) : wide_coequalizer.π f ≫ wide_coequalizer.desc k h = k := colimit.ι_desc _ _ /-- Any morphism `k : Y ⟶ W` satisfying `∀ j₁ j₂, f j₁ ≫ k = f j₂ ≫ k` induces a morphism `l : wide_coequalizer f ⟶ W` satisfying `wide_coequalizer.π ≫ g = l`. -/ def wide_coequalizer.desc' [nonempty J] {W : C} (k : Y ⟶ W) (h : ∀ j₁ j₂, f j₁ ≫ k = f j₂ ≫ k) : {l : wide_coequalizer f ⟶ W // wide_coequalizer.π f ≫ l = k} := ⟨wide_coequalizer.desc k h, wide_coequalizer.π_desc _ _⟩ /-- Two maps from a wide coequalizer are equal if they are equal when composed with the wide coequalizer map -/ @[ext] lemma wide_coequalizer.hom_ext [nonempty J] {W : C} {k l : wide_coequalizer f ⟶ W} (h : wide_coequalizer.π f ≫ k = wide_coequalizer.π f ≫ l) : k = l := cotrident.is_colimit.hom_ext (colimit.is_colimit _) h /-- A wide coequalizer morphism is an epimorphism -/ instance wide_coequalizer.π_epi [nonempty J] : epi (wide_coequalizer.π f) := { left_cancellation := λ Z h k w, wide_coequalizer.hom_ext w } end section variables {f} /-- The wide coequalizer morphism in any colimit cocone is an epimorphism. -/ lemma epi_of_is_colimit_parallel_family [nonempty J] {c : cocone (parallel_family f)} (i : is_colimit c) : epi (c.ι.app one) := { left_cancellation := λ Z h k w, cotrident.is_colimit.hom_ext i w } end variables (C) /-- `has_wide_equalizers` represents a choice of wide equalizer for every family of morphisms -/ abbreviation has_wide_equalizers := Π J, has_limits_of_shape (walking_parallel_family.{w} J) C /-- `has_wide_coequalizers` represents a choice of wide coequalizer for every family of morphisms -/ abbreviation has_wide_coequalizers := Π J, has_colimits_of_shape (walking_parallel_family.{w} J) C /-- If `C` has all limits of diagrams `parallel_family f`, then it has all wide equalizers -/ lemma has_wide_equalizers_of_has_limit_parallel_family [Π {J : Type w} {X Y : C} {f : J → (X ⟶ Y)}, has_limit (parallel_family f)] : has_wide_equalizers.{w} C := λ J, { has_limit := λ F, has_limit_of_iso (diagram_iso_parallel_family F).symm } /-- If `C` has all colimits of diagrams `parallel_family f`, then it has all wide coequalizers -/ lemma has_wide_coequalizers_of_has_colimit_parallel_family [Π {J : Type w} {X Y : C} {f : J → (X ⟶ Y)}, has_colimit (parallel_family f)] : has_wide_coequalizers.{w} C := λ J, { has_colimit := λ F, has_colimit_of_iso (diagram_iso_parallel_family F) } @[priority 10] instance has_equalizers_of_has_wide_equalizers [has_wide_equalizers.{w} C] : has_equalizers C := has_limits_of_shape_of_equivalence.{w} walking_parallel_family_equiv_walking_parallel_pair @[priority 10] instance has_coequalizers_of_has_wide_coequalizers [has_wide_coequalizers.{w} C] : has_coequalizers C := has_colimits_of_shape_of_equivalence.{w} walking_parallel_family_equiv_walking_parallel_pair end category_theory.limits
e1f8b44c7583908aac17f7a847636535f052be4d
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/fintype/card.lean
8d5532a2a5ee693010ca0a64df7b7cd4bf7d124f
[ "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
9,827
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fintype.basic import algebra.big_operators.ring import algebra.big_operators.option /-! Results about "big operations" over a `fintype`, and consequent results about cardinalities of certain types. ## Implementation note This content had previously been in `data.fintype.basic`, but was moved here to avoid requiring `algebra.big_operators` (and hence many other imports) as a dependency of `fintype`. However many of the results here really belong in `algebra.big_operators.basic` and should be moved at some point. -/ universes u v variables {α : Type*} {β : Type*} {γ : Type*} open_locale big_operators namespace fintype @[to_additive] lemma prod_bool [comm_monoid α] (f : bool → α) : ∏ b, f b = f tt * f ff := by simp lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = ∑ a : α, 1 := finset.card_eq_sum_ones _ section open finset variables {ι : Type*} [decidable_eq ι] [fintype ι] @[to_additive] lemma prod_extend_by_one [comm_monoid α] (s : finset ι) (f : ι → α) : ∏ i, (if i ∈ s then f i else 1) = ∏ i in s, f i := by rw [← prod_filter, filter_mem_eq_inter, univ_inter] end section variables {M : Type*} [fintype α] [comm_monoid M] @[to_additive] lemma prod_eq_one (f : α → M) (h : ∀ a, f a = 1) : (∏ a, f a) = 1 := finset.prod_eq_one $ λ a ha, h a @[to_additive] lemma prod_congr (f g : α → M) (h : ∀ a, f a = g a) : (∏ a, f a) = ∏ a, g a := finset.prod_congr rfl $ λ a ha, h a @[to_additive] lemma prod_eq_single {f : α → M} (a : α) (h : ∀ x ≠ a, f x = 1) : (∏ x, f x) = f a := finset.prod_eq_single a (λ x _ hx, h x hx) $ λ ha, (ha (finset.mem_univ a)).elim @[to_additive] lemma prod_eq_mul {f : α → M} (a b : α) (h₁ : a ≠ b) (h₂ : ∀ x, x ≠ a ∧ x ≠ b → f x = 1) : (∏ x, f x) = (f a) * (f b) := begin apply finset.prod_eq_mul a b h₁ (λ x _ hx, h₂ x hx); exact λ hc, (hc (finset.mem_univ _)).elim end /-- If a product of a `finset` of a subsingleton type has a given value, so do the terms in that product. -/ @[to_additive "If a sum of a `finset` of a subsingleton type has a given value, so do the terms in that sum."] lemma eq_of_subsingleton_of_prod_eq {ι : Type*} [subsingleton ι] {s : finset ι} {f : ι → M} {b : M} (h : ∏ i in s, f i = b) : ∀ i ∈ s, f i = b := finset.eq_of_card_le_one_of_prod_eq (finset.card_le_one_of_subsingleton s) h end end fintype open finset section variables {M : Type*} [fintype α] [comm_monoid M] @[simp, to_additive] lemma fintype.prod_option (f : option α → M) : ∏ i, f i = f none * ∏ i, f (some i) := finset.prod_insert_none f univ end open finset @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = ∑ a, fintype.card (β a) := card_sigma _ _ @[simp] lemma finset.card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = ∏ a in s, card (t a) := multiset.card_pi _ _ @[simp] lemma fintype.card_pi_finset [decidable_eq α] [fintype α] {δ : α → Type*} (t : Π a, finset (δ a)) : (fintype.pi_finset t).card = ∏ a, card (t a) := by simp [fintype.pi_finset, card_map] @[simp] lemma fintype.card_pi {β : α → Type*} [decidable_eq α] [fintype α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = ∏ a, fintype.card (β a) := fintype.card_pi_finset _ -- FIXME ouch, this should be in the main file. @[simp] lemma fintype.card_fun [decidable_eq α] [fintype α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const]; refl @[simp] lemma card_vector [fintype α] (n : ℕ) : fintype.card (vector α n) = fintype.card α ^ n := by rw fintype.of_equiv_card; simp @[simp, to_additive] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : ∏ x in univ.attach, f x = ∏ x, f ⟨x, (mem_univ _)⟩ := fintype.prod_equiv (equiv.subtype_univ_equiv (λ x, mem_univ _)) _ _ (λ x, by simp) /-- Taking a product over `univ.pi t` is the same as taking the product over `fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and `fintype.pi_finset t` is a `finset (Π a, t a)`. -/ @[to_additive "Taking a sum over `univ.pi t` is the same as taking the sum over `fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and `fintype.pi_finset t` is a `finset (Π a, t a)`."] lemma finset.prod_univ_pi [decidable_eq α] [fintype α] [comm_monoid β] {δ : α → Type*} {t : Π (a : α), finset (δ a)} (f : (Π (a : α), a ∈ (univ : finset α) → δ a) → β) : ∏ x in univ.pi t, f x = ∏ x in fintype.pi_finset t, f (λ a _, x a) := prod_bij (λ x _ a, x a (mem_univ _)) (by simp) (by simp) (by simp [function.funext_iff] {contextual := tt}) (λ x hx, ⟨λ a _, x a, by simp * at *⟩) /-- The product over `univ` of a sum can be written as a sum over the product of sets, `fintype.pi_finset`. `finset.prod_sum` is an alternative statement when the product is not over `univ` -/ lemma finset.prod_univ_sum [decidable_eq α] [fintype α] [comm_semiring β] {δ : α → Type u_1} [Π (a : α), decidable_eq (δ a)] {t : Π (a : α), finset (δ a)} {f : Π (a : α), δ a → β} : ∏ a, ∑ b in t a, f a b = ∑ p in fintype.pi_finset t, ∏ x, f x (p x) := by simp only [finset.prod_attach_univ, prod_sum, finset.sum_univ_pi] /-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a fintype of cardinality `n` gives `(a + b)^n`. The "good" proof involves expanding along all coordinates using the fact that `x^n` is multilinear, but multilinear maps are only available now over rings, so we give instead a proof reducing to the usual binomial theorem to have a result over semirings. -/ lemma fintype.sum_pow_mul_eq_add_pow (α : Type*) [fintype α] {R : Type*} [comm_semiring R] (a b : R) : ∑ s : finset α, a ^ s.card * b ^ (fintype.card α - s.card) = (a + b) ^ (fintype.card α) := finset.sum_pow_mul_eq_add_pow _ _ _ @[to_additive] lemma function.bijective.prod_comp [fintype α] [fintype β] [comm_monoid γ] {f : α → β} (hf : function.bijective f) (g : β → γ) : ∏ i, g (f i) = ∏ i, g i := fintype.prod_bijective f hf _ _ (λ x, rfl) @[to_additive] lemma equiv.prod_comp [fintype α] [fintype β] [comm_monoid γ] (e : α ≃ β) (f : β → γ) : ∏ i, f (e i) = ∏ i, f i := e.bijective.prod_comp f @[to_additive] lemma equiv.prod_comp' [fintype α] [fintype β] [comm_monoid γ] (e : α ≃ β) (f : α → γ) (g : β → γ) (h : ∀ i, f i = g (e i)) : ∏ i, f i = ∏ i, g i := (show f = g ∘ e, from funext h).symm ▸ e.prod_comp _ /-- It is equivalent to sum a function over `fin n` or `finset.range n`. -/ @[to_additive] lemma fin.prod_univ_eq_prod_range [comm_monoid α] (f : ℕ → α) (n : ℕ) : ∏ i : fin n, f i = ∏ i in range n, f i := calc (∏ i : fin n, f i) = ∏ i : {x // x ∈ range n}, f i : (fin.equiv_subtype.trans (equiv.subtype_equiv_right (by simp))).prod_comp' _ _ (by simp) ... = ∏ i in range n, f i : by rw [← attach_eq_univ, prod_attach] @[to_additive] lemma finset.prod_fin_eq_prod_range [comm_monoid β] {n : ℕ} (c : fin n → β) : ∏ i, c i = ∏ i in finset.range n, if h : i < n then c ⟨i, h⟩ else 1 := begin rw [← fin.prod_univ_eq_prod_range, finset.prod_congr rfl], rintros ⟨i, hi⟩ _, simp only [fin.coe_eq_val, hi, dif_pos] end @[to_additive] lemma finset.prod_to_finset_eq_subtype {M : Type*} [comm_monoid M] [fintype α] (p : α → Prop) [decidable_pred p] (f : α → M) : ∏ a in {x | p x}.to_finset, f a = ∏ a : subtype p, f a := by { rw ← finset.prod_subtype, simp } @[to_additive] lemma finset.prod_fiberwise [decidable_eq β] [fintype β] [comm_monoid γ] (s : finset α) (f : α → β) (g : α → γ) : ∏ b : β, ∏ a in s.filter (λ a, f a = b), g a = ∏ a in s, g a := finset.prod_fiberwise_of_maps_to (λ x _, mem_univ _) _ @[to_additive] lemma fintype.prod_fiberwise [fintype α] [decidable_eq β] [fintype β] [comm_monoid γ] (f : α → β) (g : α → γ) : (∏ b : β, ∏ a : {a // f a = b}, g (a : α)) = ∏ a, g a := begin rw [← (equiv.sigma_fiber_equiv f).prod_comp, ← univ_sigma_univ, prod_sigma], refl end lemma fintype.prod_dite [fintype α] {p : α → Prop} [decidable_pred p] [comm_monoid β] (f : Π (a : α) (ha : p a), β) (g : Π (a : α) (ha : ¬p a), β) : (∏ a, dite (p a) (f a) (g a)) = (∏ a : {a // p a}, f a a.2) * (∏ a : {a // ¬p a}, g a a.2) := begin simp only [prod_dite, attach_eq_univ], congr' 1, { convert (equiv.subtype_equiv_right _).prod_comp (λ x : {x // p x}, f x x.2), simp }, { convert (equiv.subtype_equiv_right _).prod_comp (λ x : {x // ¬p x}, g x x.2), simp } end section open finset variables {α₁ : Type*} {α₂ : Type*} {M : Type*} [fintype α₁] [fintype α₂] [comm_monoid M] @[to_additive] lemma fintype.prod_sum_elim (f : α₁ → M) (g : α₂ → M) : (∏ x, sum.elim f g x) = (∏ a₁, f a₁) * (∏ a₂, g a₂) := by { classical, rw [univ_sum_type, prod_sum_elim] } @[to_additive] lemma fintype.prod_sum_type (f : α₁ ⊕ α₂ → M) : (∏ x, f x) = (∏ a₁, f (sum.inl a₁)) * (∏ a₂, f (sum.inr a₂)) := by simp only [← fintype.prod_sum_elim, sum.elim_comp_inl_inr] end
a56fbd92a29abe8f20d203d96514efc16d336f22
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/set/intervals/basic.lean
c00cfd830fdefa1f0142cc4ece013b0f58c969d3
[ "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
54,225
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot, Yury Kudryashov, Rémy Degenne -/ import algebra.order.group import data.set.basic import order.rel_iso import order.order_dual /-! # Intervals In any preorder `α`, we define intervals (which on each side can be either infinite, open, or closed) using the following naming conventions: - `i`: infinite - `o`: open - `c`: closed Each interval has the name `I` + letter for left side + letter for right side. For instance, `Ioc a b` denotes the inverval `(a, b]`. This file contains these definitions, and basic facts on inclusion, intersection, difference of intervals (where the precise statements may depend on the properties of the order, in particular for some statements it should be `linear_order` or `densely_ordered`). TODO: This is just the beginning; a lot of rules are missing -/ universe u namespace set open set open order_dual (to_dual of_dual) section intervals variables {α : Type u} [preorder α] {a a₁ a₂ b b₁ b₂ x : α} /-- Left-open right-open interval -/ def Ioo (a b : α) := {x | a < x ∧ x < b} /-- Left-closed right-open interval -/ def Ico (a b : α) := {x | a ≤ x ∧ x < b} /-- Left-infinite right-open interval -/ def Iio (a : α) := {x | x < a} /-- Left-closed right-closed interval -/ def Icc (a b : α) := {x | a ≤ x ∧ x ≤ b} /-- Left-infinite right-closed interval -/ def Iic (b : α) := {x | x ≤ b} /-- Left-open right-closed interval -/ def Ioc (a b : α) := {x | a < x ∧ x ≤ b} /-- Left-closed right-infinite interval -/ def Ici (a : α) := {x | a ≤ x} /-- Left-open right-infinite interval -/ def Ioi (a : α) := {x | a < x} lemma Ioo_def (a b : α) : {x | a < x ∧ x < b} = Ioo a b := rfl lemma Ico_def (a b : α) : {x | a ≤ x ∧ x < b} = Ico a b := rfl lemma Iio_def (a : α) : {x | x < a} = Iio a := rfl lemma Icc_def (a b : α) : {x | a ≤ x ∧ x ≤ b} = Icc a b := rfl lemma Iic_def (b : α) : {x | x ≤ b} = Iic b := rfl lemma Ioc_def (a b : α) : {x | a < x ∧ x ≤ b} = Ioc a b := rfl lemma Ici_def (a : α) : {x | a ≤ x} = Ici a := rfl lemma Ioi_def (a : α) : {x | a < x} = Ioi a := rfl @[simp] lemma mem_Ioo : x ∈ Ioo a b ↔ a < x ∧ x < b := iff.rfl @[simp] lemma mem_Ico : x ∈ Ico a b ↔ a ≤ x ∧ x < b := iff.rfl @[simp] lemma mem_Iio : x ∈ Iio b ↔ x < b := iff.rfl @[simp] lemma mem_Icc : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Iic : x ∈ Iic b ↔ x ≤ b := iff.rfl @[simp] lemma mem_Ioc : x ∈ Ioc a b ↔ a < x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Ici : x ∈ Ici a ↔ a ≤ x := iff.rfl @[simp] lemma mem_Ioi : x ∈ Ioi a ↔ a < x := iff.rfl @[simp] lemma left_mem_Ioo : a ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma left_mem_Ico : a ∈ Ico a b ↔ a < b := by simp [le_refl] @[simp] lemma left_mem_Icc : a ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma left_mem_Ioc : a ∈ Ioc a b ↔ false := by simp [lt_irrefl] lemma left_mem_Ici : a ∈ Ici a := by simp @[simp] lemma right_mem_Ioo : b ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Ico : b ∈ Ico a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Icc : b ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma right_mem_Ioc : b ∈ Ioc a b ↔ a < b := by simp [le_refl] lemma right_mem_Iic : a ∈ Iic a := by simp @[simp] lemma dual_Ici : Ici (to_dual a) = of_dual ⁻¹' Iic a := rfl @[simp] lemma dual_Iic : Iic (to_dual a) = of_dual ⁻¹' Ici a := rfl @[simp] lemma dual_Ioi : Ioi (to_dual a) = of_dual ⁻¹' Iio a := rfl @[simp] lemma dual_Iio : Iio (to_dual a) = of_dual ⁻¹' Ioi a := rfl @[simp] lemma dual_Icc : Icc (to_dual a) (to_dual b) = of_dual ⁻¹' Icc b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioc : Ioc (to_dual a) (to_dual b) = of_dual ⁻¹' Ico b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ico : Ico (to_dual a) (to_dual b) = of_dual ⁻¹' Ioc b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioo : Ioo (to_dual a) (to_dual b) = of_dual ⁻¹' Ioo b a := set.ext $ λ x, and_comm _ _ @[simp] lemma nonempty_Icc : (Icc a b).nonempty ↔ a ≤ b := ⟨λ ⟨x, hx⟩, hx.1.trans hx.2, λ h, ⟨a, left_mem_Icc.2 h⟩⟩ @[simp] lemma nonempty_Ico : (Ico a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, hx.1.trans_lt hx.2, λ h, ⟨a, left_mem_Ico.2 h⟩⟩ @[simp] lemma nonempty_Ioc : (Ioc a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, hx.1.trans_le hx.2, λ h, ⟨b, right_mem_Ioc.2 h⟩⟩ @[simp] lemma nonempty_Ici : (Ici a).nonempty := ⟨a, left_mem_Ici⟩ @[simp] lemma nonempty_Iic : (Iic a).nonempty := ⟨a, right_mem_Iic⟩ @[simp] lemma nonempty_Ioo [densely_ordered α] : (Ioo a b).nonempty ↔ a < b := ⟨λ ⟨x, ha, hb⟩, ha.trans hb, exists_between⟩ @[simp] lemma nonempty_Ioi [no_top_order α] : (Ioi a).nonempty := no_top a @[simp] lemma nonempty_Iio [no_bot_order α] : (Iio a).nonempty := no_bot a lemma nonempty_Icc_subtype (h : a ≤ b) : nonempty (Icc a b) := nonempty.to_subtype (nonempty_Icc.mpr h) lemma nonempty_Ico_subtype (h : a < b) : nonempty (Ico a b) := nonempty.to_subtype (nonempty_Ico.mpr h) lemma nonempty_Ioc_subtype (h : a < b) : nonempty (Ioc a b) := nonempty.to_subtype (nonempty_Ioc.mpr h) /-- An interval `Ici a` is nonempty. -/ instance nonempty_Ici_subtype : nonempty (Ici a) := nonempty.to_subtype nonempty_Ici /-- An interval `Iic a` is nonempty. -/ instance nonempty_Iic_subtype : nonempty (Iic a) := nonempty.to_subtype nonempty_Iic lemma nonempty_Ioo_subtype [densely_ordered α] (h : a < b) : nonempty (Ioo a b) := nonempty.to_subtype (nonempty_Ioo.mpr h) /-- In a `no_top_order`, the intervals `Ioi` are nonempty. -/ instance nonempty_Ioi_subtype [no_top_order α] : nonempty (Ioi a) := nonempty.to_subtype nonempty_Ioi /-- In a `no_bot_order`, the intervals `Iio` are nonempty. -/ instance nonempty_Iio_subtype [no_bot_order α] : nonempty (Iio a) := nonempty.to_subtype nonempty_Iio @[simp] lemma Icc_eq_empty (h : ¬a ≤ b) : Icc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨ha, hb⟩, h (ha.trans hb) @[simp] lemma Ico_eq_empty (h : ¬a < b) : Ico a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨ha, hb⟩, h (ha.trans_lt hb) @[simp] lemma Ioc_eq_empty (h : ¬a < b) : Ioc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨ha, hb⟩, h (ha.trans_le hb) @[simp] lemma Ioo_eq_empty (h : ¬a < b) : Ioo a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨ha, hb⟩, h (ha.trans hb) @[simp] lemma Icc_eq_empty_of_lt (h : b < a) : Icc a b = ∅ := Icc_eq_empty h.not_le @[simp] lemma Ico_eq_empty_of_le (h : b ≤ a) : Ico a b = ∅ := Ico_eq_empty h.not_lt @[simp] lemma Ioc_eq_empty_of_le (h : b ≤ a) : Ioc a b = ∅ := Ioc_eq_empty h.not_lt @[simp] lemma Ioo_eq_empty_of_le (h : b ≤ a) : Ioo a b = ∅ := Ioo_eq_empty h.not_lt @[simp] lemma Ico_self (a : α) : Ico a a = ∅ := Ico_eq_empty $ lt_irrefl _ @[simp] lemma Ioc_self (a : α) : Ioc a a = ∅ := Ioc_eq_empty $ lt_irrefl _ @[simp] lemma Ioo_self (a : α) : Ioo a a = ∅ := Ioo_eq_empty $ lt_irrefl _ lemma Ici_subset_Ici : Ici a ⊆ Ici b ↔ b ≤ a := ⟨λ h, h $ left_mem_Ici, λ h x hx, h.trans hx⟩ lemma Iic_subset_Iic : Iic a ⊆ Iic b ↔ a ≤ b := @Ici_subset_Ici (order_dual α) _ _ _ lemma Ici_subset_Ioi : Ici a ⊆ Ioi b ↔ b < a := ⟨λ h, h left_mem_Ici, λ h x hx, h.trans_le hx⟩ lemma Iic_subset_Iio : Iic a ⊆ Iio b ↔ a < b := ⟨λ h, h right_mem_Iic, λ h x hx, lt_of_le_of_lt hx h⟩ lemma Ioo_subset_Ioo (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨h₁.trans_lt hx₁, hx₂.trans_le h₂⟩ lemma Ioo_subset_Ioo_left (h : a₁ ≤ a₂) : Ioo a₂ b ⊆ Ioo a₁ b := Ioo_subset_Ioo h le_rfl lemma Ioo_subset_Ioo_right (h : b₁ ≤ b₂) : Ioo a b₁ ⊆ Ioo a b₂ := Ioo_subset_Ioo le_rfl h lemma Ico_subset_Ico (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ico a₁ b₁ ⊆ Ico a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨h₁.trans hx₁, hx₂.trans_le h₂⟩ lemma Ico_subset_Ico_left (h : a₁ ≤ a₂) : Ico a₂ b ⊆ Ico a₁ b := Ico_subset_Ico h le_rfl lemma Ico_subset_Ico_right (h : b₁ ≤ b₂) : Ico a b₁ ⊆ Ico a b₂ := Ico_subset_Ico le_rfl h lemma Icc_subset_Icc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Icc a₁ b₁ ⊆ Icc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨h₁.trans hx₁, le_trans hx₂ h₂⟩ lemma Icc_subset_Icc_left (h : a₁ ≤ a₂) : Icc a₂ b ⊆ Icc a₁ b := Icc_subset_Icc h le_rfl lemma Icc_subset_Icc_right (h : b₁ ≤ b₂) : Icc a b₁ ⊆ Icc a b₂ := Icc_subset_Icc le_rfl h lemma Icc_subset_Ioo (ha : a₂ < a₁) (hb : b₁ < b₂) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ := λ x hx, ⟨ha.trans_le hx.1, hx.2.trans_lt hb⟩ lemma Icc_subset_Ici_self : Icc a b ⊆ Ici a := λ x, and.left lemma Icc_subset_Iic_self : Icc a b ⊆ Iic b := λ x, and.right lemma Ioc_subset_Iic_self : Ioc a b ⊆ Iic b := λ x, and.right lemma Ioc_subset_Ioc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioc a₁ b₁ ⊆ Ioc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨h₁.trans_lt hx₁, hx₂.trans h₂⟩ lemma Ioc_subset_Ioc_left (h : a₁ ≤ a₂) : Ioc a₂ b ⊆ Ioc a₁ b := Ioc_subset_Ioc h le_rfl lemma Ioc_subset_Ioc_right (h : b₁ ≤ b₂) : Ioc a b₁ ⊆ Ioc a b₂ := Ioc_subset_Ioc le_rfl h lemma Ico_subset_Ioo_left (h₁ : a₁ < a₂) : Ico a₂ b ⊆ Ioo a₁ b := λ x, and.imp_left h₁.trans_le lemma Ioc_subset_Ioo_right (h : b₁ < b₂) : Ioc a b₁ ⊆ Ioo a b₂ := λ x, and.imp_right $ λ h', h'.trans_lt h lemma Icc_subset_Ico_right (h₁ : b₁ < b₂) : Icc a b₁ ⊆ Ico a b₂ := λ x, and.imp_right $ λ h₂, h₂.trans_lt h₁ lemma Ioo_subset_Ico_self : Ioo a b ⊆ Ico a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Ioc_self : Ioo a b ⊆ Ioc a b := λ x, and.imp_right le_of_lt lemma Ico_subset_Icc_self : Ico a b ⊆ Icc a b := λ x, and.imp_right le_of_lt lemma Ioc_subset_Icc_self : Ioc a b ⊆ Icc a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Icc_self : Ioo a b ⊆ Icc a b := subset.trans Ioo_subset_Ico_self Ico_subset_Icc_self lemma Ico_subset_Iio_self : Ico a b ⊆ Iio b := λ x, and.right lemma Ioo_subset_Iio_self : Ioo a b ⊆ Iio b := λ x, and.right lemma Ioc_subset_Ioi_self : Ioc a b ⊆ Ioi a := λ x, and.left lemma Ioo_subset_Ioi_self : Ioo a b ⊆ Ioi a := λ x, and.left lemma Ioi_subset_Ici_self : Ioi a ⊆ Ici a := λ x hx, le_of_lt hx lemma Iio_subset_Iic_self : Iio a ⊆ Iic a := λ x hx, le_of_lt hx lemma Ico_subset_Ici_self : Ico a b ⊆ Ici a := λ x, and.left lemma Icc_subset_Icc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Icc a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_rfl, h₁⟩).1, (h ⟨h₁, le_rfl⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨h.trans hx, hx'.trans h'⟩⟩ lemma Icc_subset_Ioo_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ < a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_rfl, h₁⟩).1, (h ⟨h₁, le_rfl⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨h.trans_le hx, hx'.trans_lt h'⟩⟩ lemma Icc_subset_Ico_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_rfl, h₁⟩).1, (h ⟨h₁, le_rfl⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨h.trans hx, hx'.trans_lt h'⟩⟩ lemma Icc_subset_Ioc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ a₂ < a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_rfl, h₁⟩).1, (h ⟨h₁, le_rfl⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨h.trans_le hx, hx'.trans h'⟩⟩ lemma Icc_subset_Iio_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iio b₂ ↔ b₁ < b₂ := ⟨λ h, h ⟨h₁, le_rfl⟩, λ h x ⟨hx, hx'⟩, hx'.trans_lt h⟩ lemma Icc_subset_Ioi_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioi a₂ ↔ a₂ < a₁ := ⟨λ h, h ⟨le_rfl, h₁⟩, λ h x ⟨hx, hx'⟩, h.trans_le hx⟩ lemma Icc_subset_Iic_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iic b₂ ↔ b₁ ≤ b₂ := ⟨λ h, h ⟨h₁, le_rfl⟩, λ h x ⟨hx, hx'⟩, hx'.trans h⟩ lemma Icc_subset_Ici_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ici a₂ ↔ a₂ ≤ a₁ := ⟨λ h, h ⟨le_rfl, h₁⟩, λ h x ⟨hx, hx'⟩, h.trans hx⟩ lemma Icc_ssubset_Icc_left (hI : a₂ ≤ b₂) (ha : a₂ < a₁) (hb : b₁ ≤ b₂) : Icc a₁ b₁ ⊂ Icc a₂ b₂ := (ssubset_iff_of_subset (Icc_subset_Icc (le_of_lt ha) hb)).mpr ⟨a₂, left_mem_Icc.mpr hI, not_and.mpr (λ f g, lt_irrefl a₂ (ha.trans_le f))⟩ lemma Icc_ssubset_Icc_right (hI : a₂ ≤ b₂) (ha : a₂ ≤ a₁) (hb : b₁ < b₂) : Icc a₁ b₁ ⊂ Icc a₂ b₂ := (ssubset_iff_of_subset (Icc_subset_Icc ha (le_of_lt hb))).mpr ⟨b₂, right_mem_Icc.mpr hI, (λ f, lt_irrefl b₁ (hb.trans_le f.2))⟩ /-- If `a ≤ b`, then `(b, +∞) ⊆ (a, +∞)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Ioi_subset_Ioi_iff`. -/ lemma Ioi_subset_Ioi (h : a ≤ b) : Ioi b ⊆ Ioi a := λ x hx, h.trans_lt hx /-- If `a ≤ b`, then `(b, +∞) ⊆ [a, +∞)`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Ioi_subset_Ici_iff`. -/ lemma Ioi_subset_Ici (h : a ≤ b) : Ioi b ⊆ Ici a := subset.trans (Ioi_subset_Ioi h) Ioi_subset_Ici_self /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Iio_subset_Iio_iff`. -/ lemma Iio_subset_Iio (h : a ≤ b) : Iio a ⊆ Iio b := λ x hx, lt_of_lt_of_le hx h /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b]`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Iio_subset_Iic_iff`. -/ lemma Iio_subset_Iic (h : a ≤ b) : Iio a ⊆ Iic b := subset.trans (Iio_subset_Iio h) Iio_subset_Iic_self lemma Ici_inter_Iic : Ici a ∩ Iic b = Icc a b := rfl lemma Ici_inter_Iio : Ici a ∩ Iio b = Ico a b := rfl lemma Ioi_inter_Iic : Ioi a ∩ Iic b = Ioc a b := rfl lemma Ioi_inter_Iio : Ioi a ∩ Iio b = Ioo a b := rfl lemma mem_Icc_of_Ioo (h : x ∈ Ioo a b) : x ∈ Icc a b := Ioo_subset_Icc_self h lemma mem_Ico_of_Ioo (h : x ∈ Ioo a b) : x ∈ Ico a b := Ioo_subset_Ico_self h lemma mem_Ioc_of_Ioo (h : x ∈ Ioo a b) : x ∈ Ioc a b := Ioo_subset_Ioc_self h lemma mem_Icc_of_Ico (h : x ∈ Ico a b) : x ∈ Icc a b := Ico_subset_Icc_self h lemma mem_Icc_of_Ioc (h : x ∈ Ioc a b) : x ∈ Icc a b := Ioc_subset_Icc_self h lemma mem_Ici_of_Ioi (h : x ∈ Ioi a) : x ∈ Ici a := Ioi_subset_Ici_self h lemma mem_Iic_of_Iio (h : x ∈ Iio a) : x ∈ Iic a := Iio_subset_Iic_self h lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ ¬a ≤ b := by rw [←not_nonempty_iff_eq_empty, not_iff_not, nonempty_Icc] lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ ¬a < b := by rw [←not_nonempty_iff_eq_empty, not_iff_not, nonempty_Ico] lemma Ioc_eq_empty_iff : Ioc a b = ∅ ↔ ¬a < b := by rw [←not_nonempty_iff_eq_empty, not_iff_not, nonempty_Ioc] lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ ¬a < b := by rw [←not_nonempty_iff_eq_empty, not_iff_not, nonempty_Ioo] end intervals section partial_order variables {α : Type u} [partial_order α] {a b : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := set.ext $ by simp [Icc, le_antisymm_iff, and_comm] @[simp] lemma Icc_diff_left : Icc a b \ {a} = Ioc a b := ext $ λ x, by simp [lt_iff_le_and_ne, eq_comm, and.right_comm] @[simp] lemma Icc_diff_right : Icc a b \ {b} = Ico a b := ext $ λ x, by simp [lt_iff_le_and_ne, and_assoc] @[simp] lemma Ico_diff_left : Ico a b \ {a} = Ioo a b := ext $ λ x, by simp [and.right_comm, ← lt_iff_le_and_ne, eq_comm] @[simp] lemma Ioc_diff_right : Ioc a b \ {b} = Ioo a b := ext $ λ x, by simp [and_assoc, ← lt_iff_le_and_ne] @[simp] lemma Icc_diff_both : Icc a b \ {a, b} = Ioo a b := by rw [insert_eq, ← diff_diff, Icc_diff_left, Ioc_diff_right] @[simp] lemma Ici_diff_left : Ici a \ {a} = Ioi a := ext $ λ x, by simp [lt_iff_le_and_ne, eq_comm] @[simp] lemma Iic_diff_right : Iic a \ {a} = Iio a := ext $ λ x, by simp [lt_iff_le_and_ne] @[simp] lemma Ico_diff_Ioo_same (h : a < b) : Ico a b \ Ioo a b = {a} := by rw [← Ico_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 $ left_mem_Ico.2 h)] @[simp] lemma Ioc_diff_Ioo_same (h : a < b) : Ioc a b \ Ioo a b = {b} := by rw [← Ioc_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 $ right_mem_Ioc.2 h)] @[simp] lemma Icc_diff_Ico_same (h : a ≤ b) : Icc a b \ Ico a b = {b} := by rw [← Icc_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 $ right_mem_Icc.2 h)] @[simp] lemma Icc_diff_Ioc_same (h : a ≤ b) : Icc a b \ Ioc a b = {a} := by rw [← Icc_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 $ left_mem_Icc.2 h)] @[simp] lemma Icc_diff_Ioo_same (h : a ≤ b) : Icc a b \ Ioo a b = {a, b} := by { rw [← Icc_diff_both, diff_diff_cancel_left], simp [insert_subset, h] } @[simp] lemma Ici_diff_Ioi_same : Ici a \ Ioi a = {a} := by rw [← Ici_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 left_mem_Ici)] @[simp] lemma Iic_diff_Iio_same : Iic a \ Iio a = {a} := by rw [← Iic_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 right_mem_Iic)] @[simp] lemma Ioi_union_left : Ioi a ∪ {a} = Ici a := ext $ λ x, by simp [eq_comm, le_iff_eq_or_lt] @[simp] lemma Iio_union_right : Iio a ∪ {a} = Iic a := ext $ λ x, le_iff_lt_or_eq.symm lemma Ioo_union_left (hab : a < b) : Ioo a b ∪ {a} = Ico a b := by rw [← Ico_diff_left, diff_union_self, union_eq_self_of_subset_right (singleton_subset_iff.2 $ left_mem_Ico.2 hab)] lemma Ioo_union_right (hab : a < b) : Ioo a b ∪ {b} = Ioc a b := by simpa only [dual_Ioo, dual_Ico] using Ioo_union_left hab.dual lemma Ioc_union_left (hab : a ≤ b) : Ioc a b ∪ {a} = Icc a b := by rw [← Icc_diff_left, diff_union_self, union_eq_self_of_subset_right (singleton_subset_iff.2 $ left_mem_Icc.2 hab)] lemma Ico_union_right (hab : a ≤ b) : Ico a b ∪ {b} = Icc a b := by simpa only [dual_Ioc, dual_Icc] using Ioc_union_left hab.dual lemma mem_Ici_Ioi_of_subset_of_subset {s : set α} (ho : Ioi a ⊆ s) (hc : s ⊆ Ici a) : s ∈ ({Ici a, Ioi a} : set (set α)) := classical.by_cases (λ h : a ∈ s, or.inl $ subset.antisymm hc $ by rw [← Ioi_union_left, union_subset_iff]; simp *) (λ h, or.inr $ subset.antisymm (λ x hx, lt_of_le_of_ne (hc hx) (λ heq, h $ heq.symm ▸ hx)) ho) lemma mem_Iic_Iio_of_subset_of_subset {s : set α} (ho : Iio a ⊆ s) (hc : s ⊆ Iic a) : s ∈ ({Iic a, Iio a} : set (set α)) := @mem_Ici_Ioi_of_subset_of_subset (order_dual α) _ a s ho hc lemma mem_Icc_Ico_Ioc_Ioo_of_subset_of_subset {s : set α} (ho : Ioo a b ⊆ s) (hc : s ⊆ Icc a b) : s ∈ ({Icc a b, Ico a b, Ioc a b, Ioo a b} : set (set α)) := begin classical, by_cases ha : a ∈ s; by_cases hb : b ∈ s, { refine or.inl (subset.antisymm hc _), rwa [← Ico_diff_left, diff_singleton_subset_iff, insert_eq_of_mem ha, ← Icc_diff_right, diff_singleton_subset_iff, insert_eq_of_mem hb] at ho }, { refine (or.inr $ or.inl $ subset.antisymm _ _), { rw [← Icc_diff_right], exact subset_diff_singleton hc hb }, { rwa [← Ico_diff_left, diff_singleton_subset_iff, insert_eq_of_mem ha] at ho } }, { refine (or.inr $ or.inr $ or.inl $ subset.antisymm _ _), { rw [← Icc_diff_left], exact subset_diff_singleton hc ha }, { rwa [← Ioc_diff_right, diff_singleton_subset_iff, insert_eq_of_mem hb] at ho } }, { refine (or.inr $ or.inr $ or.inr $ subset.antisymm _ ho), rw [← Ico_diff_left, ← Icc_diff_right], apply_rules [subset_diff_singleton] } end lemma mem_Ioo_or_eq_endpoints_of_mem_Icc {x : α} (hmem : x ∈ Icc a b) : x = a ∨ x = b ∨ x ∈ Ioo a b := begin rw [mem_Icc, le_iff_lt_or_eq, le_iff_lt_or_eq] at hmem, rcases hmem with ⟨hxa | hxa, hxb | hxb⟩, { exact or.inr (or.inr ⟨hxa, hxb⟩) }, { exact or.inr (or.inl hxb) }, all_goals { exact or.inl hxa.symm } end lemma mem_Ioo_or_eq_left_of_mem_Ico {x : α} (hmem : x ∈ Ico a b) : x = a ∨ x ∈ Ioo a b := begin rw [mem_Ico, le_iff_lt_or_eq] at hmem, rcases hmem with ⟨hxa | hxa, hxb⟩, { exact or.inr ⟨hxa, hxb⟩ }, { exact or.inl hxa.symm } end lemma mem_Ioo_or_eq_right_of_mem_Ioc {x : α} (hmem : x ∈ Ioc a b) : x = b ∨ x ∈ Ioo a b := begin have := @mem_Ioo_or_eq_left_of_mem_Ico _ _ (to_dual b) (to_dual a) (to_dual x), rw [dual_Ioo, dual_Ico] at this, exact this hmem end lemma Ici_singleton_of_top {a : α} (h_top : ∀ x, x ≤ a) : Ici a = {a} := begin ext, exact ⟨λ h, (h_top _).antisymm h, λ h, h.ge⟩, end lemma Iic_singleton_of_bot {a : α} (h_bot : ∀ x, a ≤ x) : Iic a = {a} := @Ici_singleton_of_top (order_dual α) _ a h_bot end partial_order section order_top variables {α : Type u} [order_top α] {a : α} @[simp] lemma Ici_top : Ici (⊤ : α) = {⊤} := Ici_singleton_of_top (λ _, le_top) @[simp] lemma Iic_top : Iic (⊤ : α) = univ := eq_univ_of_forall $ λ x, le_top @[simp] lemma Icc_top : Icc a ⊤ = Ici a := by simp [← Ici_inter_Iic] @[simp] lemma Ioc_top : Ioc a ⊤ = Ioi a := by simp [← Ioi_inter_Iic] end order_top section order_bot variables {α : Type u} [order_bot α] {a : α} @[simp] lemma Iic_bot : Iic (⊥ : α) = {⊥} := Iic_singleton_of_bot (λ _, bot_le) @[simp] lemma Ici_bot : Ici (⊥ : α) = univ := @Iic_top (order_dual α) _ @[simp] lemma Icc_bot : Icc ⊥ a = Iic a := by simp [← Ici_inter_Iic] @[simp] lemma Ico_bot : Ico ⊥ a = Iio a := by simp [← Ici_inter_Iio] end order_bot section linear_order variables {α : Type u} [linear_order α] {a a₁ a₂ b b₁ b₂ c d : α} lemma not_mem_Ici : c ∉ Ici a ↔ c < a := not_le lemma not_mem_Iic : c ∉ Iic b ↔ b < c := not_le lemma not_mem_Icc_of_lt (ha : c < a) : c ∉ Icc a b := not_mem_subset Icc_subset_Ici_self $ not_mem_Ici.mpr ha lemma not_mem_Icc_of_gt (hb : b < c) : c ∉ Icc a b := not_mem_subset Icc_subset_Iic_self $ not_mem_Iic.mpr hb lemma not_mem_Ico_of_lt (ha : c < a) : c ∉ Ico a b := not_mem_subset Ico_subset_Ici_self $ not_mem_Ici.mpr ha lemma not_mem_Ioc_of_gt (hb : b < c) : c ∉ Ioc a b := not_mem_subset Ioc_subset_Iic_self $ not_mem_Iic.mpr hb lemma not_mem_Ioi : c ∉ Ioi a ↔ c ≤ a := not_lt lemma not_mem_Iio : c ∉ Iio b ↔ b ≤ c := not_lt lemma not_mem_Ioc_of_le (ha : c ≤ a) : c ∉ Ioc a b := not_mem_subset Ioc_subset_Ioi_self $ not_mem_Ioi.mpr ha lemma not_mem_Ico_of_ge (hb : b ≤ c) : c ∉ Ico a b := not_mem_subset Ico_subset_Iio_self $ not_mem_Iio.mpr hb lemma not_mem_Ioo_of_le (ha : c ≤ a) : c ∉ Ioo a b := not_mem_subset Ioo_subset_Ioi_self $ not_mem_Ioi.mpr ha lemma not_mem_Ioo_of_ge (hb : b ≤ c) : c ∉ Ioo a b := not_mem_subset Ioo_subset_Iio_self $ not_mem_Iio.mpr hb @[simp] lemma compl_Iic : (Iic a)ᶜ = Ioi a := ext $ λ _, not_le @[simp] lemma compl_Ici : (Ici a)ᶜ = Iio a := ext $ λ _, not_le @[simp] lemma compl_Iio : (Iio a)ᶜ = Ici a := ext $ λ _, not_lt @[simp] lemma compl_Ioi : (Ioi a)ᶜ = Iic a := ext $ λ _, not_lt @[simp] lemma Ici_diff_Ici : Ici a \ Ici b = Ico a b := by rw [diff_eq, compl_Ici, Ici_inter_Iio] @[simp] lemma Ici_diff_Ioi : Ici a \ Ioi b = Icc a b := by rw [diff_eq, compl_Ioi, Ici_inter_Iic] @[simp] lemma Ioi_diff_Ioi : Ioi a \ Ioi b = Ioc a b := by rw [diff_eq, compl_Ioi, Ioi_inter_Iic] @[simp] lemma Ioi_diff_Ici : Ioi a \ Ici b = Ioo a b := by rw [diff_eq, compl_Ici, Ioi_inter_Iio] @[simp] lemma Iic_diff_Iic : Iic b \ Iic a = Ioc a b := by rw [diff_eq, compl_Iic, inter_comm, Ioi_inter_Iic] @[simp] lemma Iio_diff_Iic : Iio b \ Iic a = Ioo a b := by rw [diff_eq, compl_Iic, inter_comm, Ioi_inter_Iio] @[simp] lemma Iic_diff_Iio : Iic b \ Iio a = Icc a b := by rw [diff_eq, compl_Iio, inter_comm, Ici_inter_Iic] @[simp] lemma Iio_diff_Iio : Iio b \ Iio a = Ico a b := by rw [diff_eq, compl_Iio, inter_comm, Ici_inter_Iio] lemma Ico_subset_Ico_iff (h₁ : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, have a₂ ≤ a₁ ∧ a₁ < b₂ := h ⟨le_rfl, h₁⟩, ⟨this.1, le_of_not_lt $ λ h', lt_irrefl b₂ (h ⟨this.2.le, h'⟩).2⟩, λ ⟨h₁, h₂⟩, Ico_subset_Ico h₁ h₂⟩ lemma Ioc_subset_Ioc_iff (h₁ : a₁ < b₁) : Ioc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ b₁ ≤ b₂ ∧ a₂ ≤ a₁ := by { convert @Ico_subset_Ico_iff (order_dual α) _ b₁ b₂ a₁ a₂ h₁; exact (@dual_Ico α _ _ _).symm } lemma Ioo_subset_Ioo_iff [densely_ordered α] (h₁ : a₁ < b₁) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, begin rcases exists_between h₁ with ⟨x, xa, xb⟩, split; refine le_of_not_lt (λ h', _), { have ab := (h ⟨xa, xb⟩).1.trans xb, exact lt_irrefl _ (h ⟨h', ab⟩).1 }, { have ab := xa.trans (h ⟨xa, xb⟩).2, exact lt_irrefl _ (h ⟨ab, h'⟩).2 } end, λ ⟨h₁, h₂⟩, Ioo_subset_Ioo h₁ h₂⟩ lemma Ico_eq_Ico_iff (h : a₁ < b₁ ∨ a₂ < b₂) : Ico a₁ b₁ = Ico a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ e, begin simp [subset.antisymm_iff] at e, simp [le_antisymm_iff], cases h; simp [Ico_subset_Ico_iff h] at e; [ rcases e with ⟨⟨h₁, h₂⟩, e'⟩, rcases e with ⟨e', ⟨h₁, h₂⟩⟩ ]; have := (Ico_subset_Ico_iff $ h₁.trans_lt $ h.trans_le h₂).1 e'; tauto end, λ ⟨h₁, h₂⟩, by rw [h₁, h₂]⟩ open_locale classical @[simp] lemma Ioi_subset_Ioi_iff : Ioi b ⊆ Ioi a ↔ a ≤ b := begin refine ⟨λ h, _, λ h, Ioi_subset_Ioi h⟩, by_contradiction ba, exact lt_irrefl _ (h (not_le.mp ba)) end @[simp] lemma Ioi_subset_Ici_iff [densely_ordered α] : Ioi b ⊆ Ici a ↔ a ≤ b := begin refine ⟨λ h, _, λ h, Ioi_subset_Ici h⟩, by_contradiction ba, obtain ⟨c, bc, ca⟩ : ∃c, b < c ∧ c < a := exists_between (not_le.mp ba), exact lt_irrefl _ (ca.trans_le (h bc)) end @[simp] lemma Iio_subset_Iio_iff : Iio a ⊆ Iio b ↔ a ≤ b := begin refine ⟨λ h, _, λ h, Iio_subset_Iio h⟩, by_contradiction ab, exact lt_irrefl _ (h (not_le.mp ab)) end @[simp] lemma Iio_subset_Iic_iff [densely_ordered α] : Iio a ⊆ Iic b ↔ a ≤ b := by rw [←diff_eq_empty, Iio_diff_Iic, Ioo_eq_empty_iff, not_lt] /-! ### Unions of adjacent intervals -/ /-! #### Two infinite intervals -/ @[simp] lemma Iic_union_Ici : Iic a ∪ Ici a = univ := eq_univ_of_forall (λ x, le_total x a) @[simp] lemma Iio_union_Ici : Iio a ∪ Ici a = univ := eq_univ_of_forall (λ x, lt_or_le x a) @[simp] lemma Iic_union_Ioi : Iic a ∪ Ioi a = univ := eq_univ_of_forall (λ x, le_or_lt x a) /-! #### A finite and an infinite interval -/ lemma Ioo_union_Ioi' (h₁ : c < b) : Ioo a b ∪ Ioi c = Ioi (min a c) := begin ext1 x, simp_rw [mem_union, mem_Ioo, mem_Ioi, min_lt_iff], by_cases hc : c < x, { tauto }, { have hxb : x < b := (le_of_not_gt hc).trans_lt h₁, tauto }, end lemma Ioo_union_Ioi (h : c < max a b) : Ioo a b ∪ Ioi c = Ioi (min a c) := begin cases le_total a b with hab hab; simp [hab] at h, { exact Ioo_union_Ioi' h }, { rw min_comm, simp [*, min_eq_left_of_lt] }, end lemma Ioi_subset_Ioo_union_Ici : Ioi a ⊆ Ioo a b ∪ Ici b := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ioo_union_Ici_eq_Ioi (h : a < b) : Ioo a b ∪ Ici b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left h.trans_le) Ioi_subset_Ioo_union_Ici lemma Ici_subset_Ico_union_Ici : Ici a ⊆ Ico a b ∪ Ici b := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ico_union_Ici_eq_Ici (h : a ≤ b) : Ico a b ∪ Ici b = Ici a := subset.antisymm (λ x hx, hx.elim and.left h.trans) Ici_subset_Ico_union_Ici lemma Ico_union_Ici' (h₁ : c ≤ b) : Ico a b ∪ Ici c = Ici (min a c) := begin ext1 x, simp_rw [mem_union, mem_Ico, mem_Ici, min_le_iff], by_cases hc : c ≤ x, { tauto }, { have hxb : x < b := (lt_of_not_ge hc).trans_le h₁, tauto }, end lemma Ico_union_Ici (h : c ≤ max a b) : Ico a b ∪ Ici c = Ici (min a c) := begin cases le_total a b with hab hab; simp [hab] at h, { exact Ico_union_Ici' h }, { simp [*] }, end lemma Ioi_subset_Ioc_union_Ioi : Ioi a ⊆ Ioc a b ∪ Ioi b := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ioc_union_Ioi_eq_Ioi (h : a ≤ b) : Ioc a b ∪ Ioi b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left h.trans_lt) Ioi_subset_Ioc_union_Ioi lemma Ioc_union_Ioi' (h₁ : c ≤ b) : Ioc a b ∪ Ioi c = Ioi (min a c) := begin ext1 x, simp_rw [mem_union, mem_Ioc, mem_Ioi, min_lt_iff], by_cases hc : c < x, { tauto }, { have hxb : x ≤ b := (le_of_not_gt hc).trans h₁, tauto }, end lemma Ioc_union_Ioi (h : c ≤ max a b) : Ioc a b ∪ Ioi c = Ioi (min a c) := begin cases le_total a b with hab hab; simp [hab] at h, { exact Ioc_union_Ioi' h }, { simp [*] }, end lemma Ici_subset_Icc_union_Ioi : Ici a ⊆ Icc a b ∪ Ioi b := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Icc_union_Ioi_eq_Ici (h : a ≤ b) : Icc a b ∪ Ioi b = Ici a := subset.antisymm (λ x hx, hx.elim and.left $ λ hx', h.trans $ le_of_lt hx') Ici_subset_Icc_union_Ioi lemma Ioi_subset_Ioc_union_Ici : Ioi a ⊆ Ioc a b ∪ Ici b := subset.trans Ioi_subset_Ioo_union_Ici (union_subset_union_left _ Ioo_subset_Ioc_self) @[simp] lemma Ioc_union_Ici_eq_Ioi (h : a < b) : Ioc a b ∪ Ici b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left h.trans_le) Ioi_subset_Ioc_union_Ici lemma Ici_subset_Icc_union_Ici : Ici a ⊆ Icc a b ∪ Ici b := subset.trans Ici_subset_Ico_union_Ici (union_subset_union_left _ Ico_subset_Icc_self) @[simp] lemma Icc_union_Ici_eq_Ici (h : a ≤ b) : Icc a b ∪ Ici b = Ici a := subset.antisymm (λ x hx, hx.elim and.left h.trans) Ici_subset_Icc_union_Ici lemma Icc_union_Ici' (h₁ : c ≤ b) : Icc a b ∪ Ici c = Ici (min a c) := begin ext1 x, simp_rw [mem_union, mem_Icc, mem_Ici, min_le_iff], by_cases hc : c ≤ x, { tauto }, { have hxb : x ≤ b := (le_of_not_ge hc).trans h₁, tauto }, end lemma Icc_union_Ici (h : c ≤ max a b) : Icc a b ∪ Ici c = Ici (min a c) := begin cases le_or_lt a b with hab hab; simp [hab] at h, { exact Icc_union_Ici' h }, { cases h, { simp [*] }, { have hca : c ≤ a := h.trans hab.le, simp [*] } }, end /-! #### An infinite and a finite interval -/ lemma Iic_subset_Iio_union_Icc : Iic b ⊆ Iio a ∪ Icc a b := λ x hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iio_union_Icc_eq_Iic (h : a ≤ b) : Iio a ∪ Icc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx, (le_of_lt hx).trans h) and.right) Iic_subset_Iio_union_Icc lemma Iio_subset_Iio_union_Ico : Iio b ⊆ Iio a ∪ Ico a b := λ x hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iio_union_Ico_eq_Iio (h : a ≤ b) : Iio a ∪ Ico a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx', lt_of_lt_of_le hx' h) and.right) Iio_subset_Iio_union_Ico lemma Iio_union_Ico' (h₁ : c ≤ b) : Iio b ∪ Ico c d = Iio (max b d) := begin ext1 x, simp_rw [mem_union, mem_Iio, mem_Ico, lt_max_iff], by_cases hc : c ≤ x, { tauto }, { have hxb : x < b := (lt_of_not_ge hc).trans_le h₁, tauto }, end lemma Iio_union_Ico (h : min c d ≤ b) : Iio b ∪ Ico c d = Iio (max b d) := begin cases le_total c d with hcd hcd; simp [hcd] at h, { exact Iio_union_Ico' h }, { simp [*] }, end lemma Iic_subset_Iic_union_Ioc : Iic b ⊆ Iic a ∪ Ioc a b := λ x hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iic_union_Ioc_eq_Iic (h : a ≤ b) : Iic a ∪ Ioc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx', le_trans hx' h) and.right) Iic_subset_Iic_union_Ioc lemma Iic_union_Ioc' (h₁ : c < b) : Iic b ∪ Ioc c d = Iic (max b d) := begin ext1 x, simp_rw [mem_union, mem_Iic, mem_Ioc, le_max_iff], by_cases hc : c < x, { tauto }, { have hxb : x ≤ b := (le_of_not_gt hc).trans h₁.le, tauto }, end lemma Iic_union_Ioc (h : min c d < b) : Iic b ∪ Ioc c d = Iic (max b d) := begin cases le_total c d with hcd hcd; simp [hcd] at h, { exact Iic_union_Ioc' h }, { rw max_comm, simp [*, max_eq_right_of_lt h] }, end lemma Iio_subset_Iic_union_Ioo : Iio b ⊆ Iic a ∪ Ioo a b := λ x hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iic_union_Ioo_eq_Iio (h : a < b) : Iic a ∪ Ioo a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx', lt_of_le_of_lt hx' h) and.right) Iio_subset_Iic_union_Ioo lemma Iio_union_Ioo' (h₁ : c < b) : Iio b ∪ Ioo c d = Iio (max b d) := begin ext x, cases lt_or_le x b with hba hba, { simp [hba, h₁] }, { simp only [mem_Iio, mem_union_eq, mem_Ioo, lt_max_iff], refine or_congr iff.rfl ⟨and.right, _⟩, exact λ h₂, ⟨h₁.trans_le hba, h₂⟩ }, end lemma Iio_union_Ioo (h : min c d < b) : Iio b ∪ Ioo c d = Iio (max b d) := begin cases le_total c d with hcd hcd; simp [hcd] at h, { exact Iio_union_Ioo' h }, { rw max_comm, simp [*, max_eq_right_of_lt h] }, end lemma Iic_subset_Iic_union_Icc : Iic b ⊆ Iic a ∪ Icc a b := subset.trans Iic_subset_Iic_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Iic_union_Icc_eq_Iic (h : a ≤ b) : Iic a ∪ Icc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx', le_trans hx' h) and.right) Iic_subset_Iic_union_Icc lemma Iic_union_Icc' (h₁ : c ≤ b) : Iic b ∪ Icc c d = Iic (max b d) := begin ext1 x, simp_rw [mem_union, mem_Iic, mem_Icc, le_max_iff], by_cases hc : c ≤ x, { tauto }, { have hxb : x ≤ b := (le_of_not_ge hc).trans h₁, tauto }, end lemma Iic_union_Icc (h : min c d ≤ b) : Iic b ∪ Icc c d = Iic (max b d) := begin cases le_or_lt c d with hcd hcd; simp [hcd] at h, { exact Iic_union_Icc' h }, { cases h, { have hdb : d ≤ b := hcd.le.trans h, simp [*] }, { simp [*] } }, end lemma Iio_subset_Iic_union_Ico : Iio b ⊆ Iic a ∪ Ico a b := subset.trans Iio_subset_Iic_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Iic_union_Ico_eq_Iio (h : a < b) : Iic a ∪ Ico a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx', lt_of_le_of_lt hx' h) and.right) Iio_subset_Iic_union_Ico /-! #### Two finite intervals, `I?o` and `Ic?` -/ lemma Ioo_subset_Ioo_union_Ico : Ioo a c ⊆ Ioo a b ∪ Ico b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioo_union_Ico_eq_Ioo (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Ico b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans_le h₂⟩) (λ hx, ⟨h₁.trans_le hx.1, hx.2⟩)) Ioo_subset_Ioo_union_Ico lemma Ico_subset_Ico_union_Ico : Ico a c ⊆ Ico a b ∪ Ico b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ico_union_Ico_eq_Ico (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Ico b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans_le h₂⟩) (λ hx, ⟨h₁.trans hx.1, hx.2⟩)) Ico_subset_Ico_union_Ico lemma Ico_union_Ico' (h₁ : c ≤ b) (h₂ : a ≤ d) : Ico a b ∪ Ico c d = Ico (min a c) (max b d) := begin ext1 x, simp_rw [mem_union, mem_Ico, min_le_iff, lt_max_iff], by_cases hc : c ≤ x; by_cases hd : x < d, { tauto }, { have hax : a ≤ x := h₂.trans (le_of_not_gt hd), tauto }, { have hxb : x < b := (lt_of_not_ge hc).trans_le h₁, tauto }, { tauto }, end lemma Ico_union_Ico (h₁ : min a b ≤ max c d) (h₂ : min c d ≤ max a b) : Ico a b ∪ Ico c d = Ico (min a c) (max b d) := begin cases le_total a b with hab hab; cases le_total c d with hcd hcd; simp [hab, hcd] at h₁ h₂, { exact Ico_union_Ico' h₂ h₁ }, all_goals { simp [*] }, end lemma Icc_subset_Ico_union_Icc : Icc a c ⊆ Ico a b ∪ Icc b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ico_union_Icc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Icc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.le.trans h₂⟩) (λ hx, ⟨h₁.trans hx.1, hx.2⟩)) Icc_subset_Ico_union_Icc lemma Ioc_subset_Ioo_union_Icc : Ioc a c ⊆ Ioo a b ∪ Icc b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioo_union_Icc_eq_Ioc (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Icc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.le.trans h₂⟩) (λ hx, ⟨h₁.trans_le hx.1, hx.2⟩)) Ioc_subset_Ioo_union_Icc /-! #### Two finite intervals, `I?c` and `Io?` -/ lemma Ioo_subset_Ioc_union_Ioo : Ioo a c ⊆ Ioc a b ∪ Ioo b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioc_union_Ioo_eq_Ioo (h₁ : a ≤ b) (h₂ : b < c) : Ioc a b ∪ Ioo b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans_lt h₂⟩) (λ hx, ⟨h₁.trans_lt hx.1, hx.2⟩)) Ioo_subset_Ioc_union_Ioo lemma Ico_subset_Icc_union_Ioo : Ico a c ⊆ Icc a b ∪ Ioo b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Icc_union_Ioo_eq_Ico (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ioo b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans_lt h₂⟩) (λ hx, ⟨h₁.trans hx.1.le, hx.2⟩)) Ico_subset_Icc_union_Ioo lemma Icc_subset_Icc_union_Ioc : Icc a c ⊆ Icc a b ∪ Ioc b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Icc_union_Ioc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Ioc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans h₂⟩) (λ hx, ⟨h₁.trans hx.1.le, hx.2⟩)) Icc_subset_Icc_union_Ioc lemma Ioc_subset_Ioc_union_Ioc : Ioc a c ⊆ Ioc a b ∪ Ioc b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioc_union_Ioc_eq_Ioc (h₁ : a ≤ b) (h₂ : b ≤ c) : Ioc a b ∪ Ioc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans h₂⟩) (λ hx, ⟨h₁.trans_lt hx.1, hx.2⟩)) Ioc_subset_Ioc_union_Ioc lemma Ioc_union_Ioc' (h₁ : c ≤ b) (h₂ : a ≤ d) : Ioc a b ∪ Ioc c d = Ioc (min a c) (max b d) := begin ext1 x, simp_rw [mem_union, mem_Ioc, min_lt_iff, le_max_iff], by_cases hc : c < x; by_cases hd : x ≤ d, { tauto }, { have hax : a < x := h₂.trans_lt (lt_of_not_ge hd), tauto }, { have hxb : x ≤ b := (le_of_not_gt hc).trans h₁, tauto }, { tauto }, end lemma Ioc_union_Ioc (h₁ : min a b ≤ max c d) (h₂ : min c d ≤ max a b) : Ioc a b ∪ Ioc c d = Ioc (min a c) (max b d) := begin cases le_total a b with hab hab; cases le_total c d with hcd hcd; simp [hab, hcd] at h₁ h₂, { exact Ioc_union_Ioc' h₂ h₁ }, all_goals { simp [*] }, end /-! #### Two finite intervals with a common point -/ lemma Ioo_subset_Ioc_union_Ico : Ioo a c ⊆ Ioc a b ∪ Ico b c := subset.trans Ioo_subset_Ioc_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Ioc_union_Ico_eq_Ioo (h₁ : a < b) (h₂ : b < c) : Ioc a b ∪ Ico b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx', ⟨hx'.1, hx'.2.trans_lt h₂⟩) (λ hx', ⟨h₁.trans_le hx'.1, hx'.2⟩)) Ioo_subset_Ioc_union_Ico lemma Ico_subset_Icc_union_Ico : Ico a c ⊆ Icc a b ∪ Ico b c := subset.trans Ico_subset_Icc_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Icc_union_Ico_eq_Ico (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ico b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans_lt h₂⟩) (λ hx, ⟨h₁.trans hx.1, hx.2⟩)) Ico_subset_Icc_union_Ico lemma Icc_subset_Icc_union_Icc : Icc a c ⊆ Icc a b ∪ Icc b c := subset.trans Icc_subset_Icc_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Icc_union_Icc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Icc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans h₂⟩) (λ hx, ⟨h₁.trans hx.1, hx.2⟩)) Icc_subset_Icc_union_Icc lemma Icc_union_Icc' (h₁ : c ≤ b) (h₂ : a ≤ d) : Icc a b ∪ Icc c d = Icc (min a c) (max b d) := begin ext1 x, simp_rw [mem_union, mem_Icc, min_le_iff, le_max_iff], by_cases hc : c ≤ x; by_cases hd : x ≤ d, { tauto }, { have hax : a ≤ x := h₂.trans (le_of_not_ge hd), tauto }, { have hxb : x ≤ b := (le_of_not_ge hc).trans h₁, tauto }, { tauto } end /-- We cannot replace `<` by `≤` in the hypotheses. Otherwise for `b < a = d < c` the l.h.s. is `∅` and the r.h.s. is `{a}`. -/ lemma Icc_union_Icc (h₁ : min a b < max c d) (h₂ : min c d < max a b) : Icc a b ∪ Icc c d = Icc (min a c) (max b d) := begin cases le_or_lt a b with hab hab; cases le_or_lt c d with hcd hcd; simp only [min_eq_left, min_eq_right, max_eq_left, max_eq_right, min_eq_left_of_lt, min_eq_right_of_lt, max_eq_left_of_lt, max_eq_right_of_lt, hab, hcd] at h₁ h₂, { exact Icc_union_Icc' h₂.le h₁.le }, all_goals { simp [*, min_eq_left_of_lt, max_eq_left_of_lt, min_eq_right_of_lt, max_eq_right_of_lt] }, end lemma Ioc_subset_Ioc_union_Icc : Ioc a c ⊆ Ioc a b ∪ Icc b c := subset.trans Ioc_subset_Ioc_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Ioc_union_Icc_eq_Ioc (h₁ : a < b) (h₂ : b ≤ c) : Ioc a b ∪ Icc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans h₂⟩) (λ hx, ⟨h₁.trans_le hx.1, hx.2⟩)) Ioc_subset_Ioc_union_Icc lemma Ioo_union_Ioo' (h₁ : c < b) (h₂ : a < d) : Ioo a b ∪ Ioo c d = Ioo (min a c) (max b d) := begin ext1 x, simp_rw [mem_union, mem_Ioo, min_lt_iff, lt_max_iff], by_cases hc : c < x; by_cases hd : x < d, { tauto }, { have hax : a < x := h₂.trans_le (le_of_not_lt hd), tauto }, { have hxb : x < b := (le_of_not_lt hc).trans_lt h₁, tauto }, { tauto } end lemma Ioo_union_Ioo (h₁ : min a b < max c d) (h₂ : min c d < max a b) : Ioo a b ∪ Ioo c d = Ioo (min a c) (max b d) := begin cases le_total a b with hab hab; cases le_total c d with hcd hcd; simp only [min_eq_left, min_eq_right, max_eq_left, max_eq_right, hab, hcd] at h₁ h₂, { exact Ioo_union_Ioo' h₂ h₁ }, all_goals { simp [*, min_eq_left_of_lt, min_eq_right_of_lt, max_eq_left_of_lt, max_eq_right_of_lt, le_of_lt h₂, le_of_lt h₁] }, end end linear_order section lattice section inf variables {α : Type u} [semilattice_inf α] @[simp] lemma Iic_inter_Iic {a b : α} : Iic a ∩ Iic b = Iic (a ⊓ b) := by { ext x, simp [Iic] } @[simp] lemma Iio_inter_Iio [is_total α (≤)] {a b : α} : Iio a ∩ Iio b = Iio (a ⊓ b) := by { ext x, simp [Iio] } end inf section sup variables {α : Type u} [semilattice_sup α] @[simp] lemma Ici_inter_Ici {a b : α} : Ici a ∩ Ici b = Ici (a ⊔ b) := by { ext x, simp [Ici] } @[simp] lemma Ioi_inter_Ioi [is_total α (≤)] {a b : α} : Ioi a ∩ Ioi b = Ioi (a ⊔ b) := by { ext x, simp [Ioi] } @[simp] lemma Ioc_inter_Ioi [is_total α (≤)] {a b c : α} : Ioc a b ∩ Ioi c = Ioc (a ⊔ c) b := by rw [← Ioi_inter_Iic, inter_assoc, inter_comm, inter_assoc, Ioi_inter_Ioi, inter_comm, Ioi_inter_Iic, sup_comm] end sup section both variables {α : Type u} [lattice α] [ht : is_total α (≤)] {a b c a₁ a₂ b₁ b₂ : α} lemma Icc_inter_Icc : Icc a₁ b₁ ∩ Icc a₂ b₂ = Icc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iic.symm, Ici_inter_Ici.symm, Iic_inter_Iic.symm]; ac_refl @[simp] lemma Icc_inter_Icc_eq_singleton (hab : a ≤ b) (hbc : b ≤ c) : Icc a b ∩ Icc b c = {b} := by rw [Icc_inter_Icc, sup_of_le_right hab, inf_of_le_left hbc, Icc_self] include ht lemma Ico_inter_Ico : Ico a₁ b₁ ∩ Ico a₂ b₂ = Ico (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iio.symm, Ici_inter_Ici.symm, Iio_inter_Iio.symm]; ac_refl lemma Ioc_inter_Ioc : Ioc a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iic.symm, Ioi_inter_Ioi.symm, Iic_inter_Iic.symm]; ac_refl lemma Ioo_inter_Ioo : Ioo a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iio.symm, Ioi_inter_Ioi.symm, Iio_inter_Iio.symm]; ac_refl end both lemma Icc_bot_top {α} [bounded_lattice α] : Icc (⊥ : α) ⊤ = univ := by simp end lattice section linear_order variables {α : Type u} [linear_order α] {a a₁ a₂ b b₁ b₂ c d : α} lemma Ioc_inter_Ioo_of_left_lt (h : b₁ < b₂) : Ioc a₁ b₁ ∩ Ioo a₂ b₂ = Ioc (max a₁ a₂) b₁ := ext $ λ x, by simp [and_assoc, @and.left_comm (x ≤ _), and_iff_left_iff_imp.2 (λ h', lt_of_le_of_lt h' h)] lemma Ioc_inter_Ioo_of_right_le (h : b₂ ≤ b₁) : Ioc a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (max a₁ a₂) b₂ := ext $ λ x, by simp [and_assoc, @and.left_comm (x ≤ _), and_iff_right_iff_imp.2 (λ h', ((le_of_lt h').trans h))] lemma Ioo_inter_Ioc_of_left_le (h : b₁ ≤ b₂) : Ioo a₁ b₁ ∩ Ioc a₂ b₂ = Ioo (max a₁ a₂) b₁ := by rw [inter_comm, Ioc_inter_Ioo_of_right_le h, max_comm] lemma Ioo_inter_Ioc_of_right_lt (h : b₂ < b₁) : Ioo a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (max a₁ a₂) b₂ := by rw [inter_comm, Ioc_inter_Ioo_of_left_lt h, max_comm] lemma Iic_inter_Ioc_of_le (h : a₂ ≤ a) : Iic a₂ ∩ Ioc a₁ a = Ioc a₁ a₂ := ext $ λ x, ⟨λ H, ⟨H.2.1, H.1⟩, λ H, ⟨H.2, H.1, H.2.trans h⟩⟩ @[simp] lemma Ico_diff_Iio : Ico a b \ Iio c = Ico (max a c) b := ext $ by simp [iff_def] {contextual:=tt} @[simp] lemma Ioc_diff_Ioi : Ioc a b \ Ioi c = Ioc a (min b c) := ext $ by simp [iff_def] {contextual:=tt} @[simp] lemma Ico_inter_Iio : Ico a b ∩ Iio c = Ico a (min b c) := ext $ by simp [iff_def] {contextual:=tt} @[simp] lemma Ioc_union_Ioc_right : Ioc a b ∪ Ioc a c = Ioc a (max b c) := by rw [Ioc_union_Ioc, min_self]; exact (min_le_left _ _).trans (le_max_left _ _) @[simp] lemma Ioc_union_Ioc_left : Ioc a c ∪ Ioc b c = Ioc (min a b) c := by rw [Ioc_union_Ioc, max_self]; exact (min_le_right _ _).trans (le_max_right _ _) @[simp] lemma Ioc_union_Ioc_symm : Ioc a b ∪ Ioc b a = Ioc (min a b) (max a b) := by { rw max_comm, apply Ioc_union_Ioc; rw max_comm; exact min_le_max } @[simp] lemma Ioc_union_Ioc_union_Ioc_cycle : Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc (min a (min b c)) (max a (max b c)) := begin rw [Ioc_union_Ioc, Ioc_union_Ioc], ac_refl, all_goals { solve_by_elim [min_le_of_left_le, min_le_of_right_le, le_max_of_le_left, le_max_of_le_right, le_refl] { max_depth := 5 }} end end linear_order /-! ### Lemmas about membership of arithmetic operations -/ section ordered_comm_group variables {α : Type*} [ordered_comm_group α] {a b c d : α} /-! `inv_mem_Ixx_iff`, `sub_mem_Ixx_iff` -/ @[to_additive] lemma inv_mem_Icc_iff : a⁻¹ ∈ set.Icc c d ↔ a ∈ set.Icc (d⁻¹) (c⁻¹) := (and_comm _ _).trans $ and_congr inv_le' le_inv' @[to_additive] lemma inv_mem_Ico_iff : a⁻¹ ∈ set.Ico c d ↔ a ∈ set.Ioc (d⁻¹) (c⁻¹) := (and_comm _ _).trans $ and_congr inv_lt' le_inv' @[to_additive] lemma inv_mem_Ioc_iff : a⁻¹ ∈ set.Ioc c d ↔ a ∈ set.Ico (d⁻¹) (c⁻¹) := (and_comm _ _).trans $ and_congr inv_le' lt_inv' @[to_additive] lemma inv_mem_Ioo_iff : a⁻¹ ∈ set.Ioo c d ↔ a ∈ set.Ioo (d⁻¹) (c⁻¹) := (and_comm _ _).trans $ and_congr inv_lt' lt_inv' end ordered_comm_group section ordered_add_comm_group variables {α : Type*} [ordered_add_comm_group α] {a b c d : α} /-! `add_mem_Ixx_iff_left` -/ lemma add_mem_Icc_iff_left : a + b ∈ set.Icc c d ↔ a ∈ set.Icc (c - b) (d - b) := (and_congr sub_le_iff_le_add le_sub_iff_add_le).symm lemma add_mem_Ico_iff_left : a + b ∈ set.Ico c d ↔ a ∈ set.Ico (c - b) (d - b) := (and_congr sub_le_iff_le_add lt_sub_iff_add_lt).symm lemma add_mem_Ioc_iff_left : a + b ∈ set.Ioc c d ↔ a ∈ set.Ioc (c - b) (d - b) := (and_congr sub_lt_iff_lt_add le_sub_iff_add_le).symm lemma add_mem_Ioo_iff_left : a + b ∈ set.Ioo c d ↔ a ∈ set.Ioo (c - b) (d - b) := (and_congr sub_lt_iff_lt_add lt_sub_iff_add_lt).symm /-! `add_mem_Ixx_iff_right` -/ lemma add_mem_Icc_iff_right : a + b ∈ set.Icc c d ↔ b ∈ set.Icc (c - a) (d - a) := (and_congr sub_le_iff_le_add' le_sub_iff_add_le').symm lemma add_mem_Ico_iff_right : a + b ∈ set.Ico c d ↔ b ∈ set.Ico (c - a) (d - a) := (and_congr sub_le_iff_le_add' lt_sub_iff_add_lt').symm lemma add_mem_Ioc_iff_right : a + b ∈ set.Ioc c d ↔ b ∈ set.Ioc (c - a) (d - a) := (and_congr sub_lt_iff_lt_add' le_sub_iff_add_le').symm lemma add_mem_Ioo_iff_right : a + b ∈ set.Ioo c d ↔ b ∈ set.Ioo (c - a) (d - a) := (and_congr sub_lt_iff_lt_add' lt_sub_iff_add_lt').symm /-! `sub_mem_Ixx_iff_left` -/ lemma sub_mem_Icc_iff_left : a - b ∈ set.Icc c d ↔ a ∈ set.Icc (c + b) (d + b) := and_congr le_sub_iff_add_le sub_le_iff_le_add lemma sub_mem_Ico_iff_left : a - b ∈ set.Ico c d ↔ a ∈ set.Ico (c + b) (d + b) := and_congr le_sub_iff_add_le sub_lt_iff_lt_add lemma sub_mem_Ioc_iff_left : a - b ∈ set.Ioc c d ↔ a ∈ set.Ioc (c + b) (d + b) := and_congr lt_sub_iff_add_lt sub_le_iff_le_add lemma sub_mem_Ioo_iff_left : a - b ∈ set.Ioo c d ↔ a ∈ set.Ioo (c + b) (d + b) := and_congr lt_sub_iff_add_lt sub_lt_iff_lt_add /-! `sub_mem_Ixx_iff_right` -/ lemma sub_mem_Icc_iff_right : a - b ∈ set.Icc c d ↔ b ∈ set.Icc (a - d) (a - c) := (and_comm _ _).trans $ and_congr sub_le le_sub lemma sub_mem_Ico_iff_right : a - b ∈ set.Ico c d ↔ b ∈ set.Ioc (a - d) (a - c) := (and_comm _ _).trans $ and_congr sub_lt le_sub lemma sub_mem_Ioc_iff_right : a - b ∈ set.Ioc c d ↔ b ∈ set.Ico (a - d) (a - c) := (and_comm _ _).trans $ and_congr sub_le lt_sub lemma sub_mem_Ioo_iff_right : a - b ∈ set.Ioo c d ↔ b ∈ set.Ioo (a - d) (a - c) := (and_comm _ _).trans $ and_congr sub_lt lt_sub -- I think that symmetric intervals deserve attention and API: they arise all the time, -- for instance when considering metric balls in `ℝ`. lemma mem_Icc_iff_abs_le {R : Type*} [linear_ordered_add_comm_group R] {x y z : R} : |x - y| ≤ z ↔ y ∈ Icc (x - z) (x + z) := abs_le.trans $ (and_comm _ _).trans $ and_congr sub_le neg_le_sub_iff_le_add end ordered_add_comm_group section linear_ordered_add_comm_group variables {α : Type u} [linear_ordered_add_comm_group α] /-- If we remove a smaller interval from a larger, the result is nonempty -/ lemma nonempty_Ico_sdiff {x dx y dy : α} (h : dy < dx) (hx : 0 < dx) : nonempty ↥(Ico x (x + dx) \ Ico y (y + dy)) := begin cases lt_or_le x y with h' h', { use x, simp [*, not_le.2 h'] }, { use max x (x + dy), simp [*, le_refl] } end end linear_ordered_add_comm_group end set namespace order_iso variables {α β : Type*} open set section preorder variables [preorder α] [preorder β] @[simp] lemma preimage_Iic (e : α ≃o β) (b : β) : e ⁻¹' (Iic b) = Iic (e.symm b) := by { ext x, simp [← e.le_iff_le] } @[simp] lemma preimage_Ici (e : α ≃o β) (b : β) : e ⁻¹' (Ici b) = Ici (e.symm b) := by { ext x, simp [← e.le_iff_le] } @[simp] lemma preimage_Iio (e : α ≃o β) (b : β) : e ⁻¹' (Iio b) = Iio (e.symm b) := by { ext x, simp [← e.lt_iff_lt] } @[simp] lemma preimage_Ioi (e : α ≃o β) (b : β) : e ⁻¹' (Ioi b) = Ioi (e.symm b) := by { ext x, simp [← e.lt_iff_lt] } @[simp] lemma preimage_Icc (e : α ≃o β) (a b : β) : e ⁻¹' (Icc a b) = Icc (e.symm a) (e.symm b) := by simp [← Ici_inter_Iic] @[simp] lemma preimage_Ico (e : α ≃o β) (a b : β) : e ⁻¹' (Ico a b) = Ico (e.symm a) (e.symm b) := by simp [← Ici_inter_Iio] @[simp] lemma preimage_Ioc (e : α ≃o β) (a b : β) : e ⁻¹' (Ioc a b) = Ioc (e.symm a) (e.symm b) := by simp [← Ioi_inter_Iic] @[simp] lemma preimage_Ioo (e : α ≃o β) (a b : β) : e ⁻¹' (Ioo a b) = Ioo (e.symm a) (e.symm b) := by simp [← Ioi_inter_Iio] @[simp] lemma image_Iic (e : α ≃o β) (a : α) : e '' (Iic a) = Iic (e a) := by rw [e.image_eq_preimage, e.symm.preimage_Iic, e.symm_symm] @[simp] lemma image_Ici (e : α ≃o β) (a : α) : e '' (Ici a) = Ici (e a) := e.dual.image_Iic a @[simp] lemma image_Iio (e : α ≃o β) (a : α) : e '' (Iio a) = Iio (e a) := by rw [e.image_eq_preimage, e.symm.preimage_Iio, e.symm_symm] @[simp] lemma image_Ioi (e : α ≃o β) (a : α) : e '' (Ioi a) = Ioi (e a) := e.dual.image_Iio a @[simp] lemma image_Ioo (e : α ≃o β) (a b : α) : e '' (Ioo a b) = Ioo (e a) (e b) := by rw [e.image_eq_preimage, e.symm.preimage_Ioo, e.symm_symm] @[simp] lemma image_Ioc (e : α ≃o β) (a b : α) : e '' (Ioc a b) = Ioc (e a) (e b) := by rw [e.image_eq_preimage, e.symm.preimage_Ioc, e.symm_symm] @[simp] lemma image_Ico (e : α ≃o β) (a b : α) : e '' (Ico a b) = Ico (e a) (e b) := by rw [e.image_eq_preimage, e.symm.preimage_Ico, e.symm_symm] @[simp] lemma image_Icc (e : α ≃o β) (a b : α) : e '' (Icc a b) = Icc (e a) (e b) := by rw [e.image_eq_preimage, e.symm.preimage_Icc, e.symm_symm] end preorder /-- Order isomorphism between `Iic (⊤ : α)` and `α` when `α` has a top element -/ def Iic_top [order_top α] : set.Iic (⊤ : α) ≃o α := { map_rel_iff' := λ x y, by refl, .. (@equiv.subtype_univ_equiv α (set.Iic (⊤ : α)) (λ x, le_top)), } /-- Order isomorphism between `Ici (⊥ : α)` and `α` when `α` has a bottom element -/ def Ici_bot [order_bot α] : set.Ici (⊥ : α) ≃o α := { map_rel_iff' := λ x y, by refl, .. (@equiv.subtype_univ_equiv α (set.Ici (⊥ : α)) (λ x, bot_le)) } end order_iso
ac0d625fc45b56569dddc6bee9ec18ea233acf4e
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/223.lean
34ef6ca33529bdbd71a7c9cd25b6b6be79ca8555
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
335
lean
universe u v inductive Imf {α : Type u} {β : Type v} (f : α → β) : β → Type (max u v) | mk : (a : α) → Imf f (f a) def h {α β} {f : α → β} : {b : β} → Imf f b → α | _, Imf.mk a => a #print h theorem ex : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a ≅ a | α, _, rfl, a => HEq.refl a #print ex
4c71846fd079e357fa2ae75fb0756db3b9b58731
fe84e287c662151bb313504482b218a503b972f3
/src/commutative_algebra/book/sec_rings.lean
ed2dc37a3299123b60b5eff10fa60fad32b562ba
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
8,253
lean
import algebra.ring data.rat data.real.basic data.complex.basic import data.nat.prime ring_theory.subring.basic number_theory.zsqrtd.gaussian_int data.zmod.basic import topology.constructions topology.continuous_function.algebra topology.instances.real import data.mv_polynomial import tactic.ring import commutative_algebra.local_integers import commutative_algebra.galois_field_4 import commutative_algebra.ring_of_subsets namespace sec_rings variable (n : ℕ+) /- -------------------------------------------------------- -/ /- defn-ring -/ #print comm_ring /- eg-numbers -/ #check (by apply_instance : comm_ring ℤ) #check (by apply_instance : comm_ring ℚ) #check (by apply_instance : comm_ring ℝ) #check (by apply_instance : comm_ring ℂ) #check (by apply_instance : comm_semiring ℕ) -- #check (by apply_instance : comm_ring ℕ) -- fails /- -------------------------------------------------------- -/ /- eg-tw-local -/ #check (by apply_instance : comm_ring (local_integers 2)) #check (by apply_instance : comm_ring gaussian_int) /- -------------------------------------------------------- -/ /- defn-subring -/ #print subring /- -------------------------------------------------------- -/ /- eg-subrings -/ -- TO DO /- -------------------------------------------------------- -/ /- eg-modular -/ #check (by apply_instance : comm_ring (zmod n)) /- -------------------------------------------------------- -/ /- eg-trivial-ring -/ def unit_comm_ring : comm_ring unit := by { apply_instance } /- -------------------------------------------------------- -/ /- eg-square-matrices -/ -- TO DO /- -------------------------------------------------------- -/ /- eg-F-four -/ #check F4 #check (by apply_instance : field F4) -- from galois_field_4.lean /- -------------------------------------------------------- -/ /- eg-boolean -/ namespace eg_boolean universes uS variables (S : Type uS) #check (by apply_instance : comm_ring (ring_of_subsets S)) end eg_boolean /- -------------------------------------------------------- -/ /- defn-binary-product -/ namespace defn_binary_product universes uA uB variables (A : Type uA) (B : Type uB) [comm_ring A] [comm_ring B] #check (by apply_instance : comm_ring (A × B)) example (a a' : A) (b b' : B) : (prod.mk a b) * (prod.mk a' b') = prod.mk (a * a') (b * b') := rfl end defn_binary_product /- -------------------------------------------------------- -/ /- rem axis-not_subring -/ namespace axis_not_subring lemma axis_not_subring (A B : Type*) [comm_ring A] [comm_ring B] (hB : (1 : B) ≠ 0) {S : subring (A × B)} (hS : S.carrier = (λ ab : (A × B), ab.snd = 0)) : false := begin let h := S.one_mem, rw[← subring.mem_carrier, hS] at h, exact hB h, end end axis_not_subring /- -------------------------------------------------------- -/ /- rem-infinite-product -/ -- TO DO /- -------------------------------------------------------- -/ /- defn-map-ring -/ namespace defn_map_ring universes uA uS variables (A : Type uA) [comm_ring A] (S : Type uS) #check (by apply_instance : comm_ring (S → A)) end defn_map_ring /- -------------------------------------------------------- -/ /- rem-function-rings -/ namespace rem_function_rings universe uX variables (X : Type uX) [topological_space X] noncomputable def R : (comm_ring (continuous_map X ℝ)) := continuous_map.comm_ring end rem_function_rings /- -------------------------------------------------------- -/ /- eg-sunset -/ namespace eg_sunset def X := { xy : ℝ × ℝ // (xy.1 ^ 2 + xy.2 ^ 2 - 1) * xy.2 = 0 } noncomputable instance : topological_space X := by { unfold X, apply_instance } @[reducible ] def CX := continuous_map X ℝ noncomputable instance CX_comm_ring : comm_ring CX := by { unfold CX, exact continuous_map.comm_ring } def CX.x : CX := ⟨prod.fst ∘ subtype.val, continuous.comp continuous_fst continuous_subtype_val⟩ def CX.y : CX := ⟨prod.snd ∘ subtype.val, continuous.comp continuous_snd continuous_subtype_val⟩ lemma CX.x_def (xy : X) : CX.x xy = xy.val.1 := rfl lemma CX.y_def (xy : X) : CX.y xy = xy.val.2 := rfl lemma CX.rel : (CX.x ^ 2 + CX.y ^2 - 1) * CX.y = 0 := begin ext ab, rcases ab with ⟨⟨a,b⟩,e⟩, exact e end @[derive decidable_eq] inductive A_gens | x : A_gens | y : A_gens def PX := mv_polynomial A_gens ℝ noncomputable instance PX_comm_ring : comm_ring PX := by {unfold PX, apply_instance} noncomputable def PX.x : PX := @mv_polynomial.X ℝ A_gens _ A_gens.x noncomputable def PX.y : PX := @mv_polynomial.X ℝ A_gens _ A_gens.y noncomputable def PX.relator : PX := (PX.x ^ 2 + PX.y ^ 2 - 1) * PX.y def φ₀ : ℝ →+* CX := { to_fun := λ c, ⟨(λ u, c),continuous_const⟩, map_zero' := by { ext, refl }, map_add' := λ c d, by { ext, refl }, map_one' := by { ext, refl }, map_mul' := λ c d, by { ext, refl } } def φ₁ : A_gens → CX | A_gens.x := CX.x | A_gens.y := CX.y noncomputable def φ : PX →+* CX := mv_polynomial.eval₂_hom φ₀ φ₁ end eg_sunset /- -------------------------------------------------------- -/ /- defn-general-product -/ -- TO DO /- -------------------------------------------------------- -/ /- rem-product-subring -/ -- TO DO /- -------------------------------------------------------- -/ /- eg-padic -/ namespace eg_padic variables (p : ℕ) [fact (p > 0)] lemma p_pow_pos (k : ℕ) : fact (p ^ k > 0) := fact.mk begin have h : p > 0 := fact.elim (by apply_instance), exact pow_pos h k end local attribute [instance] p_pow_pos def P := ∀ (k : ℕ), (zmod (p ^ k)) instance P_ring : comm_ring (P p) := by { unfold P, apply_instance } def π (k : ℕ) : zmod (p ^ (k + 1)) →+* zmod (p ^ k) := zmod.cast_hom (pow_dvd_pow p (le_of_lt (nat.lt_succ_self k))) (zmod (p ^ k)) def is_coherent (a : P p) := ∀ (k : ℕ), π p k (a (k + 1)) = (a k) def p_adic_integers : subring (P p) := { carrier := is_coherent p, zero_mem' := by { intro k, change π p k 0 = 0, exact ring_hom.map_zero _ }, add_mem' := by { intros a b ha hb k, change π p k ((a (k + 1)) + (b (k + 1))) = (a k) + (b k), rw[ring_hom.map_add, ha k, hb k], }, neg_mem' := by { intros a ha k, change π p k (- (a (k + 1))) = - (a k), rw[ring_hom.map_neg,ha k], }, one_mem' := by { intro k, change π p k 1 = 1, exact ring_hom.map_one _ }, mul_mem' := by { intros a b ha hb k, change π p k ((a (k + 1)) * (b (k + 1))) = (a k) * (b k), rw[ring_hom.map_mul, ha k, hb k], } } variables (q : ℕ) [fact q.prime] lemma q_pos : fact (q > 0) := ⟨nat.prime.pos (fact.elim (by { apply_instance }))⟩ lemma q_pred (k : ℕ) : (q.pred : (zmod (q ^ k))) = (q : (zmod (q ^ k))) - 1 := begin have h : q.pred + 1 = q := nat.succ_pred_eq_of_pos (fact.elim (by {apply_instance})), symmetry, rw[sub_eq_iff_eq_add, ← nat.cast_one, ← nat.cast_add, h] end local attribute [instance] q_pos def a₀ : ℕ → ℕ | 0 := 0 | (k + 1) := (a₀ k) + q ^ k lemma a₀_step (k : ℕ) : a₀ q (k + 1) = 1 + q * (a₀ q k) := begin induction k with k ih, { dsimp[a₀], rw[pow_zero, mul_zero, zero_add] }, { have h₀ : 1 + q * (a₀ q (k + 1)) = 1 + q * (a₀ q k) + q ^ (k + 1) := by { rw[a₀, mul_add, add_assoc, pow_succ] }, have h₁ : a₀ q (k + 2) = a₀ q (k + 1) + q ^ (k + 1) := rfl, rw[h₀, h₁, ih] } end def a : p_adic_integers q := ⟨ λ k, (a₀ q k), begin intro k, change π q k (a₀ q (k + 1)) = a₀ q k, rw[map_nat_cast,a₀], rw[nat.cast_add,zmod.nat_cast_self,add_zero] end ⟩ def b : p_adic_integers q := ⟨λ k, (q : zmod (q ^ k)) - 1, begin intro k, change π q k (q - 1) = (q - 1), rw[← q_pred, ← q_pred, map_nat_cast], end ⟩ lemma ab : (a q) * (b q) = - 1 := begin rw[mul_comm], ext k, change ((q : zmod (q ^ k)) - 1) * (a₀ q k) = - (1 : (zmod (q ^ k))), rw[sub_mul, one_mul, sub_eq_iff_eq_add', ← sub_eq_add_neg], symmetry, rw[sub_eq_iff_eq_add', ← nat.cast_one, ← nat.cast_mul, ← nat.cast_add], rw[← a₀_step, a₀, nat.cast_add, zmod.nat_cast_self, add_zero] end end eg_padic end sec_rings
3b5f49c472e810d82094702dc273ff35f7a57236
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Elab/Match.lean
49432830a14400daf9110990b0426ff620172c1c
[ "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
33,329
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Match.MatchPatternAttr import Lean.Meta.Match.Match import Lean.Elab.SyntheticMVars import Lean.Elab.App namespace Lean namespace Elab namespace Term open Meta /- This modules assumes "match"-expressions use the following syntax. ```lean def matchAlt : Parser := nodeWithAntiquot "matchAlt" `Lean.Parser.Term.matchAlt $ sepBy1 termParser ", " >> darrow >> termParser def matchAlts (optionalFirstBar := true) : Parser := group $ withPosition $ fun pos => (if optionalFirstBar then optional "| " else "| ") >> sepBy1 matchAlt (checkColGe pos.column "alternatives must be indented" >> "|") def matchDiscr := parser! optional (try (ident >> checkNoWsBefore "no space before ':'" >> ":")) >> termParser def «match» := parser!:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` -/ structure MatchAltView := (ref : Syntax) (patterns : Array Syntax) (rhs : Syntax) def mkMatchAltView (ref : Syntax) (matchAlt : Syntax) : MatchAltView := { ref := ref, patterns := (matchAlt.getArg 0).getArgs.getSepElems, rhs := matchAlt.getArg 2 } private def expandSimpleMatch (stx discr lhsVar rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do newStx ← `(let $lhsVar := $discr; $rhs); withMacroExpansion stx newStx $ elabTerm newStx expectedType? private def expandSimpleMatchWithType (stx discr lhsVar type rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do newStx ← `(let $lhsVar : $type := $discr; $rhs); withMacroExpansion stx newStx $ elabTerm newStx expectedType? private partial def elabDiscrsWitMatchTypeAux (discrStxs : Array Syntax) (expectedType : Expr) : Nat → Expr → Array Expr → TermElabM (Array Expr) | i, matchType, discrs => if h : i < discrStxs.size then do let discrStx := (discrStxs.get ⟨i, h⟩).getArg 1; matchType ← whnf matchType; match matchType with | Expr.forallE _ d b _ => do discr ← fullApproxDefEq $ elabTermEnsuringType discrStx d; trace `Elab.match fun _ => "discr #" ++ toString i ++ " " ++ discr ++ " : " ++ d; elabDiscrsWitMatchTypeAux (i+1) (b.instantiate1 discr) (discrs.push discr) | _ => throwError ("invalid type provided to match-expression, function type with arity #" ++ toString discrStxs ++ " expected") else do unlessM (fullApproxDefEq $ isDefEq matchType expectedType) $ throwError ("invalid result type provided to match-expression" ++ indentExpr matchType ++ Format.line ++ "expected type" ++ indentExpr expectedType); pure discrs private def elabDiscrsWitMatchType (discrStxs : Array Syntax) (matchType : Expr) (expectedType : Expr) : TermElabM (Array Expr) := elabDiscrsWitMatchTypeAux discrStxs expectedType 0 matchType #[] private def mkUserNameFor (e : Expr) : TermElabM Name := match e with | Expr.fvar fvarId _ => do localDecl ← getLocalDecl fvarId; pure localDecl.userName | _ => mkFreshBinderName private def elabMatchTypeAndDiscrsAux (discrStxs : Array Syntax) : Nat → Array Expr → Expr → Array MatchAltView → TermElabM (Array Expr × Expr × Array MatchAltView) | 0, discrs, matchType, matchAltViews => pure (discrs.reverse, matchType, matchAltViews) | i+1, discrs, matchType, matchAltViews => do let discrStx := discrStxs.get! i; discr ← elabTerm (discrStx.getArg 1) none; discr ← instantiateMVars discr; discrType ← inferType discr; discrType ← instantiateMVars discrType; matchTypeBody ← kabstract matchType discr; userName ← mkUserNameFor discr; if (discrStx.getArg 0).isNone then do elabMatchTypeAndDiscrsAux i (discrs.push discr) (Lean.mkForall userName BinderInfo.default discrType matchTypeBody) matchAltViews else let identStx := (discrStx.getArg 0).getArg 0; withLocalDeclD userName discrType fun x => do eqType ← mkEq discr x; withLocalDeclD identStx.getId eqType fun h => do let matchTypeBody := matchTypeBody.instantiate1 x; matchType ← mkForallFVars #[x, h] matchTypeBody; refl ← mkEqRefl discr; let discrs := (discrs.push refl).push discr; let matchAltViews := matchAltViews.map fun altView => { altView with patterns := altView.patterns.insertAt (i+1) identStx }; elabMatchTypeAndDiscrsAux i discrs matchType matchAltViews private def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptType : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr) : TermElabM (Array Expr × Expr × Array MatchAltView) := let numDiscrs := discrStxs.size; if matchOptType.isNone then do elabMatchTypeAndDiscrsAux discrStxs discrStxs.size #[] expectedType matchAltViews else do let matchTypeStx := (matchOptType.getArg 0).getArg 1; matchType ← elabType matchTypeStx; discrs ← elabDiscrsWitMatchType discrStxs matchType expectedType; pure (discrs, matchType, matchAltViews) /- nodeWithAntiquot "matchAlt" `Lean.Parser.Term.matchAlt $ sepBy1 termParser ", " >> darrow >> termParser -/ def expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do matchAlts.mapM fun matchAlt => do patterns ← matchAlt.patterns.mapM $ expandMacros; pure $ { matchAlt with patterns := patterns } private partial def getMatchAltsAux (args : Array Syntax) : Nat → Syntax → Array MatchAltView → Array MatchAltView | i, ref, result => if h : i < args.size then let arg := args.get ⟨i, h⟩; let ref := if ref.isNone then arg else ref; -- The first vertical is optional if arg.getKind == `Lean.Parser.Term.matchAlt then getMatchAltsAux (i+1) ref (result.push (mkMatchAltView ref arg)) else -- current `arg` is the vertical bar delimiter getMatchAltsAux (i+1) arg result else result /- Given `stx` a match-expression, return its alternatives. -/ private def getMatchAlts (stx : Syntax) : Array MatchAltView := let matchAlts := stx.getArg 4; let firstVBar := matchAlts.getArg 0; getMatchAltsAux (matchAlts.getArg 1).getArgs 0 firstVBar #[] /-- Auxiliary annotation used to mark terms marked with the "inaccessible" annotation `.(t)` and `_` in patterns. -/ def mkInaccessible (e : Expr) : Expr := mkAnnotation `_inaccessible e def inaccessible? (e : Expr) : Option Expr := annotation? `_inaccessible e inductive PatternVar | localVar (userName : Name) -- anonymous variables (`_`) are encoded using metavariables | anonymousVar (mvarId : MVarId) instance PatternVar.hasToString : HasToString PatternVar := ⟨fun v => match v with | PatternVar.localVar x => toString x | PatternVar.anonymousVar mvarId => "?m" ++ toString mvarId⟩ @[init] private def registerAuxiliaryNodeKind : IO Unit := Parser.registerBuiltinNodeKind `MVarWithIdKind /-- Create an auxiliary Syntax node wrapping a fresh metavariable id. We use this kind of Syntax for representing `_` occurring in patterns. The metavariables are created before we elaborate the patterns into `Expr`s. -/ private def mkMVarSyntax : TermElabM Syntax := do mvarId ← mkFreshId; pure $ Syntax.node `MVarWithIdKind #[Syntax.node mvarId #[]] /-- Given a syntax node constructed using `mkMVarSyntax`, return its MVarId -/ private def getMVarSyntaxMVarId (stx : Syntax) : MVarId := (stx.getArg 0).getKind /-- The elaboration function for `Syntax` created using `mkMVarSyntax`. It just converts the metavariable id wrapped by the Syntax into an `Expr`. -/ @[builtinTermElab MVarWithIdKind] def elabMVarWithIdKind : TermElab := fun stx expectedType? => pure $ mkInaccessible $ mkMVar (getMVarSyntaxMVarId stx) @[builtinTermElab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do e ← elabTerm (stx.getArg 1) expectedType?; pure $ mkInaccessible e /- Patterns define new local variables. This module collect them and preprocess `_` occurring in patterns. Recall that an `_` may represent anonymous variables or inaccessible terms that are implied by typing constraints. Thus, we represent them with fresh named holes `?x`. After we elaborate the pattern, if the metavariable remains unassigned, we transform it into a regular pattern variable. Otherwise, it becomes an inaccessible term. Macros occurring in patterns are expanded before the `collectPatternVars` method is executed. The following kinds of Syntax are handled by this module - Constructor applications - Applications of functions tagged with the `[matchPattern]` attribute - Identifiers - Anonymous constructors - Structure instances - Inaccessible terms - Named patterns - Tuple literals - Type ascriptions - Literals: num, string and char -/ namespace CollectPatternVars structure State := (found : NameSet := {}) (vars : Array PatternVar := #[]) abbrev M := StateRefT State TermElabM private def throwCtorExpected {α} : M α := throwError "invalid pattern, constructor or constant marked with '[matchPattern]' expected" private def getNumExplicitCtorParams (ctorVal : ConstructorVal) : TermElabM Nat := forallBoundedTelescope ctorVal.type ctorVal.nparams fun ps _ => ps.foldlM (fun acc p => do localDecl ← getLocalDecl p.fvarId!; if localDecl.binderInfo.isExplicit then pure $ acc+1 else pure acc) 0 private def throwAmbiguous {α} (fs : List Expr) : M α := throwError ("ambiguous pattern, use fully qualified name, possible interpretations " ++ fs) def resolveId? (stx : Syntax) : M (Option Expr) := match stx with | Syntax.ident _ _ val preresolved => do rs ← liftM $ catch (resolveName val preresolved []) (fun _ => pure []); let rs := rs.filter fun ⟨f, projs⟩ => projs.isEmpty; let fs := rs.map fun ⟨f, _⟩ => f; match fs with | [] => pure none | [f] => pure (some f) | _ => throwAmbiguous fs | _ => throwError "identifier expected" private def throwInvalidPattern {α} : M α := throwError "invalid pattern" namespace CtorApp /- An application in a pattern can be 1- A constructor application The elaborator assumes fields are accessible and inductive parameters are not accessible. 2- A regular application `(f ...)` where `f` is tagged with `[matchPattern]`. The elaborator assumes implicit arguments are not accessible and explicit ones are accessible. -/ structure Context := (funId : Syntax) (ctorVal? : Option ConstructorVal) -- It is `some`, if constructor application (explicit : Bool) (ellipsis : Bool) (paramDecls : Array LocalDecl) (paramDeclIdx : Nat := 0) (namedArgs : Array NamedArg) (args : List Arg) (newArgs : Array Syntax := #[]) instance Context.inhabited : Inhabited Context := ⟨⟨arbitrary _, none, false, false, #[], 0, #[], [], #[]⟩⟩ private def isDone (ctx : Context) : Bool := ctx.paramDeclIdx ≥ ctx.paramDecls.size private def finalize (ctx : Context) : M Syntax := if ctx.namedArgs.isEmpty && ctx.args.isEmpty then do fStx ← `(@$(ctx.funId):ident); pure $ mkAppStx fStx ctx.newArgs else throwError "too many arguments" private def isNextArgAccessible (ctx : Context) : Bool := let i := ctx.paramDeclIdx; match ctx.ctorVal? with | some ctorVal => i ≥ ctorVal.nparams -- For constructor applications only fields are accessible | none => if h : i < ctx.paramDecls.size then -- For `[matchPattern]` applications, only explicit parameters are accessible. let d := ctx.paramDecls.get ⟨i, h⟩; d.binderInfo.isExplicit else false private def getNextParam (ctx : Context) : LocalDecl × Context := let i := ctx.paramDeclIdx; let d := ctx.paramDecls.get! i; (d, { ctx with paramDeclIdx := ctx.paramDeclIdx + 1 }) private def pushNewArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) (arg : Arg) : M Context := match arg with | Arg.stx stx => do stx ← if accessible then collect stx else pure stx; pure { ctx with newArgs := ctx.newArgs.push stx } | _ => unreachable! private def processExplicitArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) : M Context := match ctx.args with | [] => if ctx.ellipsis then do hole ← `(_); pushNewArg collect accessible ctx (Arg.stx hole) else throwError ("explicit parameter is missing, unused named arguments " ++ toString (ctx.namedArgs.map $ fun narg => narg.name)) | arg::args => do let ctx := { ctx with args := args }; pushNewArg collect accessible ctx arg private def processImplicitArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) : M Context := if ctx.explicit then processExplicitArg collect accessible ctx else do hole ← `(_); pushNewArg collect accessible ctx (Arg.stx hole) private partial def processCtorAppAux (collect : Syntax → M Syntax) : Context → M Syntax | ctx => if isDone ctx then finalize ctx else let accessible := isNextArgAccessible ctx; let (d, ctx) := getNextParam ctx; match ctx.namedArgs.findIdx? (fun namedArg => namedArg.name == d.userName) with | some idx => do let arg := ctx.namedArgs.get! idx; let ctx := { ctx with namedArgs := ctx.namedArgs.eraseIdx idx }; ctx ← pushNewArg collect accessible ctx arg.val; processCtorAppAux ctx | none => do ctx ← match d.binderInfo with | BinderInfo.implicit => processImplicitArg collect accessible ctx | BinderInfo.instImplicit => processImplicitArg collect accessible ctx | _ => processExplicitArg collect accessible ctx; processCtorAppAux ctx def processCtorApp (collect : Syntax → M Syntax) (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) : M Syntax := do let args := args.toList; (fId, explicit) ← match_syntax f with | `($fId:ident) => pure (fId, false) | `(@$fId:ident) => pure (fId, true) | _ => throwError "identifier expected"; some (Expr.const fName _ _) ← resolveId? fId | throwCtorExpected; fInfo ← getConstInfo fName; forallTelescopeReducing fInfo.type fun xs _ => do paramDecls ← xs.mapM getFVarLocalDecl; match fInfo with | ConstantInfo.ctorInfo val => processCtorAppAux collect { funId := fId, explicit := explicit, ctorVal? := val, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } | _ => do env ← getEnv; if hasMatchPatternAttribute env fName then processCtorAppAux collect { funId := fId, explicit := explicit, ctorVal? := none, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } else throwCtorExpected end CtorApp def processCtorApp (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do (f, namedArgs, args, ellipsis) ← liftM $ expandApp stx true; CtorApp.processCtorApp collect f namedArgs args ellipsis def processCtor (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do CtorApp.processCtorApp collect stx #[] #[] false private def processVar (idStx : Syntax) : M Syntax := do unless idStx.isIdent $ throwErrorAt idStx "identifier expected"; let id := idStx.getId; unless id.eraseMacroScopes.isAtomic $ throwError "invalid pattern variable, must be atomic"; s ← get; when (s.found.contains id) $ throwError ("invalid pattern, variable '" ++ id ++ "' occurred more than once"); modify fun s => { s with vars := s.vars.push (PatternVar.localVar id), found := s.found.insert id }; pure idStx /- Check whether `stx` is a pattern variable or constructor-like (i.e., constructor or constant tagged with `[matchPattern]` attribute) -/ private def processId (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do env ← getEnv; f? ← resolveId? stx; match f? with | none => processVar stx | some f => match f with | Expr.const fName _ _ => do match env.find? fName with | some (ConstantInfo.ctorInfo _) => processCtor collect stx | some _ => if hasMatchPatternAttribute env fName then processCtor collect stx else processVar stx | none => throwCtorExpected | _ => processVar stx private def nameToPattern : Name → TermElabM Syntax | Name.anonymous => `(Name.anonymous) | Name.str p s _ => do p ← nameToPattern p; `(Name.str $p $(quote s) _) | Name.num p n _ => do p ← nameToPattern p; `(Name.num $p $(quote n) _) private def quotedNameToPattern (stx : Syntax) : TermElabM Syntax := match (stx.getArg 0).isNameLit? with | some val => nameToPattern val | none => throwIllFormedSyntax partial def collect : Syntax → M Syntax | stx@(Syntax.node k args) => withRef stx $ withFreshMacroScope $ if k == `Lean.Parser.Term.app then do processCtorApp collect stx else if k == `Lean.Parser.Term.anonymousCtor then do elems ← (args.get! 1).getArgs.mapSepElemsM $ collect; pure $ Syntax.node k $ args.set! 1 $ mkNullNode elems else if k == `Lean.Parser.Term.structInst then do /- { " >> optional (try (termParser >> " with ")) >> sepBy structInstField ", " true >> optional ".." >> optional (" : " >> termParser) >> " }" -/ let withMod := args.get! 1; unless withMod.isNone $ throwErrorAt withMod "invalid struct instance pattern, 'with' is not allowed in patterns"; let fields := (args.get! 2).getArgs; fields ← fields.mapSepElemsM fun field => do { -- parser! structInstLVal >> " := " >> termParser newVal ← collect (field.getArg 3); -- `structInstLVal` has arity 2 pure $ field.setArg 3 newVal }; pure $ Syntax.node k $ args.set! 2 $ mkNullNode fields else if k == `Lean.Parser.Term.hole then do r ← liftM mkMVarSyntax; modify fun s => { s with vars := s.vars.push $ PatternVar.anonymousVar $ getMVarSyntaxMVarId r }; pure r else if k == `Lean.Parser.Term.paren then let arg := args.get! 1; if arg.isNone then pure stx -- `()` else do let t := arg.getArg 0; let s := arg.getArg 1; if s.isNone || (s.getArg 0).isOfKind `Lean.Parser.Term.typeAscription then do -- Ignore `s`, since it empty or it is a type ascription t ← collect t; let arg := arg.setArg 0 t; pure $ Syntax.node k $ args.set! 1 arg else do -- Tuple literal is a constructor t ← collect t; let arg := arg.setArg 0 t; let tupleTail := s.getArg 0; let tupleTailElems := (tupleTail.getArg 1).getArgs; tupleTailElems ← tupleTailElems.mapSepElemsM collect; let tupleTail := tupleTail.setArg 1 $ mkNullNode tupleTailElems; let s := s.setArg 0 tupleTail; let arg := arg.setArg 1 s; pure $ Syntax.node k $ args.set! 1 arg else if k == `Lean.Parser.Term.explicitUniv then do processCtor collect (stx.getArg 0) else if k == `Lean.Parser.Term.namedPattern then do /- Recall that def namedPattern := check... >> tparser! "@" >> termParser -/ let id := stx.getArg 0; processVar id; let pat := stx.getArg 2; pat ← collect pat; `(namedPattern $id $pat) else if k == `Lean.Parser.Term.inaccessible then pure stx else if k == strLitKind then pure stx else if k == numLitKind then pure stx else if k == charLitKind then pure stx else if k == `Lean.Parser.Term.quotedName then /- Quoted names have an elaboration function associated with them, and they will not be macro expanded. Note that macro expansion is not a good option since it produces a term using the smart constructors `mkNameStr`, `mkNameNum` instead of the constructors `Name.str` and `Name.num` -/ liftM $ quotedNameToPattern stx else if k == choiceKind then throwError "invalid pattern, notation is ambiguous" else throwInvalidPattern | stx@(Syntax.ident _ _ _ _) => processId collect stx | stx => throwInvalidPattern def main (alt : MatchAltView) : M MatchAltView := do patterns ← alt.patterns.mapM fun p => do { trace `Elab.match fun _ => "collecting variables at pattern: " ++ p; collect p }; pure { alt with patterns := patterns } end CollectPatternVars private def collectPatternVars (alt : MatchAltView) : TermElabM (Array PatternVar × MatchAltView) := do (alt, s) ← (CollectPatternVars.main alt).run {}; pure (s.vars, alt) /- Return the pattern variables in the given pattern. Remark: this method is not used here, but in other macros (e.g., at `Do.lean`). -/ def getPatternVars (patternStx : Syntax) : TermElabM (Array PatternVar) := do (_, s) ← (CollectPatternVars.collect patternStx).run {}; pure s.vars /- We convert the collected `PatternVar`s intro `PatternVarDecl` -/ inductive PatternVarDecl /- For `anonymousVar`, we create both a metavariable and a free variable. The free variable is used as an assignment for the metavariable when it is not assigned during pattern elaboration. -/ | anonymousVar (mvarId : MVarId) (fvarId : FVarId) | localVar (fvarId : FVarId) private partial def withPatternVarsAux {α} (pVars : Array PatternVar) (k : Array PatternVarDecl → TermElabM α) : Nat → Array PatternVarDecl → TermElabM α | i, decls => if h : i < pVars.size then match pVars.get ⟨i, h⟩ with | PatternVar.anonymousVar mvarId => do type ← mkFreshTypeMVar; userName ← mkFreshBinderName; withLocalDecl userName BinderInfo.default type fun x => withPatternVarsAux (i+1) (decls.push (PatternVarDecl.anonymousVar mvarId x.fvarId!)) | PatternVar.localVar userName => do type ← mkFreshTypeMVar; withLocalDecl userName BinderInfo.default type fun x => withPatternVarsAux (i+1) (decls.push (PatternVarDecl.localVar x.fvarId!)) else do /- We must create the metavariables for `PatternVar.anonymousVar` AFTER we create the new local decls using `withLocalDecl`. Reason: their scope must include the new local decls since some of them are assigned by typing constraints. -/ decls.forM fun decl => match decl with | PatternVarDecl.anonymousVar mvarId fvarId => do type ← inferType (mkFVar fvarId); _ ← mkFreshExprMVarWithId mvarId type; pure () | _ => pure (); k decls private def withPatternVars {α} (pVars : Array PatternVar) (k : Array PatternVarDecl → TermElabM α) : TermElabM α := withPatternVarsAux pVars k 0 #[] private partial def elabPatternsAux (patternStxs : Array Syntax) : Nat → Expr → Array Expr → TermElabM (Array Expr × Expr) | i, matchType, patterns => if h : i < patternStxs.size then do matchType ← whnf matchType; match matchType with | Expr.forallE _ d b _ => do let patternStx := patternStxs.get ⟨i, h⟩; pattern ← elabTermEnsuringType patternStx d; elabPatternsAux (i+1) (b.instantiate1 pattern) (patterns.push pattern) | _ => throwError "unexpected match type" else pure (patterns, matchType) def finalizePatternDecls (patternVarDecls : Array PatternVarDecl) : TermElabM (Array LocalDecl) := patternVarDecls.foldlM (fun (decls : Array LocalDecl) pdecl => do match pdecl with | PatternVarDecl.localVar fvarId => do decl ← getLocalDecl fvarId; decl ← instantiateLocalDeclMVars decl; pure $ decls.push decl | PatternVarDecl.anonymousVar mvarId fvarId => do e ← instantiateMVars (mkMVar mvarId); trace `Elab.match fun _ => "finalizePatternDecls: mvarId: " ++ mvarId ++ " := " ++ e ++ ", fvarId: " ++ mkFVar fvarId; match e with | Expr.mvar newMVarId _ => do /- Metavariable was not assigned, or assigned to another metavariable. So, we assign to the auxiliary free variable we created at `withPatternVars` to `newMVarId`. -/ assignExprMVar newMVarId (mkFVar fvarId); trace `Elab.match fun _ => "finalizePatternDecls: " ++ mkMVar newMVarId ++ " := " ++ mkFVar fvarId; decl ← getLocalDecl fvarId; decl ← instantiateLocalDeclMVars decl; pure $ decls.push decl | _ => pure decls) #[] open Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult) namespace ToDepElimPattern structure State := (found : NameSet := {}) (localDecls : Array LocalDecl) (newLocals : NameSet := {}) abbrev M := StateRefT State TermElabM private def alreadyVisited (fvarId : FVarId) : M Bool := do s ← get; pure $ s.found.contains fvarId private def markAsVisited (fvarId : FVarId) : M Unit := modify $ fun s => { s with found := s.found.insert fvarId } private def throwInvalidPattern {α} (e : Expr) : M α := throwError ("invalid pattern " ++ indentExpr e) /- Create a new LocalDecl `x` for the metavariable `mvar`, and return `Pattern.var x` -/ private def mkLocalDeclFor (mvar : Expr) : M Pattern := do let mvarId := mvar.mvarId!; s ← get; val? ← getExprMVarAssignment? mvarId; match val? with | some val => pure $ Pattern.inaccessible val | none => do fvarId ← mkFreshId; type ← inferType mvar; /- HACK: `fvarId` is not in the scope of `mvarId` If this generates problems in the future, we should update the metavariable declarations. -/ assignExprMVar mvarId (mkFVar fvarId); userName ← liftM $ mkFreshBinderName; let newDecl := LocalDecl.cdecl (arbitrary _) fvarId userName type BinderInfo.default; modify $ fun s => { s with newLocals := s.newLocals.insert fvarId, localDecls := match s.localDecls.findIdx? fun decl => mvar.occurs decl.type with | none => s.localDecls.push newDecl -- None of the existing declarations depend on `mvar` | some i => s.localDecls.insertAt i newDecl }; pure $ Pattern.var fvarId partial def main : Expr → M Pattern | e => let isLocalDecl (fvarId : FVarId) : M Bool := do { s ← get; pure $ s.localDecls.any fun d => d.fvarId == fvarId }; let mkPatternVar (fvarId : FVarId) (e : Expr) : M Pattern := do { condM (alreadyVisited fvarId) (pure $ Pattern.inaccessible e) (do markAsVisited fvarId; pure $ Pattern.var e.fvarId!) }; let mkInaccessible (e : Expr) : M Pattern := do { match e with | Expr.fvar fvarId _ => condM (isLocalDecl fvarId) (mkPatternVar fvarId e) (pure $ Pattern.inaccessible e) | _ => pure $ Pattern.inaccessible e }; match inaccessible? e with | some t => mkInaccessible t | none => match e.arrayLit? with | some (α, lits) => do ps ← lits.mapM main; pure $ Pattern.arrayLit α ps | none => if e.isAppOfArity `namedPattern 3 then do p ← main $ e.getArg! 2; match e.getArg! 1 with | Expr.fvar fvarId _ => pure $ Pattern.as fvarId p | _ => throwError "unexpected occurrence of auxiliary declaration 'namedPattern'" else if e.isNatLit || e.isStringLit || e.isCharLit then pure $ Pattern.val e else if e.isFVar then do let fvarId := e.fvarId!; unlessM (isLocalDecl fvarId) $ throwInvalidPattern e; mkPatternVar fvarId e else if e.isMVar then do mkLocalDeclFor e else do newE ← whnf e; if newE != e then main newE else matchConstCtor e.getAppFn (fun _ => throwInvalidPattern e) fun v us => do let args := e.getAppArgs; unless (args.size == v.nparams + v.nfields) $ throwInvalidPattern e; let params := args.extract 0 v.nparams; let fields := args.extract v.nparams args.size; fields ← fields.mapM main; pure $ Pattern.ctor v.name us params.toList fields.toList end ToDepElimPattern def withDepElimPatterns {α} (localDecls : Array LocalDecl) (ps : Array Expr) (k : Array LocalDecl → Array Pattern → TermElabM α) : TermElabM α := do (patterns, s) ← (ps.mapM ToDepElimPattern.main).run { localDecls := localDecls }; localDecls ← s.localDecls.mapM fun d => instantiateLocalDeclMVars d; /- toDepElimPatterns may have added new localDecls. Thus, we must update the local context before we execute `k` -/ lctx ← getLCtx; let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.erase d.fvarId) lctx; let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.addDecl d) lctx; adaptTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) $ k localDecls patterns private def withElaboratedLHS {α} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr) (k : AltLHS → Expr → TermElabM α) : TermElabM α := do (patterns, matchType) ← withSynthesize $ elabPatternsAux patternStxs 0 matchType #[]; localDecls ← finalizePatternDecls patternVarDecls; patterns ← patterns.mapM instantiateMVars; withDepElimPatterns localDecls patterns fun localDecls patterns => k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType def elabMatchAltView (alt : MatchAltView) (matchType : Expr) : TermElabM (AltLHS × Expr) := withRef alt.ref do (patternVars, alt) ← collectPatternVars alt; trace `Elab.match fun _ => "patternVars: " ++ toString patternVars; withPatternVars patternVars fun patternVarDecls => do withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType => do rhs ← elabTermEnsuringType alt.rhs matchType; let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr; rhs ← if xs.isEmpty then pure $ mkThunk rhs else mkLambdaFVars xs rhs; trace `Elab.match fun _ => "rhs: " ++ rhs; pure (altLHS, rhs) def mkMatcher (elimName : Name) (matchType : Expr) (numDiscrs : Nat) (lhss : List AltLHS) : TermElabM MatcherResult := liftMetaM $ Meta.Match.mkMatcher elimName matchType numDiscrs lhss def reportMatcherResultErrors (result : MatcherResult) : TermElabM Unit := do -- TODO: improve error messages unless result.counterExamples.isEmpty $ throwError ("missing cases:" ++ Format.line ++ Meta.Match.counterExamplesToMessageData result.counterExamples); unless result.unusedAltIdxs.isEmpty $ throwError ("unused alternatives: " ++ toString (result.unusedAltIdxs.map fun idx => "#" ++ toString (idx+1))) private def elabMatchAux (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptType : Syntax) (expectedType : Expr) : TermElabM Expr := do (discrs, matchType, altViews) ← elabMatchTypeAndDiscrs discrStxs matchOptType altViews expectedType; matchAlts ← liftMacroM $ expandMacrosInPatterns altViews; trace `Elab.match fun _ => "matchType: " ++ matchType; alts ← matchAlts.mapM $ fun alt => elabMatchAltView alt matchType; synthesizeSyntheticMVarsNoPostponing; -- TODO report error if matchType or altLHSS.toList have metavars let rhss := alts.map Prod.snd; let altLHSS := alts.map Prod.fst; let numDiscrs := discrs.size; matcherName ← mkAuxName `match; matcherResult ← mkMatcher matcherName matchType numDiscrs altLHSS.toList; motive ← forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType; reportMatcherResultErrors matcherResult; let r := mkApp matcherResult.matcher motive; let r := mkAppN r discrs; let r := mkAppN r rhss; trace `Elab.match fun _ => "result: " ++ r; pure r private def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType?; match expectedType? with | some expectedType => pure expectedType | none => mkFreshTypeMVar /- ``` parser!:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` Remark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`. -/ private def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do expectedType ← waitExpectedType expectedType?; let discrStxs := (stx.getArg 1).getArgs.getSepElems.map fun d => d; let altViews := getMatchAlts stx; let matchOptType := stx.getArg 2; elabMatchAux discrStxs altViews matchOptType expectedType -- parser! "match " >> sepBy1 termParser ", " >> optType >> " with " >> matchAlts @[builtinTermElab «match»] def elabMatch : TermElab := fun stx expectedType? => match_syntax stx with | `(match $discr:term with $y:ident => $rhs:term) => expandSimpleMatch stx discr y rhs expectedType? | `(match $discr:term with | $y:ident => $rhs:term) => expandSimpleMatch stx discr y rhs expectedType? | `(match $discr:term : $type with $y:ident => $rhs:term) => expandSimpleMatchWithType stx discr y type rhs expectedType? | `(match $discr:term : $type with | $y:ident => $rhs:term) => expandSimpleMatchWithType stx discr y type rhs expectedType? | _ => do let discrs := (stx.getArg 1).getArgs; let matchOptType := stx.getArg 2; when (!matchOptType.isNone && discrs.getSepElems.any fun d => !(d.getArg 0).isNone) $ throwErrorAt matchOptType "match expected type should not be provided when discriminants with equality proofs are used"; elabMatchCore stx expectedType? @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.match; pure () -- parser!:leadPrec "nomatch " >> termParser @[builtinTermElab «nomatch»] def elabNoMatch : TermElab := fun stx expectedType? => match_syntax stx with | `(nomatch $discrExpr) => do expectedType ← waitExpectedType expectedType?; let discr := Syntax.node `Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr]; elabMatchAux #[discr] #[] mkNullNode expectedType | _ => throwUnsupportedSyntax end Term end Elab end Lean
5bc3f5cc363279dc6101469a6f83e7e90b2d2e1c
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/algebra_of_equiv.lean
4fb98ea9630b3506c68f020a83dfb8372046d03d
[]
no_license
ChrisHughes24/leanstuff
dca0b5349c3ed893e8792ffbd98cbcadaff20411
9efa85f72efaccd1d540385952a6acc18fce8687
refs/heads/master
1,654,883,241,759
1,652,873,885,000
1,652,873,885,000
134,599,537
1
0
null
null
null
null
UTF-8
Lean
false
false
4,472
lean
import data.equiv.basic algebra.field universes u v variables {α : Type u} {β : Type v} (e : α ≃ β) namespace equiv protected def has_zero [has_zero α] : has_zero β := ⟨e 0⟩ lemma zero_def [has_zero α] : @has_zero.zero _ (equiv.has_zero e) = e 0 := rfl protected def has_one [has_one α] : has_one β := ⟨e 1⟩ lemma one_def [has_one α] : @has_one.one _ (equiv.has_one e) = e 1 := rfl protected def has_mul [has_mul α] : has_mul β := ⟨λ x y, e (e.symm x * e.symm y)⟩ lemma mul_def [has_mul α] (x y : β) : @has_mul.mul _ (equiv.has_mul e) x y = e (e.symm x * e.symm y) := rfl protected def has_add [has_add α] : has_add β := ⟨λ x y, e (e.symm x + e.symm y)⟩ lemma add_def [has_add α] (x y : β) : @has_add.add _ (equiv.has_add e) x y = e (e.symm x + e.symm y) := rfl protected def has_inv [has_inv α] : has_inv β := ⟨λ x, e (e.symm x)⁻¹⟩ lemma inv_def [has_inv α] (x : β) : @has_inv.inv _ (equiv.has_inv e) x = e (e.symm x)⁻¹ := rfl protected def has_neg [has_neg α] : has_neg β := ⟨λ x, e (- e.symm x)⟩ lemma neg_def [has_neg α] (x : β) : @has_neg.neg _ (equiv.has_neg e) x = e (-e.symm x) := rfl protected def semigroup [semigroup α] : semigroup β := { mul_assoc := by simp [mul_def, mul_assoc], ..equiv.has_mul e } protected def comm_semigroup [comm_semigroup α] : comm_semigroup β := { mul_comm := by simp [mul_def, mul_comm], ..equiv.semigroup e } protected def monoid [monoid α] : monoid β := { one_mul := by simp [mul_def, one_def], mul_one := by simp [mul_def, one_def], ..equiv.semigroup e, ..equiv.has_one e } protected def comm_monoid [comm_monoid α] : comm_monoid β := { ..equiv.comm_semigroup e, ..equiv.monoid e } protected def group [group α] : group β := { mul_left_inv := by simp [mul_def, inv_def, one_def], ..equiv.monoid e, ..equiv.has_inv e } protected def comm_group [comm_group α] : comm_group β := { ..equiv.group e, ..equiv.comm_semigroup e } protected def add_semigroup [add_semigroup α] : add_semigroup β := @additive.add_semigroup _ (@equiv.semigroup _ _ e multiplicative.semigroup) protected def add_comm_semigroup [add_comm_semigroup α] : add_comm_semigroup β := @additive.add_comm_semigroup _ (@equiv.comm_semigroup _ _ e multiplicative.comm_semigroup) protected def add_monoid [add_monoid α] : add_monoid β := @additive.add_monoid _ (@equiv.monoid _ _ e multiplicative.monoid) protected def add_comm_monoid [add_comm_monoid α] : add_comm_monoid β := @additive.add_comm_monoid _ (@equiv.comm_monoid _ _ e multiplicative.comm_monoid) protected def add_group [add_group α] : add_group β := @additive.add_group _ (@equiv.group _ _ e multiplicative.group) protected def add_comm_group [add_comm_group α] : add_comm_group β := @additive.add_comm_group _ (@equiv.comm_group _ _ e multiplicative.comm_group) protected def ring [ring α] : ring β := { right_distrib := by simp [mul_def, add_def, add_mul], left_distrib := by simp [mul_def, add_def, mul_add], ..equiv.has_mul e, ..equiv.has_add e, ..equiv.monoid e, ..equiv.add_comm_group e } protected def comm_ring [comm_ring α] : comm_ring β := { ..equiv.comm_monoid e, ..equiv.ring e } protected def nonzero_comm_ring [nonzero_comm_ring α] : nonzero_comm_ring β := { zero_ne_one := by simp [zero_def, one_def], ..equiv.has_zero e, ..equiv.has_one e, ..equiv.comm_ring e } protected def integral_domain [integral_domain α] : integral_domain β := { eq_zero_or_eq_zero_of_mul_eq_zero := by simp [mul_def, zero_def, equiv.symm_apply_eq], ..equiv.has_zero e, ..equiv.has_mul e, ..equiv.nonzero_comm_ring e } protected def division_ring [division_ring α] : division_ring β := { zero_ne_one := by simp [zero_def, one_def], inv_mul_cancel := λ _, by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm]; exact inv_mul_cancel, mul_inv_cancel := λ _, by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm]; exact mul_inv_cancel, ..equiv.has_zero e, ..equiv.has_one e, ..equiv.ring e, ..equiv.has_inv e } protected def field [field α] : field β := { ..equiv.comm_ring e, ..equiv.division_ring e } protected def discrete_field [discrete_field α] : discrete_field β := { has_decidable_eq := equiv.decidable_eq e.symm, inv_zero := by simp [mul_def, inv_def, zero_def], ..equiv.has_mul e, ..equiv.has_inv e, ..equiv.has_zero e, ..equiv.field e } end equiv
47ee99a2ad4db40b497e166dd0b7850d37990208
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/1571.lean
b4c60b644bfd2dffecfadc8d84ec7993500881ab
[ "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
139
lean
#check True → (∃ a : Nat, a = a) -- True → ∃ a, a = a : Prop #check True → (∃ b : Nat, b = b) -- True → ∃ b, b = b : Prop
2d2311afd32beaf01336177ee38c17cebdc278fe
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/data/int/basic.lean
8c4cbd820993a89b379b4c4d1111ac13f4213f12
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
56,836
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The integers, with addition, multiplication, and subtraction. -/ import algebra.char_zero import algebra.ring import data.list.range open nat namespace int instance : comm_ring int := { add := int.add, add_assoc := int.add_assoc, zero := int.zero, zero_add := int.zero_add, add_zero := int.add_zero, neg := int.neg, add_left_neg := int.add_left_neg, add_comm := int.add_comm, mul := int.mul, mul_assoc := int.mul_assoc, one := int.one, one_mul := int.one_mul, mul_one := int.mul_one, left_distrib := int.distrib_left, right_distrib := int.distrib_right, mul_comm := int.mul_comm } /- Extra instances to short-circuit type class resolution -/ -- instance : has_sub int := by apply_instance -- This is in core instance : add_comm_monoid int := by apply_instance instance : add_monoid int := by apply_instance instance : monoid int := by apply_instance instance : comm_monoid int := by apply_instance instance : comm_semigroup int := by apply_instance instance : semigroup int := by apply_instance instance : add_comm_semigroup int := by apply_instance instance : add_semigroup int := by apply_instance instance : comm_semiring int := by apply_instance instance : semiring int := by apply_instance instance : ring int := by apply_instance instance : distrib int := by apply_instance instance : nonzero ℤ := { zero_ne_one := int.zero_ne_one } instance : inhabited ℤ := ⟨int.zero⟩ instance : decidable_linear_ordered_comm_ring int := { add_le_add_left := @int.add_le_add_left, zero_ne_one := int.zero_ne_one, mul_pos := @int.mul_pos, zero_lt_one := int.zero_lt_one, ..int.comm_ring, ..int.decidable_linear_order } instance : decidable_linear_ordered_add_comm_group int := by apply_instance theorem abs_eq_nat_abs : ∀ a : ℤ, abs a = nat_abs a | (n : ℕ) := abs_of_nonneg $ coe_zero_le _ | -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _ theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := by rw [abs_eq_nat_abs]; refl theorem sign_mul_abs (a : ℤ) : sign a * abs a = a := by rw [abs_eq_nat_abs, sign_mul_nat_abs] @[simp] lemma default_eq_zero : default ℤ = 0 := rfl meta instance : has_to_format ℤ := ⟨λ z, to_string z⟩ meta instance : has_reflect ℤ := by tactic.mk_has_reflect_instance attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ attribute [simp] int.of_nat_eq_coe int.bodd @[simp] theorem add_def {a b : ℤ} : int.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℤ} : int.mul a b = a * b := rfl @[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl @[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl @[simp, norm_cast] theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n @[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := by rw [← int.coe_nat_zero, coe_nat_lt] @[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := by rw [← int.coe_nat_zero, coe_nat_inj'] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _) lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n := ⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h), λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩ lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n) @[simp, norm_cast] theorem coe_nat_abs (n : ℕ) : abs (n : ℤ) = n := abs_of_nonneg (coe_nat_nonneg n) /- succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right _ zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self _ zero_lt_one theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b := @add_le_add_iff_right _ _ a b 1 theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b := sub_lt_iff_lt_add.trans lt_add_one_iff theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b := le_sub_iff_add_le @[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀i : ℕ, p i → p (i + 1)) (hn : ∀i : ℕ, p (-i) → p (-i - 1)) : p i := begin induction i, { induction i, { exact hz }, { exact hp _ i_ih } }, { have : ∀n:ℕ, p (- n), { intro n, induction n, { simp [hz] }, { convert hn _ n_ih using 1, simp [sub_eq_neg_add] } }, exact this (i + 1) } end protected def induction_on' {C : ℤ → Sort*} (z : ℤ) (b : ℤ) : C b → (∀ k, b ≤ k → C k → C (k + 1)) → (∀ k ≤ b, C k → C (k - 1)) → C z := λ H0 Hs Hp, begin rw ←sub_add_cancel z b, induction (z - b), { induction a with n ih, { rwa [of_nat_zero, zero_add] }, rw [of_nat_succ, add_assoc, add_comm 1 b, ←add_assoc], exact Hs _ (le_add_of_nonneg_left (of_nat_nonneg _)) ih }, { induction a with n ih, { rw [neg_succ_of_nat_eq, ←of_nat_eq_coe, of_nat_zero, zero_add, neg_add_eq_sub], exact Hp _ (le_refl _) H0 }, { rw [neg_succ_of_nat_coe', nat.succ_eq_add_one, ←neg_succ_of_nat_coe, sub_add_eq_add_sub], exact Hp _ (le_of_lt (add_lt_of_neg_of_le (neg_succ_lt_zero _) (le_refl _))) ih } } end /- nat abs -/ attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := begin have : ∀ (a b : ℕ), nat_abs (sub_nat_nat a (nat.succ b)) ≤ nat.succ (a + b), { refine (λ a b : ℕ, sub_nat_nat_elim a b.succ (λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl); intros i n e, { subst e, rw [add_comm _ i, add_assoc], exact nat.le_add_right i (b.succ + b).succ }, { apply succ_le_succ, rw [← succ.inj e, ← add_assoc, add_comm], apply nat.le_add_right } }, cases a; cases b with b b; simp [nat_abs, nat.succ_add]; try {refl}; [skip, rw add_comm a b]; apply this end theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n := by cases n; refl theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) := by cases a; cases b; simp only [(*), int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs] @[simp] lemma nat_abs_mul_self' (a : ℤ) : (nat_abs a * nat_abs a : ℤ) = a * a := by rw [← int.coe_nat_mul, nat_abs_mul_self] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq, sub_eq_neg_add] lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 := λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h @[simp] lemma nat_abs_eq_zero {a : ℤ} : a.nat_abs = 0 ↔ a = 0 := ⟨int.eq_zero_of_nat_abs_eq_zero, λ h, h.symm ▸ rfl⟩ lemma nat_abs_lt_nat_abs_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) : a.nat_abs < b.nat_abs := begin lift b to ℕ using le_trans w₁ (le_of_lt w₂), lift a to ℕ using w₁, simpa using w₂, end /- / -/ @[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl @[simp, norm_cast] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : 0 < b) : -[1+m] / b = -(m / b + 1) := match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end @[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b) | (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl | (m : ℕ) (n+1:ℕ) := rfl | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := (neg_neg _).symm | -[1+ m] 0 := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl end protected theorem div_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a / b := match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _ end protected theorem div_nonpos {a b : ℤ} (Ha : 0 ≤ a) (Hb : b ≤ 0) : a / b ≤ 0 := nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _ end -- Will be generalized to Euclidean domains. protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl local attribute [simp] -- Will be generalized to Euclidean domains. protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | 0 := rfl | (n+1:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := match b, abs b, abs_eq_nat_abs b, H2 with | (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2 | -[1+ n], ._, rfl, H2 := neg_inj $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2 end protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from λ k n a, match a with | (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos | -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ = n - (m / k.succ + 1 : ℕ), begin cases lt_or_ge m (n*k.succ) with h h, { rw [← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)], apply congr_arg of_nat, rw [mul_comm, nat.mul_sub_div], rwa mul_comm }, { change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) = ↑n - ((m / nat.succ k : ℕ) + 1), rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ), ← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h), ← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'], { apply congr_arg neg_succ_of_nat, rw [mul_comm, nat.sub_mul_div], rwa mul_comm } } end end, have ∀ {a b c : ℤ}, 0 < c → (a + b * c) / c = a / c + b, from λ a b c H, match c, eq_succ_of_zero_lt H, b with | ._, ⟨k, rfl⟩, (n : ℕ) := this | ._, ⟨k, rfl⟩, -[1+ n] := show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from eq_sub_of_add_eq $ by rw [← this, sub_add_cancel] end, match lt_trichotomy c 0 with | or.inl hlt := neg_inj $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg]; apply this (neg_pos_of_neg hlt) | or.inr (or.inl heq) := absurd heq H | or.inr (or.inr hgt) := this hgt end protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := by rw [mul_comm, int.add_mul_div_right _ _ H] @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := by have := int.add_mul_div_right 0 a H; rwa [zero_add, int.zero_div, zero_add] at this @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := by rw [mul_comm, int.mul_div_cancel _ H] @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := by have := int.mul_div_cancel 1 H; rwa one_mul at this /- mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : 0 < b) : -[1+m] % b = b - 1 - m % b := by rw [sub_sub, add_comm]; exact match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end @[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b | (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _) @[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b := abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _) local attribute [simp] -- Will be generalized to Euclidean domains. theorem zero_mod (b : ℤ) : 0 % b = 0 := congr_arg of_nat $ nat.zero_mod _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_zero : ∀ (a : ℤ), a % 0 = a | (m : ℕ) := congr_arg of_nat $ nat.mod_zero _ | -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_one : ∀ (a : ℤ), a % 1 = 0 | (m : ℕ) := congr_arg of_nat $ nat.mod_one _ | -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2) end theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → 0 ≤ a % b | (m : ℕ) n H := coe_zero_le _ | -[1+ m] n H := sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : 0 < b) : a % b < b := match a, b, eq_succ_of_zero_lt H with | (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _)) | -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _) end theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos_of_ne_zero H) theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) @[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := if cz : c = 0 then by rw [cz, mul_zero, add_zero] else by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz, mul_add, mul_comm, add_sub_add_right_eq_sub] @[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := by rw [mul_comm, add_mul_mod_self] @[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by have := add_mul_mod_self_left a b 1; rwa mul_one at this @[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := by rw [add_comm, add_mod_self] @[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℤ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔ m % n = k % n := ⟨λ H, by have := add_mod_eq_add_mod_right (-i) H; rwa [add_neg_cancel_right, add_neg_cancel_right] at this, add_mod_eq_add_mod_right _⟩ theorem mod_add_cancel_left {m n k i : ℤ} : (i + m) % n = (i + k) % n ↔ m % n = k % n := by rw [add_comm, add_comm i, mod_add_cancel_right] theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔ m % n = k % n := mod_add_cancel_right _ theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 := (mod_sub_cancel_right k).symm.trans $ by simp @[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 := by rw [← zero_add (a * b), add_mul_mod_self, zero_mod] @[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 := by rw [mul_comm, mul_mod_left] lemma mul_mod (a b n : ℤ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, mul_comm _ (n * (b / n)), mul_assoc, add_mul_mod_self_left] } end local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_self {a : ℤ} : a % a = 0 := by have := mul_mod_left 1 a; rwa one_mul at this @[simp] theorem mod_mod_of_dvd (n : int) {m k : int} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a b : ℤ) : a % b % b = a % b := by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]} /- properties of / and % -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b / (a * c) = b / c := suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with | ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _ | ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ := by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg]; apply congr_arg has_neg.neg; apply this end, λ m k b, match b, k with | (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos) | -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero] | -[1+ n], k+1 := congr_arg neg_succ_of_nat $ show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin apply nat.div_eq_of_lt_le, { refine le_trans _ (nat.le_add_right _ _), rw [← nat.mul_div_mul _ _ m.succ_pos], apply nat.div_mul_le_self }, { change m.succ * n.succ ≤ _, rw [mul_left_comm], apply nat.mul_le_mul_left, apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1, apply nat.lt_succ_self } end end @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : 0 < b) : a * b / (c * b) = a / c := by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H] @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b % (a * c) = a * (b % c) := by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : 0 < b) : a < (a / b + 1) * b := by rw [add_mul, one_mul, mul_comm]; apply lt_add_of_sub_left_lt; rw [← mod_def]; apply mod_lt_of_pos _ H theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a := suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from λ a b, match b, eq_coe_or_neg b with | ._, ⟨n, or.inl rfl⟩ := this _ _ | ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this end, λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact coe_nat_le_coe_nat_of_le (match a, n with | (m : ℕ), n := nat.div_le_self _ _ | -[1+ m], 0 := nat.zero_le _ | -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _) end) theorem div_le_self {a : ℤ} (b : ℤ) (Ha : 0 ≤ a) : a / b ≤ a := by have := le_trans (le_abs_self _) (abs_div_le_abs a b); rwa [abs_of_nonneg Ha] at this theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := by have := mod_add_div a b; rwa [H, zero_add] at this theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H] lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 := have h : n % 2 < 2 := abs_of_nonneg (show 0 ≤ (2 : ℤ), from dec_trivial) ▸ int.mod_lt _ dec_trivial, have h₁ : 0 ≤ n % 2 := int.mod_nonneg _ dec_trivial, match (n % 2), h, h₁ with | (0 : ℕ) := λ _ _, or.inl rfl | (1 : ℕ) := λ _ _, or.inr rfl | (k + 2 : ℕ) := λ h _, absurd h dec_trivial | -[1+ a] := λ _ h₁, absurd h₁ dec_trivial end /- dvd -/ @[norm_cast] theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n := ⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim (λm0, by simp [m0] at ae; simp [ae, m0]) (λm0l, by { cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a (by simp [ae.symm]) (by simpa using m0l)) with k e, subst a, exact ⟨k, int.coe_nat_inj ae⟩ }), λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩ theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem dvd_antisymm {a b : ℤ} (H1 : 0 ≤ a) (H2 : 0 ≤ b) : a ∣ b → b ∣ a → a = b := begin rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs], rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'], apply nat.dvd_antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b := ⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩ theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0 | a ._ ⟨c, rfl⟩ := mul_mod_right _ _ theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ /-- If `a % b = c` then `b` divides `a - c`. -/ lemma dvd_sub_of_mod_eq {a b c : ℤ} (h : a % b = c) : b ∣ a - c := begin have hx : a % b % b = c % b, { rw h }, rw [mod_mod, ←mod_sub_cancel_right c, sub_self, zero_mod] at hx, exact dvd_of_mod_eq_zero hx end theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b := (nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e]) theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b := (nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e]) instance decidable_dvd : @decidable_rel ℤ (∣) := assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := by rw [mul_comm, int.div_mul_cancel H] protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c) | ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz] theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a | a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az]; apply dvd_mul_right protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, int.mul_div_cancel' H1] protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := by rw [H2, int.mul_div_cancel_left _ H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2] protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2]) theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b) | ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz] lemma add_div_of_dvd {a b c : ℤ} : c ∣ a → c ∣ b → (a + b) / c = a / c + b / c := begin intros h1 h2, by_cases h3 : c = 0, { rw [h3, zero_dvd_iff] at *, rw [h1, h2, h3], refl }, { apply eq_of_mul_eq_mul_right h3, rw add_mul, repeat {rw [int.div_mul_cancel]}; try {apply dvd_add}; assumption } end theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := if az : a = 0 then by simp [az] else (int.div_eq_of_eq_mul_left (mt eq_zero_of_abs_eq_zero az) (sign_mul_abs _).symm).symm theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ theorem le_of_dvd {a b : ℤ} (bpos : 0 < b) (H : a ∣ b) : a ≤ b := match a, b, eq_succ_of_zero_lt bpos, H with | (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $ nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H | -[1+ m], ._, ⟨n, rfl⟩, _ := le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _) end theorem eq_one_of_dvd_one {a : ℤ} (H : 0 ≤ a) (H' : a ∣ 1) : a = 1 := match a, eq_coe_of_zero_le H, H' with | ._, ⟨n, rfl⟩, H' := congr_arg coe $ nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H' end theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : 0 ≤ a) (H' : a * b = 1) : a = 1 := eq_one_of_dvd_one H ⟨b, H'.symm⟩ theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : 0 ≤ b) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (by rw [mul_comm, H']) lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z | (int.of_nat _) haz := int.coe_nat_dvd.2 haz | -[1+k] haz := begin change ↑a ∣ -(k+1 : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, exact haz end lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs | (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz) | -[1+k] haz := have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz, int.coe_nat_dvd.1 haz' lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) : ↑(p ^ m) ∣ k := begin induction k, { apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1 hdiv }, { change -[1+k] with -(↑(k+1) : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1, apply dvd_of_dvd_neg, exact hdiv } end lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m := by rw ←nat.pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk /- / and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H protected theorem div_le_of_le_mul {a b c : ℤ} (H : 0 < c) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : 0 < c) (H3 : a < b / c) : a * c < b := lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3) protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : 0 < c) (H2 : a ≤ b / c) : a * c ≤ b := le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1)) protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : 0 < c) (H2 : a * c ≤ b) : a ≤ b / c := le_of_lt_add_one $ lt_of_mul_lt_mul_right (lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1) protected theorem le_div_iff_mul_le {a b c : ℤ} (H : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩ protected theorem div_le_div {a b c : ℤ} (H : 0 < c) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : 0 < c) (H' : a < b * c) : a / c < b := lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H') protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : 0 < c) (H2 : a / c < b) : a < b * c := lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2) protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : 0 < c) : a / c < b ↔ a < b * c := ⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩ protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1 protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ c) (H3 : a * b < c) : a < c / b := lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3) protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : 0 < c) (H' : c ∣ b) : a < b / c ↔ a * c < b := ⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩ theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : 0 < a) (H2 : 0 ≤ b) (H3 : b ∣ a) : 0 < a / b := int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul) theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := int.div_eq_of_eq_mul_right H3 $ by rw [← int.mul_div_assoc _ H2]; exact (int.div_eq_of_eq_mul_left H4 H5.symm).symm theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hbc : b ∣ c) (h : b * a = c * d) : a = c / b * d := begin cases hbc with k hk, subst hk, rw int.mul_div_cancel_left, rw mul_assoc at h, apply _root_.eq_of_mul_eq_mul_left _ h, repeat {assumption} end /-- If an integer with larger absolute value divides an integer, it is zero. -/ lemma eq_zero_of_dvd_of_nat_abs_lt_nat_abs {a b : ℤ} (w : a ∣ b) (h : nat_abs b < nat_abs a) : b = 0 := begin rw [←nat_abs_dvd, ←dvd_nat_abs, coe_nat_dvd] at w, rw ←nat_abs_eq_zero, exact eq_zero_of_dvd_of_lt w h end lemma eq_zero_of_dvd_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) (h : b ∣ a) : a = 0 := eq_zero_of_dvd_of_nat_abs_lt_nat_abs h (nat_abs_lt_nat_abs_of_nonneg_of_lt w₁ w₂) /-- If two integers are congruent to a sufficiently large modulus, they are equal. -/ lemma eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs {a b c : ℤ} (h1 : a % b = c) (h2 : nat_abs (a - c) < nat_abs b) : a = c := eq_of_sub_eq_zero (eq_zero_of_dvd_of_nat_abs_lt_nat_abs (dvd_sub_of_mod_eq h1) h2) theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = (n - m).succ, apply succ_sub, apply le_of_lt_succ h, simp [*, sub_nat_nat] end theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ} (h : n.succ ≤ m) : of_nat m + -[1+n] = of_nat (m - n.succ) := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = 0, apply sub_eq_zero_of_le h, simp [*, sub_nat_nat] end @[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl /- to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] lemma to_nat_sub_of_le (a b : ℤ) (h : b ≤ a) : (to_nat (a + -b) : ℤ) = a + - b := int.to_nat_of_nonneg (sub_nonneg_of_le h) @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp] theorem to_nat_le {a : ℤ} {n : ℕ} : to_nat a ≤ n ↔ a ≤ n := by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff]; exact and_iff_left (coe_zero_le _) @[simp] theorem lt_to_nat {n : ℕ} {a : ℤ} : n < to_nat a ↔ (n : ℤ) < a := le_iff_le_iff_lt_iff_lt.1 to_nat_le theorem to_nat_le_to_nat {a b : ℤ} (h : a ≤ b) : to_nat a ≤ to_nat b := by rw to_nat_le; exact le_trans h (le_to_nat b) theorem to_nat_lt_to_nat {a b : ℤ} (hb : 0 < b) : to_nat a < to_nat b ↔ a < b := ⟨λ h, begin cases a, exact lt_to_nat.1 h, exact lt_trans (neg_succ_of_nat_lt_zero a) hb, end, λ h, begin rw lt_to_nat, cases a, exact h, exact hb end⟩ theorem lt_of_to_nat_lt {a b : ℤ} (h : to_nat a < to_nat b) : a < b := (to_nat_lt_to_nat $ lt_to_nat.1 $ lt_of_le_of_lt (nat.zero_le _) h).1 h def to_nat' : ℤ → option ℕ | (n : ℕ) := some n | -[1+ n] := none theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n | (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm | -[1+ m] n := by split; intro h; cases h /- units -/ @[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 := units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹, by rw [← nat_abs_mul, units.mul_inv]; refl, by rw [← nat_abs_mul, units.inv_mul]; refl⟩ theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 := by simpa [units.ext_iff, units_nat_abs] using nat_abs_eq u lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) /- bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl @[simp] lemma bodd_two : bodd 2 = ff := rfl @[simp, norm_cast] lemma bodd_coe (n : ℕ) : int.bodd n = nat.bodd n := rfl @[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd := by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros; simp; cases i.bodd; simp @[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd := by cases n; simp; refl @[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe] @[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, -of_nat_eq_coe, bool.bxor_comm] @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; unfold has_mul.mul; simp [int.mul, -of_nat_eq_coe, bool.bxor_comm] theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl @[simp] lemma div2_bit (b n) : div2 (bit b n) = n := begin rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add], cases b, all_goals {exact dec_trivial} end @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n) | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n) | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (nat.pos_pow_of_pos _ dec_trivial) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ /- Least upper bound property for integers -/ section classical open_locale classical theorem exists_least_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) := let ⟨b, Hb⟩ := Hbdd in have EX : ∃ n : ℕ, P (b + n), from let ⟨elt, Helt⟩ := Hinh in match elt, le.dest (Hb _ Helt), Helt with | ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩ end, ⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h, match z, le.dest (Hb _ h), h with | ._, ⟨n, rfl⟩, h := add_le_add_left (int.coe_nat_le.2 $ nat.find_min' _ h) _ end⟩ theorem exists_greatest_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) := have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩, have Hinh' : ∃ z : ℤ, P (-z), from let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩, let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in ⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩ end classical /- cast (injection into groups with one) -/ @[simp, push_cast] theorem nat_cast_eq_coe_nat : ∀ n, @coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n = @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n | 0 := rfl | (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n) /-- Coercion `ℕ → ℤ` as a `ring_hom`. -/ def of_nat_hom : ℕ →+* ℤ := ⟨coe, rfl, int.of_nat_mul, rfl, int.of_nat_add⟩ section cast variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] [has_neg α] /-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/ protected def cast : ℤ → α | (n : ℕ) := n | -[1+ n] := -(n+1) -- see Note [coercion into rings] @[priority 900] instance cast_coe : has_coe_t ℤ α := ⟨int.cast⟩ @[simp, norm_cast] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl @[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl theorem cast_coe_nat' (n : ℕ) : (@coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n : α) = n := by simp @[simp, norm_cast] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl end @[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] [has_neg α] : ((1 : ℤ) : α) = 1 := nat.cast_one @[simp, norm_cast] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) : ((int.sub_nat_nat m n : ℤ) : α) = m - n := begin unfold sub_nat_nat, cases e : n - m, { simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] }, { rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e, nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] }, end @[simp, norm_cast] theorem cast_neg_of_nat [add_group α] [has_one α] : ∀ n, ((neg_of_nat n : ℤ) : α) = -n | 0 := neg_zero.symm | (n+1) := rfl @[simp, norm_cast] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n | (m : ℕ) (n : ℕ) := nat.cast_add _ _ | (m : ℕ) -[1+ n] := cast_sub_nat_nat _ _ | -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $ show (n:α) = -(m+1) + n + (m+1), by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm, nat.cast_add, cast_succ, neg_add_cancel_left] | -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1), begin rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add], apply congr_arg (λ x:ℕ, -(x:α)), ac_refl end @[simp, norm_cast] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n | (n : ℕ) := cast_neg_of_nat _ | -[1+ n] := (neg_neg _).symm @[simp, norm_cast] theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n := by simp [sub_eq_add_neg] @[simp] theorem cast_eq_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) = 0 ↔ n = 0 := ⟨λ h, begin cases n, { exact congr_arg coe (nat.cast_eq_zero.1 h) }, { rw [cast_neg_succ_of_nat, neg_eq_zero, ← cast_succ, nat.cast_eq_zero] at h, contradiction } end, λ h, by rw [h, cast_zero]⟩ @[simp, norm_cast] theorem cast_inj [add_group α] [has_one α] [char_zero α] {m n : ℤ} : (m : α) = n ↔ m = n := by rw [← sub_eq_zero, ← cast_sub, cast_eq_zero, sub_eq_zero] theorem cast_injective [add_group α] [has_one α] [char_zero α] : function.injective (coe : ℤ → α) | m n := cast_inj.1 theorem cast_ne_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp, norm_cast] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n | (m : ℕ) (n : ℕ) := nat.cast_mul _ _ | (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $ show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg] | -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $ show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n, by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul] | -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg] /-- `coe : ℤ → α` as an `add_monoid_hom`. -/ def cast_add_hom (α : Type*) [add_group α] [has_one α] : ℤ →+ α := ⟨coe, cast_zero, cast_add⟩ @[simp] lemma coe_cast_add_hom [add_group α] [has_one α] : ⇑(cast_add_hom α) = coe := rfl /-- `coe : ℤ → α` as a `ring_hom`. -/ def cast_ring_hom (α : Type*) [ring α] : ℤ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ @[simp] lemma coe_cast_ring_hom [ring α] : ⇑(cast_ring_hom α) = coe := rfl lemma cast_commute [ring α] (m : ℤ) (x : α) : commute ↑m x := int.cases_on m (λ n, n.cast_commute x) (λ n, ((n+1).cast_commute x).neg_left) lemma commute_cast [ring α] (x : α) (m : ℤ) : commute x m := (m.cast_commute x).symm @[simp, norm_cast] theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n := by {unfold bit0, simp} @[simp, norm_cast] theorem coe_nat_bit1 (n : ℕ) : (↑(bit1 n) : ℤ) = bit1 ↑n := by {unfold bit1, unfold bit0, simp} @[simp, norm_cast] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl lemma cast_two [ring α] : ((2 : ℤ) : α) = 2 := by simp theorem cast_nonneg [linear_ordered_ring α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n | (n : ℕ) := by simp | -[1+ n] := by simpa [not_le_of_gt (neg_succ_lt_zero n)] using show -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one @[simp, norm_cast] theorem cast_le [linear_ordered_ring α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp, norm_cast] theorem cast_lt [linear_ordered_ring α] {m n : ℤ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_ring α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_ring α] {n : ℤ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_ring α] {n : ℤ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp, norm_cast] theorem cast_min [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp, norm_cast] theorem cast_max [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp, norm_cast] theorem cast_abs [decidable_linear_ordered_comm_ring α] {q : ℤ} : ((abs q : ℤ) : α) = abs q := by simp [abs] end cast section decidable /-- List enumerating `[m, n)`. -/ def range (m n : ℤ) : list ℤ := (list.range (to_nat (n-m))).map $ λ r, m+r theorem mem_range_iff {m n r : ℤ} : r ∈ range m n ↔ m ≤ r ∧ r < n := ⟨λ H, let ⟨s, h1, h2⟩ := list.mem_map.1 H in h2 ▸ ⟨le_add_of_nonneg_right trivial, add_lt_of_lt_sub_left $ match n-m, h1 with | (k:ℕ), h1 := by rwa [list.mem_range, to_nat_coe_nat, ← coe_nat_lt] at h1 end⟩, λ ⟨h1, h2⟩, list.mem_map.2 ⟨to_nat (r-m), list.mem_range.2 $ by rw [← coe_nat_lt, to_nat_of_nonneg (sub_nonneg_of_le h1), to_nat_of_nonneg (sub_nonneg_of_le (le_of_lt (lt_of_le_of_lt h1 h2)))]; exact sub_lt_sub_right h2 _, show m + _ = _, by rw [to_nat_of_nonneg (sub_nonneg_of_le h1), add_sub_cancel'_right]⟩⟩ instance decidable_le_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r < n → P r) := decidable_of_iff (∀ r ∈ range m n, P r) $ by simp only [mem_range_iff, and_imp] instance decidable_le_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r ≤ n → P r) := decidable_of_iff (∀ r ∈ range m (n+1), P r) $ by simp only [mem_range_iff, and_imp, lt_add_one_iff] instance decidable_lt_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r < n → P r) := int.decidable_le_lt P _ _ instance decidable_lt_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r ≤ n → P r) := int.decidable_le_le P _ _ end decidable end int open int namespace add_monoid_hom variables {A : Type*} /-- Two additive monoid homomorphisms `f`, `g` from `ℤ` to an additive monoid are equal if `f 1 = g 1`. -/ @[ext] theorem ext_int [add_monoid A] {f g : ℤ →+ A} (h1 : f 1 = g 1) : f = g := have f.comp (int.of_nat_hom : ℕ →+ ℤ) = g.comp (int.of_nat_hom : ℕ →+ ℤ) := ext_nat h1, have ∀ n : ℕ, f n = g n := ext_iff.1 this, ext $ λ n, int.cases_on n this $ λ n, eq_on_neg (this $ n + 1) variables [add_group A] [has_one A] theorem eq_int_cast_hom (f : ℤ →+ A) (h1 : f 1 = 1) : f = int.cast_add_hom A := ext_int $ by simp [h1] theorem eq_int_cast (f : ℤ →+ A) (h1 : f 1 = 1) : ∀ n : ℤ, f n = n := ext_iff.1 (f.eq_int_cast_hom h1) end add_monoid_hom namespace ring_hom variables {α : Type*} {β : Type*} [ring α] [ring β] @[simp] lemma eq_int_cast (f : ℤ →+* α) (n : ℤ) : f n = n := f.to_add_monoid_hom.eq_int_cast f.map_one n lemma eq_int_cast' (f : ℤ →+* α) : f = int.cast_ring_hom α := ring_hom.ext f.eq_int_cast @[simp] lemma map_int_cast (f : α →+* β) (n : ℤ) : f n = n := (f.comp (int.cast_ring_hom α)).eq_int_cast n lemma ext_int {R : Type*} [semiring R] (f g : ℤ →+* R) : f = g := coe_add_monoid_hom_injective $ add_monoid_hom.ext_int $ f.map_one.trans g.map_one.symm instance int.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℤ →+* R) := ⟨ring_hom.ext_int⟩ end ring_hom @[simp, norm_cast] theorem int.cast_id (n : ℤ) : ↑n = n := ((ring_hom.id ℤ).eq_int_cast n).symm
a441cb7e88db09883b52f2e1d596e3e15891632b
367134ba5a65885e863bdc4507601606690974c1
/src/tactic/omega/term.lean
de2e3cd34ea02364445e553a4f6a23b9db2c4858
[ "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
2,675
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ /- Normalized linear integer arithmetic terms. -/ import tactic.omega.coeffs namespace omega /-- Shadow syntax of normalized terms. The first element represents the constant term and the list represents the coefficients. -/ @[derive inhabited] def term : Type := int × list int namespace term /-- Evaluate a term using the valuation v. -/ @[simp] def val (v : nat → int) : term → int | (b,as) := b + coeffs.val v as @[simp] def neg : term → term | (b,as) := (-b, list.func.neg as) @[simp] def add : term → term → term | (c1,cfs1) (c2,cfs2) := (c1+c2, list.func.add cfs1 cfs2) @[simp] def sub : term → term → term | (c1,cfs1) (c2,cfs2) := (c1 - c2, list.func.sub cfs1 cfs2) @[simp] def mul (i : int) : term → term | (b,as) := (i * b, as.map ((*) i)) @[simp] def div (i : int) : term → term | (b,as) := (b/i, as.map (λ x, x / i)) lemma val_neg {v : nat → int} {t : term} : (neg t).val v = -(t.val v) := begin cases t with b as, simp only [val, neg_add, neg, val, coeffs.val_neg] end @[simp] lemma val_sub {v : nat → int} {t1 t2 : term} : (sub t1 t2).val v = t1.val v - t2.val v := begin cases t1, cases t2, simp only [add_assoc, coeffs.val_sub, neg_add_rev, val, sub, add_comm, add_left_comm, sub_eq_add_neg] end @[simp] lemma val_add {v : nat → int} {t1 t2 : term} : (add t1 t2).val v = t1.val v + t2.val v := begin cases t1, cases t2, simp only [coeffs.val_add, add, val, add_comm, add_left_comm] end @[simp] lemma val_mul {v : nat → int} {i : int} {t : term} : val v (mul i t) = i * (val v t) := begin cases t, simp only [mul, mul_add, add_mul, list.length_map, coeffs.val, coeffs.val_between_map_mul, val, list.map] end lemma val_div {v : nat → int} {i b : int} {as : list int} : i ∣ b → (∀ x ∈ as, i ∣ x) → (div i (b,as)).val v = (val v (b,as)) / i := begin intros h1 h2, simp only [val, div, list.map], rw [int.add_div_of_dvd_left h1], apply fun_mono_2 rfl, rw ← coeffs.val_map_div h2 end /-- Fresh de Brujin index not used by any variable ocurring in the term -/ def fresh_index (t : term) : nat := t.snd.length def to_string (t : term) : string := t.2.enum.foldr (λ ⟨i, n⟩ r, to_string n ++ " * x" ++ to_string i ++ " + " ++ r) (to_string t.1) instance : has_to_string term := ⟨to_string⟩ end term /-- Fresh de Brujin index not used by any variable ocurring in the list of terms -/ def terms.fresh_index : list term → nat | [] := 0 | (t::ts) := max t.fresh_index (terms.fresh_index ts) end omega
f90e2cd68e43e649227fa10029a46e1a654b64ec
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/logic/relation.lean
249e24aef2306fcba58dbdd2593c46c6371db122
[ "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
20,557
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 -/ import tactic.basic import logic.relator /-! # Relation closures This file defines the reflexive, transitive, and reflexive transitive closures of relations. It also proves some basic results on definitions in core, such as `eqv_gen`. Note that this is about unbundled relations, that is terms of types of the form `α → β → Prop`. For the bundled version, see `rel`. ## Definitions * `relation.refl_gen`: Reflexive closure. `refl_gen r` relates everything `r` related, plus for all `a` it relates `a` with itself. So `refl_gen r a b ↔ r a b ∨ a = b`. * `relation.trans_gen`: Transitive closure. `trans_gen r` relates everything `r` related transitively. So `trans_gen r a b ↔ ∃ x₀ ... xₙ, r a x₀ ∧ r x₀ x₁ ∧ ... ∧ r xₙ b`. * `relation.refl_trans_gen`: Reflexive transitive closure. `refl_trans_gen r` relates everything `r` related transitively, plus for all `a` it relates `a` with itself. So `refl_trans_gen r a b ↔ (∃ x₀ ... xₙ, r a x₀ ∧ r x₀ x₁ ∧ ... ∧ r xₙ b) ∨ a = b`. It is the same as the reflexive closure of the transitive closure, or the transitive closure of the reflexive closure. In terms of rewriting systems, this means that `a` can be rewritten to `b` in a number of rewrites. * `relation.comp`: Relation composition. We provide notation `∘r`. For `r : α → β → Prop` and `s : β → γ → Prop`, `r ∘r s`relates `a : α` and `c : γ` iff there exists `b : β` that's related to both. * `relation.map`: Image of a relation under a pair of maps. For `r : α → β → Prop`, `f : α → γ`, `g : β → δ`, `map r f g` is the relation `γ → δ → Prop` relating `f a` and `g b` for all `a`, `b` related by `r`. * `relation.join`: Join of a relation. For `r : α → α → Prop`, `join r a b ↔ ∃ c, r a c ∧ r b c`. In terms of rewriting systems, this means that `a` and `b` can be rewritten to the same term. -/ open function variables {α β γ δ : Type*} section ne_imp variable {r : α → α → Prop} lemma is_refl.reflexive [is_refl α r] : reflexive r := λ x, is_refl.refl x /-- To show a reflexive relation `r : α → α → Prop` holds over `x y : α`, it suffices to show it holds when `x ≠ y`. -/ lemma reflexive.rel_of_ne_imp (h : reflexive r) {x y : α} (hr : x ≠ y → r x y) : r x y := begin by_cases hxy : x = y, { exact hxy ▸ h x }, { exact hr hxy } end /-- If a reflexive relation `r : α → α → Prop` holds over `x y : α`, then it holds whether or not `x ≠ y`. -/ lemma reflexive.ne_imp_iff (h : reflexive r) {x y : α} : (x ≠ y → r x y) ↔ r x y := ⟨h.rel_of_ne_imp, λ hr _, hr⟩ /-- If a reflexive relation `r : α → α → Prop` holds over `x y : α`, then it holds whether or not `x ≠ y`. Unlike `reflexive.ne_imp_iff`, this uses `[is_refl α r]`. -/ lemma reflexive_ne_imp_iff [is_refl α r] {x y : α} : (x ≠ y → r x y) ↔ r x y := is_refl.reflexive.ne_imp_iff protected lemma symmetric.iff (H : symmetric r) (x y : α) : r x y ↔ r y x := ⟨λ h, H h, λ h, H h⟩ end ne_imp section comap variables {r : β → β → Prop} lemma reflexive.comap (h : reflexive r) (f : α → β) : reflexive (r on f) := λ a, h (f a) lemma symmetric.comap (h : symmetric r) (f : α → β) : symmetric (r on f) := λ a b hab, h hab lemma transitive.comap (h : transitive r) (f : α → β) : transitive (r on f) := λ a b c hab hbc, h hab hbc lemma equivalence.comap (h : equivalence r) (f : α → β) : equivalence (r on f) := ⟨h.1.comap f, h.2.1.comap f, h.2.2.comap f⟩ end comap namespace relation section comp variables {r : α → β → Prop} {p : β → γ → Prop} {q : γ → δ → Prop} /-- The composition of two relations, yielding a new relation. The result relates a term of `α` and a term of `γ` if there is an intermediate term of `β` related to both. -/ def comp (r : α → β → Prop) (p : β → γ → Prop) (a : α) (c : γ) : Prop := ∃ b, r a b ∧ p b c local infixr ` ∘r ` : 80 := relation.comp lemma comp_eq : r ∘r (=) = r := funext $ λ a, funext $ λ b, propext $ iff.intro (λ ⟨c, h, eq⟩, eq ▸ h) (λ h, ⟨b, h, rfl⟩) lemma eq_comp : (=) ∘r r = r := funext $ λ a, funext $ λ b, propext $ iff.intro (λ ⟨c, eq, h⟩, eq.symm ▸ h) (λ h, ⟨a, rfl, h⟩) lemma iff_comp {r : Prop → α → Prop} : (↔) ∘r r = r := have (↔) = (=), by funext a b; exact iff_eq_eq, by rw [this, eq_comp] lemma comp_iff {r : α → Prop → Prop} : r ∘r (↔) = r := have (↔) = (=), by funext a b; exact iff_eq_eq, by rw [this, comp_eq] lemma comp_assoc : (r ∘r p) ∘r q = r ∘r p ∘r q := begin funext a d, apply propext, split, exact λ ⟨c, ⟨b, hab, hbc⟩, hcd⟩, ⟨b, hab, c, hbc, hcd⟩, exact λ ⟨b, hab, c, hbc, hcd⟩, ⟨c, ⟨b, hab, hbc⟩, hcd⟩ end lemma flip_comp : flip (r ∘r p) = (flip p) ∘r (flip r) := begin funext c a, apply propext, split, exact λ ⟨b, hab, hbc⟩, ⟨b, hbc, hab⟩, exact λ ⟨b, hbc, hab⟩, ⟨b, hab, hbc⟩ end end comp /-- The map of a relation `r` through a pair of functions pushes the relation to the codomains of the functions. The resulting relation is defined by having pairs of terms related if they have preimages related by `r`. -/ protected def map (r : α → β → Prop) (f : α → γ) (g : β → δ) : γ → δ → Prop := λ c d, ∃ a b, r a b ∧ f a = c ∧ g b = d variables {r : α → α → Prop} {a b c d : α} /-- `refl_trans_gen r`: reflexive transitive closure of `r` -/ @[mk_iff relation.refl_trans_gen.cases_tail_iff] inductive refl_trans_gen (r : α → α → Prop) (a : α) : α → Prop | refl : refl_trans_gen a | tail {b c} : refl_trans_gen b → r b c → refl_trans_gen c attribute [refl] refl_trans_gen.refl /-- `refl_gen r`: reflexive closure of `r` -/ @[mk_iff] inductive refl_gen (r : α → α → Prop) (a : α) : α → Prop | refl : refl_gen a | single {b} : r a b → refl_gen b /-- `trans_gen r`: transitive closure of `r` -/ @[mk_iff] inductive trans_gen (r : α → α → Prop) (a : α) : α → Prop | single {b} : r a b → trans_gen b | tail {b c} : trans_gen b → r b c → trans_gen c attribute [refl] refl_gen.refl namespace refl_gen lemma to_refl_trans_gen : ∀ {a b}, refl_gen r a b → refl_trans_gen r a b | a _ refl := by refl | a b (single h) := refl_trans_gen.tail refl_trans_gen.refl h lemma mono {p : α → α → Prop} (hp : ∀ a b, r a b → p a b) : ∀ {a b}, refl_gen r a b → refl_gen p a b | a _ refl_gen.refl := by refl | a b (single h) := single (hp a b h) end refl_gen namespace refl_trans_gen @[trans] lemma trans (hab : refl_trans_gen r a b) (hbc : refl_trans_gen r b c) : refl_trans_gen r a c := begin induction hbc, case refl_trans_gen.refl { assumption }, case refl_trans_gen.tail : c d hbc hcd hac { exact hac.tail hcd } end lemma single (hab : r a b) : refl_trans_gen r a b := refl.tail hab lemma head (hab : r a b) (hbc : refl_trans_gen r b c) : refl_trans_gen r a c := begin induction hbc, case refl_trans_gen.refl { exact refl.tail hab }, case refl_trans_gen.tail : c d hbc hcd hac { exact hac.tail hcd } end lemma symmetric (h : symmetric r) : symmetric (refl_trans_gen r) := begin intros x y h, induction h with z w a b c, { refl }, { apply relation.refl_trans_gen.head (h b) c } end lemma cases_tail : refl_trans_gen r a b → b = a ∨ (∃ c, refl_trans_gen r a c ∧ r c b) := (cases_tail_iff r a b).1 @[elab_as_eliminator] lemma head_induction_on {P : ∀ (a:α), refl_trans_gen r a b → Prop} {a : α} (h : refl_trans_gen r a b) (refl : P b refl) (head : ∀ {a c} (h' : r a c) (h : refl_trans_gen r c b), P c h → P a (h.head h')) : P a h := begin induction h generalizing P, case refl_trans_gen.refl { exact refl }, case refl_trans_gen.tail : b c hab hbc ih { apply ih, show P b _, from head hbc _ refl, show ∀ a a', r a a' → refl_trans_gen r a' b → P a' _ → P a _, from λ a a' hab hbc, head hab _ } end @[elab_as_eliminator] lemma trans_induction_on {P : ∀ {a b : α}, refl_trans_gen r a b → Prop} {a b : α} (h : refl_trans_gen r a b) (ih₁ : ∀ a, @P a a refl) (ih₂ : ∀ {a b} (h : r a b), P (single h)) (ih₃ : ∀ {a b c} (h₁ : refl_trans_gen r a b) (h₂ : refl_trans_gen r b c), P h₁ → P h₂ → P (h₁.trans h₂)) : P h := begin induction h, case refl_trans_gen.refl { exact ih₁ a }, case refl_trans_gen.tail : b c hab hbc ih { exact ih₃ hab (single hbc) ih (ih₂ hbc) } end lemma cases_head (h : refl_trans_gen r a b) : a = b ∨ (∃ c, r a c ∧ refl_trans_gen r c b) := begin induction h using relation.refl_trans_gen.head_induction_on, { left, refl }, { right, existsi _, split; assumption } end lemma cases_head_iff : refl_trans_gen r a b ↔ a = b ∨ (∃ c, r a c ∧ refl_trans_gen r c b) := begin use cases_head, rintro (rfl | ⟨c, hac, hcb⟩), { refl }, { exact head hac hcb } end lemma total_of_right_unique (U : relator.right_unique r) (ab : refl_trans_gen r a b) (ac : refl_trans_gen r a c) : refl_trans_gen r b c ∨ refl_trans_gen r c b := begin induction ab with b d ab bd IH, { exact or.inl ac }, { rcases IH with IH | IH, { rcases cases_head IH with rfl | ⟨e, be, ec⟩, { exact or.inr (single bd) }, { cases U bd be, exact or.inl ec } }, { exact or.inr (IH.tail bd) } } end end refl_trans_gen namespace trans_gen lemma to_refl {a b} (h : trans_gen r a b) : refl_trans_gen r a b := begin induction h with b h b c _ bc ab, exact refl_trans_gen.single h, exact refl_trans_gen.tail ab bc end @[trans] lemma trans_left (hab : trans_gen r a b) (hbc : refl_trans_gen r b c) : trans_gen r a c := begin induction hbc, case refl_trans_gen.refl : { assumption }, case refl_trans_gen.tail : c d hbc hcd hac { exact hac.tail hcd } end @[trans] lemma trans (hab : trans_gen r a b) (hbc : trans_gen r b c) : trans_gen r a c := trans_left hab hbc.to_refl lemma head' (hab : r a b) (hbc : refl_trans_gen r b c) : trans_gen r a c := trans_left (single hab) hbc lemma tail' (hab : refl_trans_gen r a b) (hbc : r b c) : trans_gen r a c := begin induction hab generalizing c, case refl_trans_gen.refl : c hac { exact single hac }, case refl_trans_gen.tail : d b hab hdb IH { exact tail (IH hdb) hbc } end lemma head (hab : r a b) (hbc : trans_gen r b c) : trans_gen r a c := head' hab hbc.to_refl @[elab_as_eliminator] lemma head_induction_on {P : ∀ (a:α), trans_gen r a b → Prop} {a : α} (h : trans_gen r a b) (base : ∀ {a} (h : r a b), P a (single h)) (ih : ∀ {a c} (h' : r a c) (h : trans_gen r c b), P c h → P a (h.head h')) : P a h := begin induction h generalizing P, case single : a h { exact base h }, case tail : b c hab hbc h_ih { apply h_ih, show ∀ a, r a b → P a _, from λ a h, ih h (single hbc) (base hbc), show ∀ a a', r a a' → trans_gen r a' b → P a' _ → P a _, from λ a a' hab hbc, ih hab _ } end @[elab_as_eliminator] lemma trans_induction_on {P : ∀ {a b : α}, trans_gen r a b → Prop} {a b : α} (h : trans_gen r a b) (base : ∀ {a b} (h : r a b), P (single h)) (ih : ∀ {a b c} (h₁ : trans_gen r a b) (h₂ : trans_gen r b c), P h₁ → P h₂ → P (h₁.trans h₂)) : P h := begin induction h, case single : a h { exact base h }, case tail : b c hab hbc h_ih { exact ih hab (single hbc) h_ih (base hbc) } end @[trans] lemma trans_right (hab : refl_trans_gen r a b) (hbc : trans_gen r b c) : trans_gen r a c := begin induction hbc, case trans_gen.single : c hbc { exact tail' hab hbc }, case trans_gen.tail : c d hbc hcd hac { exact hac.tail hcd } end lemma tail'_iff : trans_gen r a c ↔ ∃ b, refl_trans_gen r a b ∧ r b c := begin refine ⟨λ h, _, λ ⟨b, hab, hbc⟩, tail' hab hbc⟩, cases h with _ hac b _ hab hbc, { exact ⟨_, by refl, hac⟩ }, { exact ⟨_, hab.to_refl, hbc⟩ } end lemma head'_iff : trans_gen r a c ↔ ∃ b, r a b ∧ refl_trans_gen r b c := begin refine ⟨λ h, _, λ ⟨b, hab, hbc⟩, head' hab hbc⟩, induction h, case trans_gen.single : c hac { exact ⟨_, hac, by refl⟩ }, case trans_gen.tail : b c hab hbc IH { rcases IH with ⟨d, had, hdb⟩, exact ⟨_, had, hdb.tail hbc⟩ } end end trans_gen section trans_gen lemma trans_gen_eq_self (trans : transitive r) : trans_gen r = r := funext $ λ a, funext $ λ b, propext $ ⟨λ h, begin induction h, case trans_gen.single : c hc { exact hc }, case trans_gen.tail : c d hac hcd hac { exact trans hac hcd } end, trans_gen.single⟩ lemma transitive_trans_gen : transitive (trans_gen r) := λ a b c, trans_gen.trans lemma trans_gen_idem : trans_gen (trans_gen r) = trans_gen r := trans_gen_eq_self transitive_trans_gen lemma trans_gen.lift {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀ a b, r a b → p (f a) (f b)) (hab : trans_gen r a b) : trans_gen p (f a) (f b) := begin induction hab, case trans_gen.single : c hac { exact trans_gen.single (h a c hac) }, case trans_gen.tail : c d hac hcd hac { exact trans_gen.tail hac (h c d hcd) } end lemma trans_gen.lift' {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀ a b, r a b → trans_gen p (f a) (f b)) (hab : trans_gen r a b) : trans_gen p (f a) (f b) := by simpa [trans_gen_idem] using hab.lift f h lemma trans_gen.closed {p : α → α → Prop} : (∀ a b, r a b → trans_gen p a b) → trans_gen r a b → trans_gen p a b := trans_gen.lift' id lemma trans_gen.mono {p : α → α → Prop} : (∀ a b, r a b → p a b) → trans_gen r a b → trans_gen p a b := trans_gen.lift id lemma trans_gen.swap (h : trans_gen r b a) : trans_gen (swap r) a b := by { induction h with b h b c hab hbc ih, { exact trans_gen.single h }, exact ih.head hbc } lemma trans_gen_swap : trans_gen (swap r) a b ↔ trans_gen r b a := ⟨trans_gen.swap, trans_gen.swap⟩ end trans_gen section refl_trans_gen open refl_trans_gen lemma refl_trans_gen_iff_eq (h : ∀ b, ¬ r a b) : refl_trans_gen r a b ↔ b = a := by rw [cases_head_iff]; simp [h, eq_comm] lemma refl_trans_gen_iff_eq_or_trans_gen : refl_trans_gen r a b ↔ b = a ∨ trans_gen r a b := begin refine ⟨λ h, _, λ h, _⟩, { cases h with c _ hac hcb, { exact or.inl rfl }, { exact or.inr (trans_gen.tail' hac hcb) } }, { rcases h with rfl | h, {refl}, {exact h.to_refl} } end lemma refl_trans_gen.lift {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀ a b, r a b → p (f a) (f b)) (hab : refl_trans_gen r a b) : refl_trans_gen p (f a) (f b) := refl_trans_gen.trans_induction_on hab (λ a, refl) (λ a b, refl_trans_gen.single ∘ h _ _) (λ a b c _ _, trans) lemma refl_trans_gen.mono {p : α → α → Prop} : (∀ a b, r a b → p a b) → refl_trans_gen r a b → refl_trans_gen p a b := refl_trans_gen.lift id lemma refl_trans_gen_eq_self (refl : reflexive r) (trans : transitive r) : refl_trans_gen r = r := funext $ λ a, funext $ λ b, propext $ ⟨λ h, begin induction h with b c h₁ h₂ IH, {apply refl}, exact trans IH h₂, end, single⟩ lemma reflexive_refl_trans_gen : reflexive (refl_trans_gen r) := λ a, refl lemma transitive_refl_trans_gen : transitive (refl_trans_gen r) := λ a b c, trans lemma refl_trans_gen_idem : refl_trans_gen (refl_trans_gen r) = refl_trans_gen r := refl_trans_gen_eq_self reflexive_refl_trans_gen transitive_refl_trans_gen lemma refl_trans_gen.lift' {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀ a b, r a b → refl_trans_gen p (f a) (f b)) (hab : refl_trans_gen r a b) : refl_trans_gen p (f a) (f b) := by simpa [refl_trans_gen_idem] using hab.lift f h lemma refl_trans_gen_closed {p : α → α → Prop} : (∀ a b, r a b → refl_trans_gen p a b) → refl_trans_gen r a b → refl_trans_gen p a b := refl_trans_gen.lift' id lemma refl_trans_gen.swap (h : refl_trans_gen r b a) : refl_trans_gen (swap r) a b := by { induction h with b c hab hbc ih, { refl }, exact ih.head hbc } lemma refl_trans_gen_swap : refl_trans_gen (swap r) a b ↔ refl_trans_gen r b a := ⟨refl_trans_gen.swap, refl_trans_gen.swap⟩ end refl_trans_gen /-- The join of a relation on a single type is a new relation for which pairs of terms are related if there is a third term they are both related to. For example, if `r` is a relation representing rewrites in a term rewriting system, then *confluence* is the property that if `a` rewrites to both `b` and `c`, then `join r` relates `b` and `c` (see `relation.church_rosser`). -/ def join (r : α → α → Prop) : α → α → Prop := λ a b, ∃ c, r a c ∧ r b c section join open refl_trans_gen refl_gen /-- A sufficient condition for the Church-Rosser property. -/ lemma church_rosser (h : ∀ a b c, r a b → r a c → ∃ d, refl_gen r b d ∧ refl_trans_gen r c d) (hab : refl_trans_gen r a b) (hac : refl_trans_gen r a c) : join (refl_trans_gen r) b c := begin induction hab, case refl_trans_gen.refl { exact ⟨c, hac, refl⟩ }, case refl_trans_gen.tail : d e had hde ih { clear hac had a, rcases ih with ⟨b, hdb, hcb⟩, have : ∃ a, refl_trans_gen r e a ∧ refl_gen r b a, { clear hcb, induction hdb, case refl_trans_gen.refl { exact ⟨e, refl, refl_gen.single hde⟩ }, case refl_trans_gen.tail : f b hdf hfb ih { rcases ih with ⟨a, hea, hfa⟩, cases hfa with _ hfa, { exact ⟨b, hea.tail hfb, refl_gen.refl⟩ }, { rcases h _ _ _ hfb hfa with ⟨c, hbc, hac⟩, exact ⟨c, hea.trans hac, hbc⟩ } } }, rcases this with ⟨a, hea, hba⟩, cases hba with _ hba, { exact ⟨b, hea, hcb⟩ }, { exact ⟨a, hea, hcb.tail hba⟩ } } end lemma join_of_single (h : reflexive r) (hab : r a b) : join r a b := ⟨b, hab, h b⟩ lemma symmetric_join : symmetric (join r) := λ a b ⟨c, hac, hcb⟩, ⟨c, hcb, hac⟩ lemma reflexive_join (h : reflexive r) : reflexive (join r) := λ a, ⟨a, h a, h a⟩ lemma transitive_join (ht : transitive r) (h : ∀ a b c, r a b → r a c → join r b c) : transitive (join r) := λ a b c ⟨x, hax, hbx⟩ ⟨y, hby, hcy⟩, let ⟨z, hxz, hyz⟩ := h b x y hbx hby in ⟨z, ht hax hxz, ht hcy hyz⟩ lemma equivalence_join (hr : reflexive r) (ht : transitive r) (h : ∀ a b c, r a b → r a c → join r b c) : equivalence (join r) := ⟨reflexive_join hr, symmetric_join, transitive_join ht h⟩ lemma equivalence_join_refl_trans_gen (h : ∀ a b c, r a b → r a c → ∃ d, refl_gen r b d ∧ refl_trans_gen r c d) : equivalence (join (refl_trans_gen r)) := equivalence_join reflexive_refl_trans_gen transitive_refl_trans_gen (λ a b c, church_rosser h) lemma join_of_equivalence {r' : α → α → Prop} (hr : equivalence r) (h : ∀ a b, r' a b → r a b) : join r' a b → r a b | ⟨c, hac, hbc⟩ := hr.2.2 (h _ _ hac) (hr.2.1 $ h _ _ hbc) lemma refl_trans_gen_of_transitive_reflexive {r' : α → α → Prop} (hr : reflexive r) (ht : transitive r) (h : ∀ a b, r' a b → r a b) (h' : refl_trans_gen r' a b) : r a b := begin induction h' with b c hab hbc ih, { exact hr _ }, { exact ht ih (h _ _ hbc) } end lemma refl_trans_gen_of_equivalence {r' : α → α → Prop} (hr : equivalence r) : (∀ a b, r' a b → r a b) → refl_trans_gen r' a b → r a b := refl_trans_gen_of_transitive_reflexive hr.1 hr.2.2 end join end relation section eqv_gen variables {r : α → α → Prop} {a b : α} lemma equivalence.eqv_gen_iff (h : equivalence r) : eqv_gen r a b ↔ r a b := iff.intro begin intro h, induction h, case eqv_gen.rel { assumption }, case eqv_gen.refl { exact h.1 _ }, case eqv_gen.symm { apply h.2.1, assumption }, case eqv_gen.trans : a b c _ _ hab hbc { exact h.2.2 hab hbc } end (eqv_gen.rel a b) lemma equivalence.eqv_gen_eq (h : equivalence r) : eqv_gen r = r := funext $ λ _, funext $ λ _, propext $ h.eqv_gen_iff lemma eqv_gen.mono {r p : α → α → Prop} (hrp : ∀ a b, r a b → p a b) (h : eqv_gen r a b) : eqv_gen p a b := begin induction h, case eqv_gen.rel : a b h { exact eqv_gen.rel _ _ (hrp _ _ h) }, case eqv_gen.refl : { exact eqv_gen.refl _ }, case eqv_gen.symm : a b h ih { exact eqv_gen.symm _ _ ih }, case eqv_gen.trans : a b c ih1 ih2 hab hbc { exact eqv_gen.trans _ _ _ hab hbc } end end eqv_gen
60f80fb7af2ad13c8742ff46fe4fa120dd76702d
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/is_connected.lean
bec73cf91a3598f154815073347d05bd220d50b4
[ "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
12,870
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import data.list.chain import category_theory.punit /-! # Connected category Define a connected category as a _nonempty_ category for which every functor to a discrete category is isomorphic to the constant functor. NB. Some authors include the empty category as connected, we do not. We instead are interested in categories with exactly one 'connected component'. We give some equivalent definitions: - A nonempty category for which every functor to a discrete category is constant on objects. See `any_functor_const_on_obj` and `connected.of_any_functor_const_on_obj`. - A nonempty category for which every function `F` for which the presence of a morphism `f : j₁ ⟶ j₂` implies `F j₁ = F j₂` must be constant everywhere. See `constant_of_preserves_morphisms` and `connected.of_constant_of_preserves_morphisms`. - A nonempty category for which any subset of its elements containing the default and closed under morphisms is everything. See `induct_on_objects` and `connected.of_induct`. - A nonempty category for which every object is related under the reflexive transitive closure of the relation "there is a morphism in some direction from `j₁` to `j₂`". See `connected_zigzag` and `zigzag_connected`. - A nonempty category for which for any two objects there is a sequence of morphisms (some reversed) from one to the other. See `exists_zigzag'` and `connected_of_zigzag`. We also prove the result that the functor given by `(X × -)` preserves any connected limit. That is, any limit of shape `J` where `J` is a connected category is preserved by the functor `(X × -)`. This appears in `category_theory.limits.connected`. -/ universes v₁ v₂ u₁ u₂ noncomputable theory open category_theory.category namespace category_theory /-- A possibly empty category for which every functor to a discrete category is constant. -/ class is_preconnected (J : Type u₁) [category.{v₁} J] : Prop := (iso_constant : Π {α : Type u₁} (F : J ⥤ discrete α) (j : J), nonempty (F ≅ (functor.const J).obj (F.obj j))) /-- We define a connected category as a _nonempty_ category for which every functor to a discrete category is constant. NB. Some authors include the empty category as connected, we do not. We instead are interested in categories with exactly one 'connected component'. This allows us to show that the functor X ⨯ - preserves connected limits. See https://stacks.math.columbia.edu/tag/002S -/ class is_connected (J : Type u₁) [category.{v₁} J] extends is_preconnected J : Prop := [is_nonempty : nonempty J] attribute [instance, priority 100] is_connected.is_nonempty variables {J : Type u₁} [category.{v₁} J] variables {K : Type u₂} [category.{v₂} K] /-- If `J` is connected, any functor `F : J ⥤ discrete α` is isomorphic to the constant functor with value `F.obj j` (for any choice of `j`). -/ def iso_constant [is_preconnected J] {α : Type u₁} (F : J ⥤ discrete α) (j : J) : F ≅ (functor.const J).obj (F.obj j) := (is_preconnected.iso_constant F j).some /-- If J is connected, any functor to a discrete category is constant on objects. The converse is given in `is_connected.of_any_functor_const_on_obj`. -/ lemma any_functor_const_on_obj [is_preconnected J] {α : Type u₁} (F : J ⥤ discrete α) (j j' : J) : F.obj j = F.obj j' := ((iso_constant F j').hom.app j).down.1 /-- If any functor to a discrete category is constant on objects, J is connected. The converse of `any_functor_const_on_obj`. -/ lemma is_connected.of_any_functor_const_on_obj [nonempty J] (h : ∀ {α : Type u₁} (F : J ⥤ discrete α), ∀ (j j' : J), F.obj j = F.obj j') : is_connected J := { iso_constant := λ α F j', ⟨nat_iso.of_components (λ j, eq_to_iso (h F j j')) (λ _ _ _, subsingleton.elim _ _)⟩ } /-- If `J` is connected, then given any function `F` such that the presence of a morphism `j₁ ⟶ j₂` implies `F j₁ = F j₂`, we have that `F` is constant. This can be thought of as a local-to-global property. The converse is shown in `is_connected.of_constant_of_preserves_morphisms` -/ lemma constant_of_preserves_morphisms [is_preconnected J] {α : Type u₁} (F : J → α) (h : ∀ (j₁ j₂ : J) (f : j₁ ⟶ j₂), F j₁ = F j₂) (j j' : J) : F j = F j' := any_functor_const_on_obj { obj := F, map := λ _ _ f, eq_to_hom (h _ _ f) } j j' /-- `J` is connected if: given any function `F : J → α` which is constant for any `j₁, j₂` for which there is a morphism `j₁ ⟶ j₂`, then `F` is constant. This can be thought of as a local-to-global property. The converse of `constant_of_preserves_morphisms`. -/ lemma is_connected.of_constant_of_preserves_morphisms [nonempty J] (h : ∀ {α : Type u₁} (F : J → α), (∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), F j₁ = F j₂) → (∀ j j' : J, F j = F j')) : is_connected J := is_connected.of_any_functor_const_on_obj (λ _ F, h F.obj (λ _ _ f, (F.map f).down.1)) /-- An inductive-like property for the objects of a connected category. If the set `p` is nonempty, and `p` is closed under morphisms of `J`, then `p` contains all of `J`. The converse is given in `is_connected.of_induct`. -/ lemma induct_on_objects [is_preconnected J] (p : set J) {j₀ : J} (h0 : j₀ ∈ p) (h1 : ∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), j₁ ∈ p ↔ j₂ ∈ p) (j : J) : j ∈ p := begin injection (constant_of_preserves_morphisms (λ k, ulift.up (k ∈ p)) (λ j₁ j₂ f, _) j j₀) with i, rwa i, dsimp, exact congr_arg ulift.up (propext (h1 f)), end /-- If any maximal connected component containing some element j₀ of J is all of J, then J is connected. The converse of `induct_on_objects`. -/ lemma is_connected.of_induct [nonempty J] {j₀ : J} (h : ∀ (p : set J), j₀ ∈ p → (∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), j₁ ∈ p ↔ j₂ ∈ p) → ∀ (j : J), j ∈ p) : is_connected J := is_connected.of_constant_of_preserves_morphisms (λ α F a, begin have w := h {j | F j = F j₀} rfl (λ _ _ f, by simp [a f]), dsimp at w, intros j j', rw [w j, w j'], end) /-- Another induction principle for `is_preconnected J`: given a type family `Z : J → Sort*` and a rule for transporting in *both* directions along a morphism in `J`, we can transport an `x : Z j₀` to a point in `Z j` for any `j`. -/ lemma is_preconnected_induction [is_preconnected J] (Z : J → Sort*) (h₁ : Π {j₁ j₂ : J} (f : j₁ ⟶ j₂), Z j₁ → Z j₂) (h₂ : Π {j₁ j₂ : J} (f : j₁ ⟶ j₂), Z j₂ → Z j₁) {j₀ : J} (x : Z j₀) (j : J) : nonempty (Z j) := (induct_on_objects {j | nonempty (Z j)} ⟨x⟩ (λ j₁ j₂ f, ⟨by { rintro ⟨y⟩, exact ⟨h₁ f y⟩, }, by { rintro ⟨y⟩, exact ⟨h₂ f y⟩, }⟩) j : _) /-- If `J` and `K` are equivalent, then if `J` is preconnected then `K` is as well. -/ lemma is_preconnected_of_equivalent {K : Type u₁} [category.{v₂} K] [is_preconnected J] (e : J ≌ K) : is_preconnected K := { iso_constant := λ α F k, ⟨ calc F ≅ e.inverse ⋙ e.functor ⋙ F : (e.inv_fun_id_assoc F).symm ... ≅ e.inverse ⋙ (functor.const J).obj ((e.functor ⋙ F).obj (e.inverse.obj k)) : iso_whisker_left e.inverse (iso_constant (e.functor ⋙ F) (e.inverse.obj k)) ... ≅ e.inverse ⋙ (functor.const J).obj (F.obj k) : iso_whisker_left _ ((F ⋙ functor.const J).map_iso (e.counit_iso.app k)) ... ≅ (functor.const K).obj (F.obj k) : nat_iso.of_components (λ X, iso.refl _) (by simp), ⟩ } /-- If `J` and `K` are equivalent, then if `J` is connected then `K` is as well. -/ lemma is_connected_of_equivalent {K : Type u₁} [category.{v₂} K] (e : J ≌ K) [is_connected J] : is_connected K := { is_nonempty := nonempty.map e.functor.obj (by apply_instance), to_is_preconnected := is_preconnected_of_equivalent e } /-- j₁ and j₂ are related by `zag` if there is a morphism between them. -/ @[reducible] def zag (j₁ j₂ : J) : Prop := nonempty (j₁ ⟶ j₂) ∨ nonempty (j₂ ⟶ j₁) lemma zag_symmetric : symmetric (@zag J _) := λ j₂ j₁ h, h.swap /-- `j₁` and `j₂` are related by `zigzag` if there is a chain of morphisms from `j₁` to `j₂`, with backward morphisms allowed. -/ @[reducible] def zigzag : J → J → Prop := relation.refl_trans_gen zag lemma zigzag_symmetric : symmetric (@zigzag J _) := relation.refl_trans_gen.symmetric zag_symmetric lemma zigzag_equivalence : _root_.equivalence (@zigzag J _) := mk_equivalence _ relation.reflexive_refl_trans_gen zigzag_symmetric relation.transitive_refl_trans_gen /-- The setoid given by the equivalence relation `zigzag`. A quotient for this setoid is a connected component of the category. -/ def zigzag.setoid (J : Type u₂) [category.{v₁} J] : setoid J := { r := zigzag, iseqv := zigzag_equivalence } /-- If there is a zigzag from `j₁` to `j₂`, then there is a zigzag from `F j₁` to `F j₂` as long as `F` is a functor. -/ lemma zigzag_obj_of_zigzag (F : J ⥤ K) {j₁ j₂ : J} (h : zigzag j₁ j₂) : zigzag (F.obj j₁) (F.obj j₂) := begin refine relation.refl_trans_gen_lift _ _ h, intros j k, exact or.imp (nonempty.map (λ f, F.map f)) (nonempty.map (λ f, F.map f)) end -- TODO: figure out the right way to generalise this to `zigzag`. lemma zag_of_zag_obj (F : J ⥤ K) [full F] {j₁ j₂ : J} (h : zag (F.obj j₁) (F.obj j₂)) : zag j₁ j₂ := or.imp (nonempty.map F.preimage) (nonempty.map F.preimage) h /-- Any equivalence relation containing (⟶) holds for all pairs of a connected category. -/ lemma equiv_relation [is_connected J] (r : J → J → Prop) (hr : _root_.equivalence r) (h : ∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), r j₁ j₂) : ∀ (j₁ j₂ : J), r j₁ j₂ := begin have z : ∀ (j : J), r (classical.arbitrary J) j := induct_on_objects (λ k, r (classical.arbitrary J) k) (hr.1 (classical.arbitrary J)) (λ _ _ f, ⟨λ t, hr.2.2 t (h f), λ t, hr.2.2 t (hr.2.1 (h f))⟩), intros, apply hr.2.2 (hr.2.1 (z _)) (z _) end /-- In a connected category, any two objects are related by `zigzag`. -/ lemma is_connected_zigzag [is_connected J] (j₁ j₂ : J) : zigzag j₁ j₂ := equiv_relation _ zigzag_equivalence (λ _ _ f, relation.refl_trans_gen.single (or.inl (nonempty.intro f))) _ _ /-- If any two objects in an nonempty category are related by `zigzag`, the category is connected. -/ lemma zigzag_is_connected [nonempty J] (h : ∀ (j₁ j₂ : J), zigzag j₁ j₂) : is_connected J := begin apply is_connected.of_induct, intros p hp hjp j, have: ∀ (j₁ j₂ : J), zigzag j₁ j₂ → (j₁ ∈ p ↔ j₂ ∈ p), { introv k, induction k with _ _ rt_zag zag, { refl }, { rw k_ih, rcases zag with ⟨⟨_⟩⟩ | ⟨⟨_⟩⟩, apply hjp zag, apply (hjp zag).symm } }, rwa this j (classical.arbitrary J) (h _ _) end lemma exists_zigzag' [is_connected J] (j₁ j₂ : J) : ∃ l, list.chain zag j₁ l ∧ list.last (j₁ :: l) (list.cons_ne_nil _ _) = j₂ := list.exists_chain_of_relation_refl_trans_gen (is_connected_zigzag _ _) /-- If any two objects in an nonempty category are linked by a sequence of (potentially reversed) morphisms, then J is connected. The converse of `exists_zigzag'`. -/ lemma is_connected_of_zigzag [nonempty J] (h : ∀ (j₁ j₂ : J), ∃ l, list.chain zag j₁ l ∧ list.last (j₁ :: l) (list.cons_ne_nil _ _) = j₂) : is_connected J := begin apply zigzag_is_connected, intros j₁ j₂, rcases h j₁ j₂ with ⟨l, hl₁, hl₂⟩, apply list.relation_refl_trans_gen_of_exists_chain l hl₁ hl₂, end /-- If `discrete α` is connected, then `α` is (type-)equivalent to `punit`. -/ def discrete_is_connected_equiv_punit {α : Type*} [is_connected (discrete α)] : α ≃ punit := discrete.equiv_of_equivalence { functor := functor.star α, inverse := discrete.functor (λ _, classical.arbitrary _), unit_iso := by { exact (iso_constant _ (classical.arbitrary _)), }, counit_iso := functor.punit_ext _ _ } variables {C : Type u₂} [category.{u₁} C] /-- For objects `X Y : C`, any natural transformation `α : const X ⟶ const Y` from a connected category must be constant. This is the key property of connected categories which we use to establish properties about limits. -/ lemma nat_trans_from_is_connected [is_preconnected J] {X Y : C} (α : (functor.const J).obj X ⟶ (functor.const J).obj Y) : ∀ (j j' : J), α.app j = (α.app j' : X ⟶ Y) := @constant_of_preserves_morphisms _ _ _ (X ⟶ Y) (λ j, α.app j) (λ _ _ f, (by { have := α.naturality f, erw [id_comp, comp_id] at this, exact this.symm })) end category_theory
47526e14cd1ee7ed74dc13a97e7d2929c30f969b
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/balanced.lean
c1277508f7cef5ff1bad8ba3054001235a03dc13
[ "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
1,440
lean
/- Copyright (c) 2022 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.epi_mono /-! # Balanced categories A category is called balanced if any morphism that is both monic and epic is an isomorphism. Balanced categories arise frequently. For example, categories in which every monomorphism (or epimorphism) is strong are balanced. Examples of this are abelian categories and toposes, such as the category of types. -/ universes v u namespace category_theory variables {C : Type u} [category.{v} C] section variables (C) /-- A category is called balanced if any morphism that is both monic and epic is an isomorphism. -/ class balanced : Prop := (is_iso_of_mono_of_epi : ∀ {X Y : C} (f : X ⟶ Y) [mono f] [epi f], is_iso f) end lemma is_iso_of_mono_of_epi [balanced C] {X Y : C} (f : X ⟶ Y) [mono f] [epi f] : is_iso f := balanced.is_iso_of_mono_of_epi _ lemma is_iso_iff_mono_and_epi [balanced C] {X Y : C} (f : X ⟶ Y) : is_iso f ↔ mono f ∧ epi f := ⟨λ _, by exactI ⟨infer_instance, infer_instance⟩, λ ⟨_, _⟩, by exactI is_iso_of_mono_of_epi _⟩ section local attribute [instance] is_iso_of_mono_of_epi lemma balanced_opposite [balanced C] : balanced Cᵒᵖ := { is_iso_of_mono_of_epi := λ X Y f fmono fepi, by { rw ← quiver.hom.op_unop f, exactI is_iso_of_op _ } } end end category_theory
bbeb15377692290d87a13c23c9bb6068be86e95f
f68c8823d8ddc719de8a4513815174aa7408ac4a
/lean_resolutions/PUZ031_1.lean
416b063c960ed296aaeed1839b85943875819c4a
[]
no_license
FredsoNerd/tptp-lean-puzzles
e7ea66a0de9aa3cb7cc7480299f01adf885440a6
43d4d77524e797a4ac7a62b2cfaf8df08b409815
refs/heads/master
1,606,359,611,765
1,576,824,274,000
1,576,824,274,000
228,945,807
4
0
null
null
null
null
UTF-8
Lean
false
false
3,645
lean
-------------------------------------------------------------------------------- -- File : PUZ031_1 : TPTP v7.3.0. Released v5.0.0. -- Domain : Puzzles -- Problem : Schubert's Steamroller -- Version : Especial. -- English : Wolves, foxes, birds, caterpillars, and snails are animals, and -- there are some of each of them. Also there are some grains, and -- grains are plants. Every animal either likes to eat all plants -- or all animals much smaller than itself that like to eat some -- plants. Caterpillars and snails are much smaller than birds, -- which are much smaller than foxes, which in turn are much -- smaller than wolves. Wolves do not like to eat foxes or grains, -- while birds like to eat caterpillars but not snails. -- Caterpillars and snails like to eat some plants. Therefore -- there is an animal that likes to eat a grain eating animal. -- Source : [TPTP] -------------------------------------------------------------------------------- variable animal: Type variable wolf: Type variable wolf_to_animal: wolf → animal variable fox: Type variable fox_to_animal: fox → animal variable bird: Type variable bird_to_animal: bird → animal variable caterpillar: Type variable caterpillar_to_animal: caterpillar → animal variable snail: Type variable snail_to_animal: snail → animal variable plant: Type variable grain: Type variable grain_to_plant: grain → plant variable edible: Type variable animal_to_edible: animal → edible variable plant_to_edible: plant → edible variable eats: animal × edible → Prop variable much_smaller: animal × animal → Prop -- existence variable existence : ∀ A : Type, A -- axioms variable pel47_7: ∀ (X: animal), (∀ (Y: plant), eats(X,plant_to_edible(Y))) ∨ (∃ Y1: animal, (much_smaller(Y1,X) ∧ ∃ Z: plant, eats(Y1,plant_to_edible(Z))) → eats(X,animal_to_edible(Y1))) variable pel47_8: ∀ (X: snail) (Y: bird), much_smaller(snail_to_animal(X),bird_to_animal(Y)) variable pel47_8a: ∀ (X: caterpillar) (Y: bird), much_smaller(caterpillar_to_animal(X),bird_to_animal(Y)) variable pel47_9: ∀ (X: bird) (Y: fox), much_smaller(bird_to_animal(X),fox_to_animal(Y)) variable pel47_10: ∀ (X: fox) (Y: wolf), much_smaller(fox_to_animal(X),wolf_to_animal(Y)) variable pel47_11: ∀ (X: wolf) (Y: fox), ¬ eats(wolf_to_animal(X),animal_to_edible(fox_to_animal(Y))) variable pel47_11a: ∀ (X: wolf) (Y: grain), ¬ eats(wolf_to_animal(X),plant_to_edible(grain_to_plant(Y))) variable pel47_12: ∀ (X: bird) (Y: caterpillar), eats(bird_to_animal(X),animal_to_edible(caterpillar_to_animal(Y))) variable pel47_13: ∀ (X: bird) (Y: snail), ¬ eats(bird_to_animal(X),animal_to_edible(snail_to_animal(Y))) variable pel47_14: ∀ (X: caterpillar), ∃ (Y: plant), eats(caterpillar_to_animal(X),plant_to_edible(Y)) variable pel47_14a: ∀ (X: snail), ∃ (Y: plant), eats(snail_to_animal(X),plant_to_edible(Y)) -- conjecture : pel47 include existence include pel47_7 pel47_11a include wolf wolf_to_animal caterpillar include grain grain_to_plant theorem pel47: ∃ (X: animal) (Y: animal) (Z: grain), (eats(Y,plant_to_edible(grain_to_plant(Z))) ∧ eats(X,animal_to_edible(Y))) := begin have ex_wolf : wolf, from existence _, cases pel47_7 (wolf_to_animal ex_wolf), have ex_grain : grain, from existence _, have wolf_eats_grain, from h (grain_to_plant ex_grain), have not_wolf_eats_grain, from (pel47_11a ex_wolf ex_grain), contradiction, exact sorry end
7170f3f66f8a5ce62de598abe2eba78582a89e12
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/ring_theory/noetherian.lean
7acf7aa2a911f373500719bb2d16c176028fa73e
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
21,133
lean
/- Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import ring_theory.ideal.operations import linear_algebra.basis import order.order_iso_nat /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodule M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set open_locale big_operators namespace submodule variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ /-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢, rw [ring_hom.map_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_group P] [module R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩ theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨linear_map.inl R M P '' tb ∪ linear_map.inr R M P '' tc, (htb.1.image _).union (htc.1.image _), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ variable (f) /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [ring R] [add_comm_group M] [module R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, trivial, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices : ∀ s : finset ι, is_noetherian R (Π i : (↑s : set ι), M i), { letI := this finset.univ, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (this finset.univ), { exact λ f i, f ⟨i, finset.mem_univ _⟩ }, { intros, ext, refl }, { intros, ext, refl }, { exact λ f i, f i.1 }, { intro, ext ⟨⟩, refl }, { intro, ext i, refl } }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext ⟨i, his⟩, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext ⟨i, hi⟩, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], refl }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], refl } } end end open is_noetherian submodule function theorem is_noetherian_iff_well_founded {R M} [ring R] [add_comm_group M] [module R M] : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := ⟨λ h, begin apply rel_embedding.well_founded_iff_no_descending_seq.2, swap, { apply is_strict_order.swap }, rintro ⟨⟨N, hN⟩⟩, let Q := ⨆ n, N n, resetI, rcases submodule.fg_def.1 (noetherian Q) with ⟨t, h₁, h₂⟩, have hN' : ∀ {a b}, a ≤ b → N a ≤ N b := λ a b, (strict_mono.le_iff_le (λ _ _, hN.1)).2, have : t ⊆ ⋃ i, (N i : set M), { rw [← submodule.coe_supr_of_directed N _], { show t ⊆ Q, rw ← h₂, apply submodule.subset_span }, { exact λ i j, ⟨max i j, hN' (le_max_left _ _), hN' (le_max_right _ _)⟩ } }, simp [subset_def] at this, choose f hf using show ∀ x : t, ∃ (i : ℕ), x.1 ∈ N i, { simpa }, cases h₁ with h₁, let A := finset.sup (@finset.univ t h₁) f, have : Q ≤ N A, { rw ← h₂, apply submodule.span_le.2, exact λ x h, hN' (finset.le_sup (@finset.mem_univ t h₁ _)) (hf ⟨x, h⟩) }, exact not_le_of_lt (hN.1 (nat.lt_succ_self A)) (le_trans (le_supr _ _) this) end, begin assume h, split, assume N, suffices : ∀ P ≤ N, ∃ s, finite s ∧ P ⊔ submodule.span R s = N, { rcases this ⊥ bot_le with ⟨s, hs, e⟩, exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ }, refine λ P, h.induction P _, intros P IH PN, letI := classical.dec, by_cases h : ∀ x, x ∈ N → x ∈ P, { cases le_antisymm PN h, exact ⟨∅, by simp⟩ }, { simp [not_forall] at h, rcases h with ⟨x, h, h₂⟩, have : ¬P ⊔ submodule.span R {x} ≤ P, { intro hn, apply h₂, have := le_trans le_sup_right hn, exact submodule.span_le.1 this (mem_singleton x) }, rcases IH (P ⊔ submodule.span R {x}) ⟨@le_sup_left _ _ P _, this⟩ (sup_le PN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩, refine ⟨insert x s, hs.insert x, _⟩, rw [← hs₂, sup_assoc, ← submodule.span_union], simp } end⟩ lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp lemma finite_of_linear_independent {R M} [comm_ring R] [nontrivial R] [add_comm_group M] [module R M] [is_noetherian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, rel_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff hs (this a) (this b), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them. -/ theorem set_has_maximal_iff_noetherian {R M} [ring R] [add_comm_group M] [module R M] : (∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, M' ≤ I → I = M') ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.well_founded_iff_has_max'] /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ @[class] def is_noetherian_ring (R) [ring R] : Prop := is_noetherian R R instance is_noetherian_ring.to_is_noetherian {R : Type*} [ring R] : ∀ [is_noetherian_ring R], is_noetherian R R := id @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one h01; haveI := fintype.of_subsingleton (0:R); exact ring.is_noetherian_of_fintype _ _ theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.map_subtype.order_embedding N).dual h, end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.comap_mkq.order_embedding N).dual h, end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.semimodule _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin rw [is_noetherian_ring, is_noetherian_iff_well_founded] at H ⊢, exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H, end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring (set.range f) := is_noetherian_ring_of_surjective R (set.range f) (f.cod_restrict (set.range f) set.mem_range_self) set.surjective_onto_range theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, hfm.mul hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule
ab7fd00d25688606c8722ec63c8349db4b035b8e
2385ce0e3b60d8dbea33dd439902a2070cca7a24
/library/init/algebra/classes.lean
e0276ec4a85f96e84e2986f2c77b9fa6c0f9ff76
[ "Apache-2.0" ]
permissive
TehMillhouse/lean
68d6fdd2fb11a6c65bc28dec308d70f04dad38b4
6bbf2fbd8912617e5a973575bab8c383c9c268a1
refs/heads/master
1,620,830,893,339
1,515,592,479,000
1,515,592,997,000
116,964,828
0
0
null
1,515,592,734,000
1,515,592,734,000
null
UTF-8
Lean
false
false
11,694
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.logic init.data.ordering.basic universes u @[algebra] class is_commutative (α : Type u) (op : α → α → α) : Prop := (comm : ∀ a b, op a b = op b a) @[algebra] class is_associative (α : Type u) (op : α → α → α) : Prop := (assoc : ∀ a b c, op (op a b) c = op a (op b c)) @[algebra] class is_left_id (α : Type u) (op : α → α → α) (o : out_param α) : Prop := (left_id : ∀ a, op o a = a) @[algebra] class is_right_id (α : Type u) (op : α → α → α) (o : out_param α) : Prop := (right_id : ∀ a, op a o = a) @[algebra] class is_left_null (α : Type u) (op : α → α → α) (o : out_param α) : Prop := (left_null : ∀ a, op o a = o) @[algebra] class is_right_null (α : Type u) (op : α → α → α) (o : out_param α) : Prop := (right_null : ∀ a, op a o = o) @[algebra] class is_left_cancel (α : Type u) (op : α → α → α) : Prop := (left_cancel : ∀ a b c, op a b = op a c → b = c) @[algebra] class is_right_cancel (α : Type u) (op : α → α → α) : Prop := (right_cancel : ∀ a b c, op a b = op c b → a = c) @[algebra] class is_idempotent (α : Type u) (op : α → α → α) : Prop := (idempotent : ∀ a, op a a = a) @[algebra] class is_left_distrib (α : Type u) (op₁ : α → α → α) (op₂ : out_param $ α → α → α) : Prop := (left_distrib : ∀ a b c, op₁ a (op₂ b c) = op₂ (op₁ a b) (op₁ a c)) @[algebra] class is_right_distrib (α : Type u) (op₁ : α → α → α) (op₂ : out_param $ α → α → α) : Prop := (right_distrib : ∀ a b c, op₁ (op₂ a b) c = op₂ (op₁ a c) (op₁ b c)) @[algebra] class is_left_inv (α : Type u) (op : α → α → α) (inv : out_param α → α) (o : out_param $ α) : Prop := (left_inv : ∀ a, op (inv a) a = o) @[algebra] class is_right_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param $ α) : Prop := (right_inv : ∀ a, op a (inv a) = o) @[algebra] class is_cond_left_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param $ α) (p : out_param $ α → Prop) : Prop := (left_inv : ∀ a, p a → op (inv a) a = o) @[algebra] class is_cond_right_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param $ α) (p : out_param $ α → Prop) : Prop := (right_inv : ∀ a, p a → op a (inv a) = o) @[algebra] class is_distinct (α : Type u) (a : α) (b : α) : Prop := (distinct : a ≠ b) /- -- The following type class doesn't seem very useful, a regular simp lemma should work for this. class is_inv (α : Type u) (β : Type v) (f : α → β) (g : out β → α) : Prop := (inv : ∀ a, g (f a) = a) -- The following one can also be handled using a regular simp lemma class is_idempotent (α : Type u) (f : α → α) : Prop := (idempotent : ∀ a, f (f a) = f a) -/ @[algebra] class is_irrefl (α : Type u) (r : α → α → Prop) : Prop := (irrefl : ∀ a, ¬ r a a) @[algebra] class is_refl (α : Type u) (r : α → α → Prop) : Prop := (refl : ∀ a, r a a) @[algebra] class is_symm (α : Type u) (r : α → α → Prop) : Prop := (symm : ∀ a b, r a b → r b a) @[algebra] class is_asymm (α : Type u) (r : α → α → Prop) : Prop := (asymm : ∀ a b, r a b → ¬ r b a) @[algebra] class is_antisymm (α : Type u) (r : α → α → Prop) : Prop := (antisymm : ∀ a b, r a b → r b a → a = b) @[algebra] class is_trans (α : Type u) (r : α → α → Prop) : Prop := (trans : ∀ a b c, r a b → r b c → r a c) @[algebra] class is_total (α : Type u) (r : α → α → Prop) : Prop := (total : ∀ a b, r a b ∨ r b a) @[algebra] class is_preorder (α : Type u) (r : α → α → Prop) extends is_refl α r, is_trans α r : Prop. @[algebra] class is_total_preorder (α : Type u) (r : α → α → Prop) extends is_trans α r, is_total α r : Prop. instance is_total_preorder_is_preorder (α : Type u) (r : α → α → Prop) [s : is_total_preorder α r] : is_preorder α r := {trans := s.trans, refl := λ a, or.elim (is_total.total r a a) id id} @[algebra] class is_partial_order (α : Type u) (r : α → α → Prop) extends is_preorder α r, is_antisymm α r : Prop. @[algebra] class is_linear_order (α : Type u) (r : α → α → Prop) extends is_partial_order α r, is_total α r : Prop. @[algebra] class is_equiv (α : Type u) (r : α → α → Prop) extends is_preorder α r, is_symm α r : Prop. @[algebra] class is_per (α : Type u) (r : α → α → Prop) extends is_symm α r, is_trans α r : Prop. @[algebra] class is_strict_order (α : Type u) (r : α → α → Prop) extends is_irrefl α r, is_trans α r : Prop. @[algebra] class is_incomp_trans (α : Type u) (lt : α → α → Prop) : Prop := (incomp_trans : ∀ a b c, (¬ lt a b ∧ ¬ lt b a) → (¬ lt b c ∧ ¬ lt c b) → (¬ lt a c ∧ ¬ lt c a)) @[algebra] class is_strict_weak_order (α : Type u) (lt : α → α → Prop) extends is_strict_order α lt, is_incomp_trans α lt : Prop. @[algebra] class is_trichotomous (α : Type u) (lt : α → α → Prop) : Prop := (trichotomous : ∀ a b, lt a b ∨ a = b ∨ lt b a) @[algebra] class is_strict_total_order (α : Type u) (lt : α → α → Prop) extends is_trichotomous α lt, is_strict_weak_order α lt. instance eq_is_equiv (α : Type u) : is_equiv α (=) := {symm := @eq.symm _, trans := @eq.trans _, refl := eq.refl} section variables {α : Type u} {r : α → α → Prop} local infix `≺`:50 := r lemma irrefl [is_irrefl α r] (a : α) : ¬ a ≺ a := is_irrefl.irrefl _ a lemma refl [is_refl α r] (a : α) : a ≺ a := is_refl.refl _ a lemma trans [is_trans α r] {a b c : α} : a ≺ b → b ≺ c → a ≺ c := is_trans.trans _ _ _ lemma symm [is_symm α r] {a b : α} : a ≺ b → b ≺ a := is_symm.symm _ _ lemma antisymm [is_antisymm α r] {a b : α} : a ≺ b → b ≺ a → a = b := is_antisymm.antisymm _ _ lemma asymm [is_asymm α r] {a b : α} : a ≺ b → ¬ b ≺ a := is_asymm.asymm _ _ lemma trichotomous [is_trichotomous α r] : ∀ (a b : α), a ≺ b ∨ a = b ∨ b ≺ a := is_trichotomous.trichotomous r lemma incomp_trans [is_incomp_trans α r] {a b c : α} : (¬ a ≺ b ∧ ¬ b ≺ a) → (¬ b ≺ c ∧ ¬ c ≺ b) → (¬ a ≺ c ∧ ¬ c ≺ a) := is_incomp_trans.incomp_trans _ _ _ instance is_asymm_of_is_trans_of_is_irrefl [is_trans α r] [is_irrefl α r] : is_asymm α r := ⟨λ a b h₁ h₂, absurd (trans h₁ h₂) (irrefl a)⟩ section explicit_relation_variants variable (r) @[elab_simple] lemma irrefl_of [is_irrefl α r] (a : α) : ¬ a ≺ a := irrefl a @[elab_simple] lemma refl_of [is_refl α r] (a : α) : a ≺ a := refl a @[elab_simple] lemma trans_of [is_trans α r] {a b c : α} : a ≺ b → b ≺ c → a ≺ c := trans @[elab_simple] lemma symm_of [is_symm α r] {a b : α} : a ≺ b → b ≺ a := symm @[elab_simple] lemma asymm_of [is_asymm α r] {a b : α} : a ≺ b → ¬ b ≺ a := asymm @[elab_simple] lemma total_of [is_total α r] (a b : α) : a ≺ b ∨ b ≺ a := is_total.total _ _ _ @[elab_simple] lemma trichotomous_of [is_trichotomous α r] : ∀ (a b : α), a ≺ b ∨ a = b ∨ b ≺ a := trichotomous @[elab_simple] lemma incomp_trans_of [is_incomp_trans α r] {a b c : α} : (¬ a ≺ b ∧ ¬ b ≺ a) → (¬ b ≺ c ∧ ¬ c ≺ b) → (¬ a ≺ c ∧ ¬ c ≺ a) := incomp_trans end explicit_relation_variants end namespace strict_weak_order section parameters {α : Type u} {r : α → α → Prop} local infix `≺`:50 := r def equiv (a b : α) : Prop := ¬ a ≺ b ∧ ¬ b ≺ a parameter [is_strict_weak_order α r] local infix ` ≈ `:50 := equiv lemma erefl (a : α) : a ≈ a := ⟨irrefl a, irrefl a⟩ lemma esymm {a b : α} : a ≈ b → b ≈ a := λ ⟨h₁, h₂⟩, ⟨h₂, h₁⟩ lemma etrans {a b c : α} : a ≈ b → b ≈ c → a ≈ c := incomp_trans lemma not_lt_of_equiv {a b : α} : a ≈ b → ¬ a ≺ b := λ h, h.1 lemma not_lt_of_equiv' {a b : α} : a ≈ b → ¬ b ≺ a := λ h, h.2 instance : is_equiv α equiv := {refl := erefl, trans := @etrans, symm := @esymm} end /- Notation for the equivalence relation induced by lt -/ notation a ` ≈[`:50 lt `]` b:50 := @equiv _ lt a b end strict_weak_order lemma is_strict_weak_order_of_is_total_preorder {α : Type u} {le : α → α → Prop} {lt : α → α → Prop} [decidable_rel le] [s : is_total_preorder α le] (h : ∀ a b, lt a b ↔ ¬ le b a) : is_strict_weak_order α lt := { trans := λ a b c hab hbc, have nba : ¬ le b a, from iff.mp (h _ _) hab, have ncb : ¬ le c b, from iff.mp (h _ _) hbc, have hab : le a b, from or.resolve_left (total_of le b a) nba, have nca : ¬ le c a, from λ hca : le c a, have hcb : le c b, from trans_of le hca hab, absurd hcb ncb, iff.mpr (h _ _) nca, irrefl := λ a hlt, absurd (refl_of le a) (iff.mp (h _ _) hlt), incomp_trans := λ a b c ⟨nab, nba⟩ ⟨nbc, ncb⟩, have hba : le b a, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) nab), have hab : le a b, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) nba), have hcb : le c b, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) nbc), have hbc : le b c, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) ncb), have hac : le a c, from trans_of le hab hbc, have hca : le c a, from trans_of le hcb hba, and.intro (λ n, absurd hca (iff.mp (h _ _) n)) (λ n, absurd hac (iff.mp (h _ _) n)) } lemma lt_of_lt_of_incomp {α : Type u} {lt : α → α → Prop} [is_strict_weak_order α lt] [decidable_rel lt] : ∀ {a b c}, lt a b → (¬ lt b c ∧ ¬ lt c b) → lt a c := λ a b c hab ⟨nbc, ncb⟩, have nca : ¬ lt c a, from λ hca, absurd (trans_of lt hca hab) ncb, decidable.by_contradiction $ λ nac : ¬ lt a c, have ¬ lt a b ∧ ¬ lt b a, from incomp_trans_of lt ⟨nac, nca⟩ ⟨ncb, nbc⟩, absurd hab this.1 lemma lt_of_incomp_of_lt {α : Type u} {lt : α → α → Prop} [is_strict_weak_order α lt] [decidable_rel lt] : ∀ {a b c}, (¬ lt a b ∧ ¬ lt b a) → lt b c → lt a c := λ a b c ⟨nab, nba⟩ hbc, have nca : ¬ lt c a, from λ hca, absurd (trans_of lt hbc hca) nba, decidable.by_contradiction $ λ nac : ¬ lt a c, have ¬ lt b c ∧ ¬ lt c b, from incomp_trans_of lt ⟨nba, nab⟩ ⟨nac, nca⟩, absurd hbc this.1 lemma eq_of_incomp {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] {a b} : (¬ lt a b ∧ ¬ lt b a) → a = b := λ ⟨nab, nba⟩, match trichotomous_of lt a b with | or.inl hab := absurd hab nab | or.inr (or.inl hab) := hab | or.inr (or.inr hba) := absurd hba nba end lemma eq_of_eqv_lt {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] {a b} : a ≈[lt] b → a = b := eq_of_incomp lemma incomp_iff_eq {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] [is_irrefl α lt] (a b) : (¬ lt a b ∧ ¬ lt b a) ↔ a = b := iff.intro eq_of_incomp (λ hab, eq.subst hab (and.intro (irrefl_of lt a) (irrefl_of lt a))) lemma eqv_lt_iff_eq {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] [is_irrefl α lt] (a b) : a ≈[lt] b ↔ a = b := incomp_iff_eq a b lemma not_lt_of_lt {α : Type u} {lt : α → α → Prop} [is_strict_order α lt] {a b} : lt a b → ¬ lt b a := λ h₁ h₂, absurd (trans_of lt h₁ h₂) (irrefl_of lt _)
55786430c8aa95d0f3be0e6e20ec4e4a158db2c9
618003631150032a5676f229d13a079ac875ff77
/src/data/list/sigma.lean
63467a3ca56469f5b9608fac446fee991ad29343
[ "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
24,012
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Sean Leather Functions on lists of sigma types. -/ import data.list.perm import data.list.range import data.sigma universes u v namespace list variables {α : Type u} {β : α → Type v} /- keys -/ /-- List of keys from a list of key-value pairs -/ def keys : list (sigma β) → list α := map sigma.fst @[simp] theorem keys_nil : @keys α β [] = [] := rfl @[simp] theorem keys_cons {s} {l : list (sigma β)} : (s :: l).keys = s.1 :: l.keys := rfl theorem mem_keys_of_mem {s : sigma β} {l : list (sigma β)} : s ∈ l → s.1 ∈ l.keys := mem_map_of_mem sigma.fst theorem exists_of_mem_keys {a} {l : list (sigma β)} (h : a ∈ l.keys) : ∃ (b : β a), sigma.mk a b ∈ l := let ⟨⟨a', b'⟩, m, e⟩ := exists_of_mem_map h in eq.rec_on e (exists.intro b' m) theorem mem_keys {a} {l : list (sigma β)} : a ∈ l.keys ↔ ∃ (b : β a), sigma.mk a b ∈ l := ⟨exists_of_mem_keys, λ ⟨b, h⟩, mem_keys_of_mem h⟩ theorem not_mem_keys {a} {l : list (sigma β)} : a ∉ l.keys ↔ ∀ b : β a, sigma.mk a b ∉ l := (not_iff_not_of_iff mem_keys).trans not_exists theorem not_eq_key {a} {l : list (sigma β)} : a ∉ l.keys ↔ ∀ s : sigma β, s ∈ l → a ≠ s.1 := iff.intro (λ h₁ s h₂ e, absurd (mem_keys_of_mem h₂) (by rwa e at h₁)) (λ f h₁, let ⟨b, h₂⟩ := exists_of_mem_keys h₁ in f _ h₂ rfl) /- nodupkeys -/ def nodupkeys (l : list (sigma β)) : Prop := l.keys.nodup theorem nodupkeys_iff_pairwise {l} : nodupkeys l ↔ pairwise (λ s s' : sigma β, s.1 ≠ s'.1) l := pairwise_map _ theorem nodupkeys.pairwise_ne {l} (h : nodupkeys l) : pairwise (λ s s' : sigma β, s.1 ≠ s'.1) l := nodupkeys_iff_pairwise.1 h @[simp] theorem nodupkeys_nil : @nodupkeys α β [] := pairwise.nil @[simp] theorem nodupkeys_cons {s : sigma β} {l : list (sigma β)} : nodupkeys (s::l) ↔ s.1 ∉ l.keys ∧ nodupkeys l := by simp [keys, nodupkeys] theorem nodupkeys.eq_of_fst_eq {l : list (sigma β)} (nd : nodupkeys l) {s s' : sigma β} (h : s ∈ l) (h' : s' ∈ l) : s.1 = s'.1 → s = s' := @forall_of_forall_of_pairwise _ (λ s s' : sigma β, s.1 = s'.1 → s = s') (λ s s' H h, (H h.symm).symm) _ (λ x h _, rfl) ((nodupkeys_iff_pairwise.1 nd).imp (λ s s' h h', (h h').elim)) _ h _ h' theorem nodupkeys.eq_of_mk_mem {a : α} {b b' : β a} {l : list (sigma β)} (nd : nodupkeys l) (h : sigma.mk a b ∈ l) (h' : sigma.mk a b' ∈ l) : b = b' := by cases nd.eq_of_fst_eq h h' rfl; refl theorem nodupkeys_singleton (s : sigma β) : nodupkeys [s] := nodup_singleton _ theorem nodupkeys_of_sublist {l₁ l₂ : list (sigma β)} (h : l₁ <+ l₂) : nodupkeys l₂ → nodupkeys l₁ := nodup_of_sublist (h.map _) theorem nodup_of_nodupkeys {l : list (sigma β)} : nodupkeys l → nodup l := nodup_of_nodup_map _ theorem perm_nodupkeys {l₁ l₂ : list (sigma β)} (h : l₁ ~ l₂) : nodupkeys l₁ ↔ nodupkeys l₂ := (h.map _).nodup_iff theorem nodupkeys_join {L : list (list (sigma β))} : nodupkeys (join L) ↔ (∀ l ∈ L, nodupkeys l) ∧ pairwise disjoint (L.map keys) := begin rw [nodupkeys_iff_pairwise, pairwise_join, pairwise_map], refine and_congr (ball_congr $ λ l h, by simp [nodupkeys_iff_pairwise]) _, apply iff_of_eq, congr', ext l₁ l₂, simp [keys, disjoint_iff_ne] end theorem nodup_enum_map_fst (l : list α) : (l.enum.map prod.fst).nodup := by simp [list.nodup_range] lemma mem_ext {l₀ l₁ : list (sigma β)} (nd₀ : l₀.nodup) (nd₁ : l₁.nodup) (h : ∀ x, x ∈ l₀ ↔ x ∈ l₁) : l₀ ~ l₁ := begin induction l₀ with x xs generalizing l₁; cases l₁ with y ys, { constructor }, iterate 2 { specialize h x <|> specialize h y, simp at h, cases h }, simp at nd₀ nd₁, classical, cases nd₀, cases nd₁, by_cases h' : x = y, { subst y, constructor, apply l₀_ih ‹ _ › ‹ nodup ys ›, intro a, specialize h a, simp at h, by_cases h' : a = x, { subst a, rw ← not_iff_not, split; intro; assumption }, { simp [h'] at h, exact h } }, { transitivity x :: y :: ys.erase x, { constructor, apply l₀_ih ‹ _ ›, { simp, split, { intro, apply nd₁_left, apply mem_of_mem_erase a }, apply nodup_erase_of_nodup; assumption }, { intro a, specialize h a, simp at h, by_cases h' : a = x, { subst a, rw ← not_iff_not, split; intro, simp [mem_erase_of_nodup,*], assumption }, { simp [h'] at h, simp [h], apply or_congr, refl, simp [mem_erase_of_ne,*] } } }, transitivity y :: x :: ys.erase x, { constructor }, { constructor, symmetry, apply perm_cons_erase, specialize h x, simp [h'] at h, exact h } } end variables [decidable_eq α] /- lookup -/ /-- `lookup a l` is the first value in `l` corresponding to the key `a`, or `none` if no such element exists. -/ def lookup (a : α) : list (sigma β) → option (β a) | [] := none | (⟨a', b⟩ :: l) := if h : a' = a then some (eq.rec_on h b) else lookup l @[simp] theorem lookup_nil (a : α) : lookup a [] = @none (β a) := rfl @[simp] theorem lookup_cons_eq (l) (a : α) (b : β a) : lookup a (⟨a, b⟩::l) = some b := dif_pos rfl @[simp] theorem lookup_cons_ne (l) {a} : ∀ s : sigma β, a ≠ s.1 → lookup a (s::l) = lookup a l | ⟨a', b⟩ h := dif_neg h.symm theorem lookup_is_some {a : α} : ∀ {l : list (sigma β)}, (lookup a l).is_some ↔ a ∈ l.keys | [] := by simp | (⟨a', b⟩ :: l) := begin by_cases h : a = a', { subst a', simp }, { simp [h, lookup_is_some] }, end theorem lookup_eq_none {a : α} {l : list (sigma β)} : lookup a l = none ↔ a ∉ l.keys := by simp [← lookup_is_some, option.is_none_iff_eq_none] theorem of_mem_lookup {a : α} {b : β a} : ∀ {l : list (sigma β)}, b ∈ lookup a l → sigma.mk a b ∈ l | (⟨a', b'⟩ :: l) H := begin by_cases h : a = a', { subst a', simp at H, simp [H] }, { simp [h] at H, exact or.inr (of_mem_lookup H) } end theorem mem_lookup {a} {b : β a} {l : list (sigma β)} (nd : l.nodupkeys) (h : sigma.mk a b ∈ l) : b ∈ lookup a l := begin cases option.is_some_iff_exists.mp (lookup_is_some.mpr (mem_keys_of_mem h)) with b' h', cases nd.eq_of_mk_mem h (of_mem_lookup h'), exact h' end theorem map_lookup_eq_find (a : α) : ∀ l : list (sigma β), (lookup a l).map (sigma.mk a) = find (λ s, a = s.1) l | [] := rfl | (⟨a', b'⟩ :: l) := begin by_cases h : a = a', { subst a', simp }, { simp [h, map_lookup_eq_find] } end theorem mem_lookup_iff {a : α} {b : β a} {l : list (sigma β)} (nd : l.nodupkeys) : b ∈ lookup a l ↔ sigma.mk a b ∈ l := ⟨of_mem_lookup, mem_lookup nd⟩ theorem perm_lookup (a : α) {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) (p : l₁ ~ l₂) : lookup a l₁ = lookup a l₂ := by ext b; simp [mem_lookup_iff, nd₁, nd₂]; exact p.mem_iff lemma lookup_ext {l₀ l₁ : list (sigma β)} (nd₀ : l₀.nodupkeys) (nd₁ : l₁.nodupkeys) (h : ∀ x y, y ∈ l₀.lookup x ↔ y ∈ l₁.lookup x) : l₀ ~ l₁ := mem_ext (nodup_of_nodupkeys nd₀) (nodup_of_nodupkeys nd₁) (λ ⟨a,b⟩, by rw [← mem_lookup_iff, ← mem_lookup_iff, h]; assumption) /- lookup_all -/ /-- `lookup_all a l` is the list of all values in `l` corresponding to the key `a`. -/ def lookup_all (a : α) : list (sigma β) → list (β a) | [] := [] | (⟨a', b⟩ :: l) := if h : a' = a then eq.rec_on h b :: lookup_all l else lookup_all l @[simp] theorem lookup_all_nil (a : α) : lookup_all a [] = @nil (β a) := rfl @[simp] theorem lookup_all_cons_eq (l) (a : α) (b : β a) : lookup_all a (⟨a, b⟩::l) = b :: lookup_all a l := dif_pos rfl @[simp] theorem lookup_all_cons_ne (l) {a} : ∀ s : sigma β, a ≠ s.1 → lookup_all a (s::l) = lookup_all a l | ⟨a', b⟩ h := dif_neg h.symm theorem lookup_all_eq_nil {a : α} : ∀ {l : list (sigma β)}, lookup_all a l = [] ↔ ∀ b : β a, sigma.mk a b ∉ l | [] := by simp | (⟨a', b⟩ :: l) := begin by_cases h : a = a', { subst a', simp, exact ⟨_, or.inl rfl⟩ }, { simp [h, lookup_all_eq_nil] }, end theorem head_lookup_all (a : α) : ∀ l : list (sigma β), head' (lookup_all a l) = lookup a l | [] := by simp | (⟨a', b⟩ :: l) := by by_cases h : a = a'; [{subst h, simp}, simp *] theorem mem_lookup_all {a : α} {b : β a} : ∀ {l : list (sigma β)}, b ∈ lookup_all a l ↔ sigma.mk a b ∈ l | [] := by simp | (⟨a', b'⟩ :: l) := by by_cases h : a = a'; [{subst h, simp *}, simp *] theorem lookup_all_sublist (a : α) : ∀ l : list (sigma β), (lookup_all a l).map (sigma.mk a) <+ l | [] := by simp | (⟨a', b'⟩ :: l) := begin by_cases h : a = a', { subst h, simp, exact (lookup_all_sublist l).cons2 _ _ _ }, { simp [h], exact (lookup_all_sublist l).cons _ _ _ } end theorem lookup_all_length_le_one (a : α) {l : list (sigma β)} (h : l.nodupkeys) : length (lookup_all a l) ≤ 1 := by have := nodup_of_sublist ((lookup_all_sublist a l).map _) h; rw map_map at this; rwa [← nodup_repeat, ← map_const _ a] theorem lookup_all_eq_lookup (a : α) {l : list (sigma β)} (h : l.nodupkeys) : lookup_all a l = (lookup a l).to_list := begin rw ← head_lookup_all, have := lookup_all_length_le_one a h, revert this, rcases lookup_all a l with _|⟨b, _|⟨c, l⟩⟩; intro; try {refl}, exact absurd this dec_trivial end theorem lookup_all_nodup (a : α) {l : list (sigma β)} (h : l.nodupkeys) : (lookup_all a l).nodup := by rw lookup_all_eq_lookup a h; apply option.to_list_nodup theorem perm_lookup_all (a : α) {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) (p : l₁ ~ l₂) : lookup_all a l₁ = lookup_all a l₂ := by simp [lookup_all_eq_lookup, nd₁, nd₂, perm_lookup a nd₁ nd₂ p] /- kreplace -/ def kreplace (a : α) (b : β a) : list (sigma β) → list (sigma β) := lookmap $ λ s, if h : a = s.1 then some ⟨a, b⟩ else none theorem kreplace_of_forall_not (a : α) (b : β a) {l : list (sigma β)} (H : ∀ b : β a, sigma.mk a b ∉ l) : kreplace a b l = l := lookmap_of_forall_not _ $ begin rintro ⟨a', b'⟩ h, dsimp, split_ifs, { subst a', exact H _ h }, {refl} end theorem kreplace_self {a : α} {b : β a} {l : list (sigma β)} (nd : nodupkeys l) (h : sigma.mk a b ∈ l) : kreplace a b l = l := begin refine (lookmap_congr _).trans (lookmap_id' (option.guard (λ s, a = s.1)) _ _), { rintro ⟨a', b'⟩ h', dsimp [option.guard], split_ifs, { subst a', exact ⟨rfl, heq_of_eq $ nd.eq_of_mk_mem h h'⟩ }, { refl } }, { rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, dsimp [option.guard], split_ifs, { subst a₁, rintro ⟨⟩, simp }, { rintro ⟨⟩ } }, end theorem keys_kreplace (a : α) (b : β a) : ∀ l : list (sigma β), (kreplace a b l).keys = l.keys := lookmap_map_eq _ _ $ by rintro ⟨a₁, b₂⟩ ⟨a₂, b₂⟩; dsimp; split_ifs; simp [h] {contextual := tt} theorem kreplace_nodupkeys (a : α) (b : β a) {l : list (sigma β)} : (kreplace a b l).nodupkeys ↔ l.nodupkeys := by simp [nodupkeys, keys_kreplace] theorem perm.kreplace {a : α} {b : β a} {l₁ l₂ : list (sigma β)} (nd : l₁.nodupkeys) : l₁ ~ l₂ → kreplace a b l₁ ~ kreplace a b l₂ := perm_lookmap _ $ begin refine nd.pairwise_ne.imp _, intros x y h z h₁ w h₂, split_ifs at h₁ h₂; cases h₁; cases h₂, exact (h (h_2.symm.trans h_1)).elim end /- kerase -/ /-- Remove the first pair with the key `a`. -/ def kerase (a : α) : list (sigma β) → list (sigma β) := erasep $ λ s, a = s.1 @[simp] theorem kerase_nil {a} : @kerase _ β _ a [] = [] := rfl @[simp, priority 990] theorem kerase_cons_eq {a} {s : sigma β} {l : list (sigma β)} (h : a = s.1) : kerase a (s :: l) = l := by simp [kerase, h] @[simp, priority 990] theorem kerase_cons_ne {a} {s : sigma β} {l : list (sigma β)} (h : a ≠ s.1) : kerase a (s :: l) = s :: kerase a l := by simp [kerase, h] @[simp, priority 980] theorem kerase_of_not_mem_keys {a} {l : list (sigma β)} (h : a ∉ l.keys) : kerase a l = l := by induction l with _ _ ih; [refl, { simp [not_or_distrib] at h, simp [h.1, ih h.2] }] theorem kerase_sublist (a : α) (l : list (sigma β)) : kerase a l <+ l := erasep_sublist _ theorem kerase_keys_subset (a) (l : list (sigma β)) : (kerase a l).keys ⊆ l.keys := ((kerase_sublist a l).map _).subset theorem mem_keys_of_mem_keys_kerase {a₁ a₂} {l : list (sigma β)} : a₁ ∈ (kerase a₂ l).keys → a₁ ∈ l.keys := @kerase_keys_subset _ _ _ _ _ _ theorem exists_of_kerase {a : α} {l : list (sigma β)} (h : a ∈ l.keys) : ∃ (b : β a) (l₁ l₂ : list (sigma β)), a ∉ l₁.keys ∧ l = l₁ ++ ⟨a, b⟩ :: l₂ ∧ kerase a l = l₁ ++ l₂ := begin induction l, case list.nil { cases h }, case list.cons : hd tl ih { by_cases e : a = hd.1, { subst e, exact ⟨hd.2, [], tl, by simp, by cases hd; refl, by simp⟩ }, { simp at h, cases h, case or.inl : h { exact absurd h e }, case or.inr : h { rcases ih h with ⟨b, tl₁, tl₂, h₁, h₂, h₃⟩, exact ⟨b, hd :: tl₁, tl₂, not_mem_cons_of_ne_of_not_mem e h₁, by rw h₂; refl, by simp [e, h₃]⟩ } } } end @[simp, priority 990] theorem mem_keys_kerase_of_ne {a₁ a₂} {l : list (sigma β)} (h : a₁ ≠ a₂) : a₁ ∈ (kerase a₂ l).keys ↔ a₁ ∈ l.keys := iff.intro mem_keys_of_mem_keys_kerase $ λ p, if q : a₂ ∈ l.keys then match l, kerase a₂ l, exists_of_kerase q, p with | _, _, ⟨_, _, _, _, rfl, rfl⟩, p := by simpa [keys, h] using p end else by simp [q, p] theorem keys_kerase {a} {l : list (sigma β)} : (kerase a l).keys = l.keys.erase a := by rw [keys, kerase, ←erasep_map sigma.fst l, erase_eq_erasep] theorem kerase_kerase {a a'} {l : list (sigma β)} : (kerase a' l).kerase a = (kerase a l).kerase a' := begin by_cases a = a', { subst a' }, induction l with x xs, { refl }, { by_cases a' = x.1, { subst a', simp [kerase_cons_ne h,kerase_cons_eq rfl] }, by_cases h' : a = x.1, { subst a, simp [kerase_cons_eq rfl,kerase_cons_ne (ne.symm h)] }, { simp [kerase_cons_ne,*] } } end theorem kerase_nodupkeys (a : α) {l : list (sigma β)} : nodupkeys l → (kerase a l).nodupkeys := nodupkeys_of_sublist $ kerase_sublist _ _ theorem perm.kerase {a : α} {l₁ l₂ : list (sigma β)} (nd : l₁.nodupkeys) : l₁ ~ l₂ → kerase a l₁ ~ kerase a l₂ := perm.erasep _ $ (nodupkeys_iff_pairwise.1 nd).imp $ by rintro x y h rfl; exact h @[simp] theorem not_mem_keys_kerase (a) {l : list (sigma β)} (nd : l.nodupkeys) : a ∉ (kerase a l).keys := begin induction l, case list.nil { simp }, case list.cons : hd tl ih { simp at nd, by_cases h : a = hd.1, { subst h, simp [nd.1] }, { simp [h, ih nd.2] } } end @[simp] theorem lookup_kerase (a) {l : list (sigma β)} (nd : l.nodupkeys) : lookup a (kerase a l) = none := lookup_eq_none.mpr (not_mem_keys_kerase a nd) @[simp] theorem lookup_kerase_ne {a a'} {l : list (sigma β)} (h : a ≠ a') : lookup a (kerase a' l) = lookup a l := begin induction l, case list.nil { refl }, case list.cons : hd tl ih { cases hd with ah bh, by_cases h₁ : a = ah; by_cases h₂ : a' = ah, { substs h₁ h₂, cases ne.irrefl h }, { subst h₁, simp [h₂] }, { subst h₂, simp [h] }, { simp [h₁, h₂, ih] } } end theorem kerase_append_left {a} : ∀ {l₁ l₂ : list (sigma β)}, a ∈ l₁.keys → kerase a (l₁ ++ l₂) = kerase a l₁ ++ l₂ | [] _ h := by cases h | (s :: l₁) l₂ h₁ := if h₂ : a = s.1 then by simp [h₂] else by simp at h₁; cases h₁; [exact absurd h₁ h₂, simp [h₂, kerase_append_left h₁]] theorem kerase_append_right {a} : ∀ {l₁ l₂ : list (sigma β)}, a ∉ l₁.keys → kerase a (l₁ ++ l₂) = l₁ ++ kerase a l₂ | [] _ h := rfl | (_ :: l₁) l₂ h := by simp [not_or_distrib] at h; simp [h.1, kerase_append_right h.2] theorem kerase_comm (a₁ a₂) (l : list (sigma β)) : kerase a₂ (kerase a₁ l) = kerase a₁ (kerase a₂ l) := if h : a₁ = a₂ then by simp [h] else if ha₁ : a₁ ∈ l.keys then if ha₂ : a₂ ∈ l.keys then match l, kerase a₁ l, exists_of_kerase ha₁, ha₂ with | _, _, ⟨b₁, l₁, l₂, a₁_nin_l₁, rfl, rfl⟩, a₂_in_l₁_app_l₂ := if h' : a₂ ∈ l₁.keys then by simp [kerase_append_left h', kerase_append_right (mt (mem_keys_kerase_of_ne h).mp a₁_nin_l₁)] else by simp [kerase_append_right h', kerase_append_right a₁_nin_l₁, @kerase_cons_ne _ _ _ a₂ ⟨a₁, b₁⟩ _ (ne.symm h)] end else by simp [ha₂, mt mem_keys_of_mem_keys_kerase ha₂] else by simp [ha₁, mt mem_keys_of_mem_keys_kerase ha₁] /- kinsert -/ /-- Insert the pair `⟨a, b⟩` and erase the first pair with the key `a`. -/ def kinsert (a : α) (b : β a) (l : list (sigma β)) : list (sigma β) := ⟨a, b⟩ :: kerase a l @[simp] theorem kinsert_def {a} {b : β a} {l : list (sigma β)} : kinsert a b l = ⟨a, b⟩ :: kerase a l := rfl theorem mem_keys_kinsert {a a'} {b' : β a'} {l : list (sigma β)} : a ∈ (kinsert a' b' l).keys ↔ a = a' ∨ a ∈ l.keys := by by_cases h : a = a'; simp [h] theorem kinsert_nodupkeys (a) (b : β a) {l : list (sigma β)} (nd : l.nodupkeys) : (kinsert a b l).nodupkeys := nodupkeys_cons.mpr ⟨not_mem_keys_kerase a nd, kerase_nodupkeys a nd⟩ theorem perm.kinsert {a} {b : β a} {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (p : l₁ ~ l₂) : kinsert a b l₁ ~ kinsert a b l₂ := (p.kerase nd₁).cons _ theorem lookup_kinsert {a} {b : β a} (l : list (sigma β)) : lookup a (kinsert a b l) = some b := by simp only [kinsert, lookup_cons_eq] theorem lookup_kinsert_ne {a a'} {b' : β a'} {l : list (sigma β)} (h : a ≠ a') : lookup a (kinsert a' b' l) = lookup a l := by simp [h] /- kextract -/ def kextract (a : α) : list (sigma β) → option (β a) × list (sigma β) | [] := (none, []) | (s::l) := if h : s.1 = a then (some (eq.rec_on h s.2), l) else let (b', l') := kextract l in (b', s :: l') @[simp] theorem kextract_eq_lookup_kerase (a : α) : ∀ l : list (sigma β), kextract a l = (lookup a l, kerase a l) | [] := rfl | (⟨a', b⟩::l) := begin simp [kextract], dsimp, split_ifs, { subst a', simp [kerase] }, { simp [kextract, ne.symm h, kextract_eq_lookup_kerase l, kerase] } end /- erase_dupkeys -/ /-- Remove entries with duplicate keys from `l : list (sigma β)`. -/ def erase_dupkeys : list (sigma β) → list (sigma β) := list.foldr (λ x, kinsert x.1 x.2) [] lemma erase_dupkeys_cons {x : sigma β} (l : list (sigma β)) : erase_dupkeys (x :: l) = kinsert x.1 x.2 (erase_dupkeys l) := rfl lemma nodupkeys_erase_dupkeys (l : list (sigma β)) : nodupkeys (erase_dupkeys l) := begin dsimp [erase_dupkeys], generalize hl : nil = l', have : nodupkeys l', { rw ← hl, apply nodup_nil }, clear hl, induction l with x xs, { apply this }, { cases x, simp [erase_dupkeys], split, { simp [keys_kerase], apply mem_erase_of_nodup l_ih }, apply kerase_nodupkeys _ l_ih, } end lemma lookup_erase_dupkeys (a : α) (l : list (sigma β)) : lookup a (erase_dupkeys l) = lookup a l := begin induction l, refl, cases l_hd with a' b, by_cases a = a', { subst a', rw [erase_dupkeys_cons,lookup_kinsert,lookup_cons_eq] }, { rw [erase_dupkeys_cons,lookup_kinsert_ne h,l_ih,lookup_cons_ne], exact h }, end /- kunion -/ /-- `kunion l₁ l₂` is the append to l₁ of l₂ after, for each key in l₁, the first matching pair in l₂ is erased. -/ def kunion : list (sigma β) → list (sigma β) → list (sigma β) | [] l₂ := l₂ | (s :: l₁) l₂ := s :: kunion l₁ (kerase s.1 l₂) @[simp] theorem nil_kunion {l : list (sigma β)} : kunion [] l = l := rfl @[simp] theorem kunion_nil : ∀ {l : list (sigma β)}, kunion l [] = l | [] := rfl | (_ :: l) := by rw [kunion, kerase_nil, kunion_nil] @[simp] theorem kunion_cons {s} {l₁ l₂ : list (sigma β)} : kunion (s :: l₁) l₂ = s :: kunion l₁ (kerase s.1 l₂) := rfl @[simp] theorem mem_keys_kunion {a} {l₁ l₂ : list (sigma β)} : a ∈ (kunion l₁ l₂).keys ↔ a ∈ l₁.keys ∨ a ∈ l₂.keys := begin induction l₁ generalizing l₂, case list.nil { simp }, case list.cons : s l₁ ih { by_cases h : a = s.1; [simp [h], simp [h, ih]] } end @[simp] theorem kunion_kerase {a} : ∀ {l₁ l₂ : list (sigma β)}, kunion (kerase a l₁) (kerase a l₂) = kerase a (kunion l₁ l₂) | [] _ := rfl | (s :: _) l := by by_cases h : a = s.1; simp [h, kerase_comm a s.1 l, kunion_kerase] theorem kunion_nodupkeys {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) : (kunion l₁ l₂).nodupkeys := begin induction l₁ generalizing l₂, case list.nil { simp only [nil_kunion, nd₂] }, case list.cons : s l₁ ih { simp at nd₁, simp [not_or_distrib, nd₁.1, nd₂, ih nd₁.2 (kerase_nodupkeys s.1 nd₂)] } end theorem perm.kunion_right {l₁ l₂ : list (sigma β)} (p : l₁ ~ l₂) (l) : kunion l₁ l ~ kunion l₂ l := begin induction p generalizing l, case list.perm.nil { refl }, case list.perm.cons : hd tl₁ tl₂ p ih { simp [ih (kerase hd.1 l), perm.cons] }, case list.perm.swap : s₁ s₂ l { simp [kerase_comm, perm.swap] }, case list.perm.trans : l₁ l₂ l₃ p₁₂ p₂₃ ih₁₂ ih₂₃ { exact perm.trans (ih₁₂ l) (ih₂₃ l) } end theorem perm.kunion_left : ∀ l {l₁ l₂ : list (sigma β)}, l₁.nodupkeys → l₁ ~ l₂ → kunion l l₁ ~ kunion l l₂ | [] _ _ _ p := p | (s :: l) l₁ l₂ nd₁ p := by simp [((p.kerase nd₁).kunion_left l (kerase_nodupkeys s.1 nd₁)).cons s] theorem perm.kunion {l₁ l₂ l₃ l₄ : list (sigma β)} (nd₃ : l₃.nodupkeys) (p₁₂ : l₁ ~ l₂) (p₃₄ : l₃ ~ l₄) : kunion l₁ l₃ ~ kunion l₂ l₄ := (p₁₂.kunion_right l₃).trans (p₃₄.kunion_left l₂ nd₃) @[simp] theorem lookup_kunion_left {a} {l₁ l₂ : list (sigma β)} (h : a ∈ l₁.keys) : lookup a (kunion l₁ l₂) = lookup a l₁ := begin induction l₁ with s _ ih generalizing l₂; simp at h; cases h; cases s with a', { subst h, simp }, { rw kunion_cons, by_cases h' : a = a', { subst h', simp }, { simp [h', ih h] } } end @[simp] theorem lookup_kunion_right {a} {l₁ l₂ : list (sigma β)} (h : a ∉ l₁.keys) : lookup a (kunion l₁ l₂) = lookup a l₂ := begin induction l₁ generalizing l₂, case list.nil { simp }, case list.cons : _ _ ih { simp [not_or_distrib] at h, simp [h.1, ih h.2] } end @[simp] theorem mem_lookup_kunion {a} {b : β a} {l₁ l₂ : list (sigma β)} : b ∈ lookup a (kunion l₁ l₂) ↔ b ∈ lookup a l₁ ∨ a ∉ l₁.keys ∧ b ∈ lookup a l₂ := begin induction l₁ generalizing l₂, case list.nil { simp }, case list.cons : s _ ih { cases s with a', by_cases h₁ : a = a', { subst h₁, simp }, { let h₂ := @ih (kerase a' l₂), simp [h₁] at h₂, simp [h₁, h₂] } } end theorem mem_lookup_kunion_middle {a} {b : β a} {l₁ l₂ l₃ : list (sigma β)} (h₁ : b ∈ lookup a (kunion l₁ l₃)) (h₂ : a ∉ keys l₂) : b ∈ lookup a (kunion (kunion l₁ l₂) l₃) := match mem_lookup_kunion.mp h₁ with | or.inl h := mem_lookup_kunion.mpr (or.inl (mem_lookup_kunion.mpr (or.inl h))) | or.inr h := mem_lookup_kunion.mpr $ or.inr ⟨mt mem_keys_kunion.mp (not_or_distrib.mpr ⟨h.1, h₂⟩), h.2⟩ end end list
0529a54790f605a16296b944bb6369a9e97797fd
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/category_theory/elements.lean
46ab556901fcbe2edd9f39e34325f23aeaa2789b
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
4,056
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.comma import category_theory.groupoid /-! # The category of elements This file defines the category of elements, also known as (a special case of) the Grothendieck construction. Given a functor `F : C ⥤ Type`, an object of `F.elements` is a pair `(X : C, x : F.obj X)`. A morphism `(X, x) ⟶ (Y, y)` is a morphism `f : X ⟶ Y` in `C`, so `F.map f` takes `x` to `y`. ## Implementation notes This construction is equivalent to a special case of a comma construction, so this is mostly just a more convenient API. We prove the equivalence in `category_theory.category_of_elements.comma_equivalence`. ## References * [Emily Riehl, *Category Theory in Context*, Section 2.4][riehl2017] * <https://en.wikipedia.org/wiki/Category_of_elements> * <https://ncatlab.org/nlab/show/category+of+elements> ## Tags category of elements, Grothendieck construction, comma category -/ namespace category_theory universes w v u variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 /-- The type of objects for the category of elements of a functor `F : C ⥤ Type` is a pair `(X : C, x : F.obj X)`. -/ def functor.elements (F : C ⥤ Type w) := (Σ c : C, F.obj c) /-- The category structure on `F.elements`, for `F : C ⥤ Type`. A morphism `(X, x) ⟶ (Y, y)` is a morphism `f : X ⟶ Y` in `C`, so `F.map f` takes `x` to `y`. -/ instance category_of_elements (F : C ⥤ Type w) : category F.elements := { hom := λ p q, { f : p.1 ⟶ q.1 // (F.map f) p.2 = q.2 }, id := λ p, ⟨𝟙 p.1, by obviously⟩, comp := λ p q r f g, ⟨f.val ≫ g.val, by obviously⟩ } omit 𝒞 -- We'll assume C has a groupoid structure, so temporarily forget its category structure -- to avoid conflicts. instance groupoid_of_elements [groupoid C] (F : C ⥤ Type w) : groupoid F.elements := { inv := λ p q f, ⟨inv f.val, calc F.map (inv f.val) q.2 = F.map (inv f.val) (F.map f.val p.2) : by rw f.2 ... = (F.map f.val ≫ F.map (inv f.val)) p.2 : by simp ... = p.2 : by {rw ←functor.map_comp, simp}⟩ } include 𝒞 namespace category_of_elements variable (F : C ⥤ Type w) /-- The functor out of the category of elements which forgets the element. -/ def π : F.elements ⥤ C := { obj := λ X, X.1, map := λ X Y f, f.val } @[simp] lemma π_obj (X : F.elements) : (π F).obj X = X.1 := rfl @[simp] lemma π_map {X Y : F.elements} (f : X ⟶ Y) : (π F).map f = f.val := rfl /-- The forward direction of the equivalence `F.elements ≅ (*, F)`. -/ def to_comma : F.elements ⥤ comma ((functor.const punit).obj punit) F := { obj := λ X, { left := punit.star, right := X.1, hom := λ _, X.2 }, map := λ X Y f, { right := f.val } } @[simp] lemma to_comma_obj (X) : (to_comma F).obj X = { left := punit.star, right := X.1, hom := λ _, X.2 } := rfl @[simp] lemma to_comma_map {X Y} (f : X ⟶ Y) : (to_comma F).map f = { right := f.val } := rfl /-- The reverse direction of the equivalence `F.elements ≅ (*, F)`. -/ def from_comma : comma ((functor.const punit).obj punit) F ⥤ F.elements := { obj := λ X, ⟨X.right, X.hom (punit.star)⟩, map := λ X Y f, ⟨f.right, congr_fun f.w'.symm punit.star⟩ } @[simp] lemma from_comma_obj (X) : (from_comma F).obj X = ⟨X.right, X.hom (punit.star)⟩ := rfl @[simp] lemma from_comma_map {X Y} (f : X ⟶ Y) : (from_comma F).map f = ⟨f.right, congr_fun f.w'.symm punit.star⟩ := rfl /-- The equivalence between the category of elements `F.elements` and the comma category `(*, F)`. -/ def comma_equivalence : F.elements ≌ comma ((functor.const punit).obj punit) F := equivalence.mk (to_comma F) (from_comma F) (nat_iso.of_components (λ X, eq_to_iso (by tidy)) (by tidy)) (nat_iso.of_components (λ X, { hom := { right := 𝟙 _ }, inv := { right := 𝟙 _ } }) (by tidy)) end category_of_elements end category_theory
7fb693e3c005f254d4535dc0bff6d7d84baccb0f
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/simp_tactic.lean
8e98d0b4e39723aca4551f440914eb1bb97a1d0d
[ "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
28,078
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.meta.attribute init.meta.constructor_tactic import init.meta.relation_tactics init.meta.occurrences import init.data.option.basic open tactic def tactic.id_tag.simp : unit := () def simp.default_max_steps := 10000000 /-- Prefix the given `attr_name` with `"simp_attr"`. -/ meta constant mk_simp_attr_decl_name (attr_name : name) : name /-- Simp lemmas are used by the "simplifier" family of tactics. `simp_lemmas` is essentially a pair of tables `rb_map (expr_type × name) (priority_list simp_lemma)`. One of the tables is for congruences and one is for everything else. An individual simp lemma is: - A kind which can be `Refl`, `Simp` or `Congr`. - A pair of `expr`s `l ~> r`. The rb map is indexed by the name of `get_app_fn(l)`. - A proof that `l = r` or `l ↔ r`. - A list of the metavariables that must be filled before the proof can be applied. - A priority number -/ meta constant simp_lemmas : Type /-- Make a new table of simp lemmas -/ meta constant simp_lemmas.mk : simp_lemmas /-- Merge the simp_lemma tables. -/ meta constant simp_lemmas.join : simp_lemmas → simp_lemmas → simp_lemmas /-- Remove the given lemmas from the table. Use the names of the lemmas. -/ meta constant simp_lemmas.erase : simp_lemmas → list name → simp_lemmas /-- Remove all simp lemmas from the table. -/ meta constant simp_lemmas.erase_simp_lemmas : simp_lemmas → simp_lemmas /-- Makes the default simp_lemmas table which is composed of all lemmas tagged with `simp`. -/ meta constant simp_lemmas.mk_default : tactic simp_lemmas /-- Add a simplification lemma by an expression `p`. Some conditions on `p` must hold for it to be added, see list below. If your lemma is not being added, you can see the reasons by setting `set_option trace.simp_lemmas true`. - `p` must have the type `Π (h₁ : _) ... (hₙ : _), LHS ~ RHS` for some reflexive, transitive relation (usually `=`). - Any of the hypotheses `hᵢ` should either be present in `LHS` or otherwise a `Prop` or a typeclass instance. - `LHS` should not occur within `RHS`. - `LHS` should not occur within a hypothesis `hᵢ`. -/ meta constant simp_lemmas.add (s : simp_lemmas) (e : expr) (symm : bool := false) : tactic simp_lemmas /-- Add a simplification lemma by it's declaration name. See `simp_lemmas.add` for more information.-/ meta constant simp_lemmas.add_simp (s : simp_lemmas) (id : name) (symm : bool := false) : tactic simp_lemmas /-- Adds a congruence simp lemma to simp_lemmas. A congruence simp lemma is a lemma that breaks the simplification down into separate problems. For example, to simplify `a ∧ b` to `c ∧ d`, we should try to simp `a` to `c` and `b` to `d`. For examples of congruence simp lemmas look for lemmas with the `@[congr]` attribute. ```lean lemma if_simp_congr ... (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := ... lemma imp_congr_right (h : a → (b ↔ c)) : (a → b) ↔ (a → c) := ... lemma and_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∧ b) ↔ (c ∧ d) := ... ``` -/ meta constant simp_lemmas.add_congr : simp_lemmas → name → tactic simp_lemmas /-- Add expressions to a set of simp lemmas using `simp_lemmas.add`. This is the new version of `simp_lemmas.append`, which also allows you to set the `symm` flag. -/ meta def simp_lemmas.append_with_symm (s : simp_lemmas) (hs : list (expr × bool)) : tactic simp_lemmas := hs.mfoldl (λ s h, simp_lemmas.add s h.fst h.snd) s /-- Add expressions to a set of simp lemmas using `simp_lemmas.add`. This is the backwards-compatibility version of `simp_lemmas.append_with_symm`, and sets all `symm` flags to `ff`. -/ meta def simp_lemmas.append (s : simp_lemmas) (hs : list expr) : tactic simp_lemmas := hs.mfoldl (λ s h, simp_lemmas.add s h ff) s /-- `simp_lemmas.rewrite s e prove R` apply a simplification lemma from 's' - 'e' is the expression to be "simplified" - 'prove' is used to discharge proof obligations. - 'r' is the equivalence relation being used (e.g., 'eq', 'iff') - 'md' is the transparency; how aggresively should the simplifier perform reductions. Result (new_e, pr) is the new expression 'new_e' and a proof (pr : e R new_e) -/ meta constant simp_lemmas.rewrite (s : simp_lemmas) (e : expr) (prove : tactic unit := failed) (r : name := `eq) (md := reducible) : tactic (expr × expr) meta constant simp_lemmas.rewrites (s : simp_lemmas) (e : expr) (prove : tactic unit := failed) (r : name := `eq) (md := reducible) : tactic $ list (expr × expr) /-- `simp_lemmas.drewrite s e` tries to rewrite 'e' using only refl lemmas in 's' -/ meta constant simp_lemmas.drewrite (s : simp_lemmas) (e : expr) (md := reducible) : tactic expr meta constant is_valid_simp_lemma_cnst : name → tactic bool meta constant is_valid_simp_lemma : expr → tactic bool meta constant simp_lemmas.pp : simp_lemmas → tactic format meta instance : has_to_tactic_format simp_lemmas := ⟨simp_lemmas.pp⟩ namespace tactic /- Remark: `transform` should not change the target. -/ /-- Revert a local constant, change its type using `transform`. -/ meta def revert_and_transform (transform : expr → tactic expr) (h : expr) : tactic unit := do num_reverted : ℕ ← revert h, t ← target, match t with | expr.pi n bi d b := do h_simp ← transform d, unsafe_change $ expr.pi n bi h_simp b | expr.elet n g e f := do h_simp ← transform g, unsafe_change $ expr.elet n h_simp e f | _ := fail "reverting hypothesis created neither a pi nor an elet expr (unreachable?)" end, intron num_reverted /-- `get_eqn_lemmas_for deps d` returns the automatically generated equational lemmas for definition d. If deps is tt, then lemmas for automatically generated auxiliary declarations used to define d are also included. -/ meta def get_eqn_lemmas_for (deps : bool) (d : name) : tactic (list name) := do env ← get_env, pure $ if deps then env.get_ext_eqn_lemmas_for d else env.get_eqn_lemmas_for d structure dsimp_config := (md := reducible) -- reduction mode: how aggressively constants are replaced with their definitions. (max_steps : nat := simp.default_max_steps) -- The maximum number of steps allowed before failing. (canonize_instances : bool := tt) -- See the documentation in `src/library/defeq_canonizer.h` (single_pass : bool := ff) -- Visit each subterm no more than once. (fail_if_unchanged := tt) -- Don't throw if dsimp didn't do anything. (eta := tt) -- allow eta-equivalence: `(λ x, F $ x) ↝ F` (zeta : bool := tt) -- do zeta-reductions: `let x : a := b in c ↝ c[x/b]`. (beta : bool := tt) -- do beta-reductions: `(λ x, E) $ (y) ↝ E[x/y]`. (proj : bool := tt) -- reduce projections: `⟨a,b⟩.1 ↝ a`. (iota : bool := tt) -- reduce recursors for inductive datatypes: eg `nat.rec_on (succ n) Z R ↝ R n $ nat.rec_on n Z R` (unfold_reducible := ff) -- if tt, definitions with `reducible` transparency will be unfolded (delta-reduced) (memoize := tt) -- Perform caching of dsimps of subterms. end tactic /-- (Definitional) Simplify the given expression using *only* reflexivity equality lemmas from the given set of lemmas. The resulting expression is definitionally equal to the input. The list `u` contains defintions to be delta-reduced, and projections to be reduced.-/ meta constant simp_lemmas.dsimplify (s : simp_lemmas) (u : list name := []) (e : expr) (cfg : tactic.dsimp_config := {}) : tactic expr namespace tactic /-- Remark: the configuration parameters `cfg.md` and `cfg.eta` are ignored by this tactic. -/ meta constant dsimplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) /- (pre a e) is invoked before visiting the children of subterm 'e', if it succeeds the result (new_a, new_e, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression that must be definitionally equal to 'e', - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → expr → tactic (α × expr × bool)) /- (post a e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → expr → tactic (α × expr × bool)) (e : expr) (cfg : dsimp_config := {}) : tactic (α × expr) meta def dsimplify (pre : expr → tactic (expr × bool)) (post : expr → tactic (expr × bool)) : expr → tactic expr := λ e, do (a, new_e) ← dsimplify_core () (λ u e, do r ← pre e, return (u, r)) (λ u e, do r ← post e, return (u, r)) e, return new_e meta def get_simp_lemmas_or_default : option simp_lemmas → tactic simp_lemmas | none := simp_lemmas.mk_default | (some s) := return s meta def dsimp_target (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : tactic unit := do s ← get_simp_lemmas_or_default s, t ← target >>= instantiate_mvars, s.dsimplify u t cfg >>= unsafe_change meta def dsimp_hyp (h : expr) (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : tactic unit := do s ← get_simp_lemmas_or_default s, revert_and_transform (λ e, s.dsimplify u e cfg) h /- Remark: we use transparency.instances by default to make sure that we can unfold projections of type classes. Example: (@has_add.add nat nat.has_add a b) -/ /-- Tries to unfold `e` if it is a constant or a constant application. Remark: this is not a recursive procedure. -/ meta constant dunfold_head (e : expr) (md := transparency.instances) : tactic expr structure dunfold_config extends dsimp_config := (md := transparency.instances) /-! Remark: in principle, dunfold can be implemented on top of dsimp. We don't do it for performance reasons. -/ meta constant dunfold (cs : list name) (e : expr) (cfg : dunfold_config := {}) : tactic expr meta def dunfold_target (cs : list name) (cfg : dunfold_config := {}) : tactic unit := do t ← target, dunfold cs t cfg >>= unsafe_change meta def dunfold_hyp (cs : list name) (h : expr) (cfg : dunfold_config := {}) : tactic unit := revert_and_transform (λ e, dunfold cs e cfg) h structure delta_config := (max_steps := simp.default_max_steps) (visit_instances := tt) private meta def is_delta_target (e : expr) (cs : list name) : bool := cs.any (λ c, if e.is_app_of c then tt /- Exact match -/ else let f := e.get_app_fn in /- f is an auxiliary constant generated when compiling c -/ f.is_constant && f.const_name.is_internal && (f.const_name.get_prefix = c)) /-- Delta reduce the given constant names -/ meta def delta (cs : list name) (e : expr) (cfg : delta_config := {}) : tactic expr := let unfold (u : unit) (e : expr) : tactic (unit × expr × bool) := do guard (is_delta_target e cs), (expr.const f_name f_lvls) ← return e.get_app_fn, env ← get_env, decl ← env.get f_name, new_f ← decl.instantiate_value_univ_params f_lvls, new_e ← head_beta (expr.mk_app new_f e.get_app_args), return (u, new_e, tt) in do (c, new_e) ← dsimplify_core () (λ c e, failed) unfold e {max_steps := cfg.max_steps, canonize_instances := cfg.visit_instances}, return new_e meta def delta_target (cs : list name) (cfg : delta_config := {}) : tactic unit := do t ← target, delta cs t cfg >>= unsafe_change meta def delta_hyp (cs : list name) (h : expr) (cfg : delta_config := {}) :tactic unit := revert_and_transform (λ e, delta cs e cfg) h structure unfold_proj_config extends dsimp_config := (md := transparency.instances) /-- If `e` is a projection application, try to unfold it, otherwise fail. -/ meta constant unfold_proj (e : expr) (md := transparency.instances) : tactic expr meta def unfold_projs (e : expr) (cfg : unfold_proj_config := {}) : tactic expr := let unfold (changed : bool) (e : expr) : tactic (bool × expr × bool) := do new_e ← unfold_proj e cfg.md, return (tt, new_e, tt) in do (tt, new_e) ← dsimplify_core ff (λ c e, failed) unfold e cfg.to_dsimp_config | fail "no projections to unfold", return new_e meta def unfold_projs_target (cfg : unfold_proj_config := {}) : tactic unit := do t ← target, unfold_projs t cfg >>= unsafe_change meta def unfold_projs_hyp (h : expr) (cfg : unfold_proj_config := {}) : tactic unit := revert_and_transform (λ e, unfold_projs e cfg) h structure simp_config := (max_steps : nat := simp.default_max_steps) (contextual : bool := ff) (lift_eq : bool := tt) (canonize_instances : bool := tt) (canonize_proofs : bool := ff) (use_axioms : bool := tt) (zeta : bool := tt) (beta : bool := tt) (eta : bool := tt) (proj : bool := tt) -- reduce projections (iota : bool := tt) (iota_eqn : bool := ff) -- reduce using all equation lemmas generated by equation/pattern-matching compiler (constructor_eq : bool := tt) (single_pass : bool := ff) (fail_if_unchanged := tt) (memoize := tt) (trace_lemmas := ff) /-- `simplify s e cfg r prove` simplify `e` using `s` using bottom-up traversal. `discharger` is a tactic for dischaging new subgoals created by the simplifier. If it fails, the simplifier tries to discharge the subgoal by simplifying it to `true`. The parameter `to_unfold` specifies definitions that should be delta-reduced, and projection applications that should be unfolded. -/ meta constant simplify (s : simp_lemmas) (to_unfold : list name := []) (e : expr) (cfg : simp_config := {}) (r : name := `eq) (discharger : tactic unit := failed) : tactic (expr × expr × name_set) meta def simp_target (s : simp_lemmas) (to_unfold : list name := []) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic name_set := do t ← target >>= instantiate_mvars, (new_t, pr, lms) ← simplify s to_unfold t cfg `eq discharger, replace_target new_t pr ``id_tag.simp, return lms meta def simp_hyp (s : simp_lemmas) (to_unfold : list name := []) (h : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic (expr × name_set) := do when (expr.is_local_constant h = ff) (fail "tactic simp_at failed, the given expression is not a hypothesis"), htype ← infer_type h, (h_new_type, pr, lms) ← simplify s to_unfold htype cfg `eq discharger, new_hyp ← replace_hyp h h_new_type pr ``id_tag.simp, return (new_hyp, lms) /-- `ext_simplify_core a c s discharger pre post r e`: - `a : α` - initial user data - `c : simp_config` - simp configuration options - `s : simp_lemmas` - the set of simp_lemmas to use. Remark: the simplification lemmas are not applied automatically like in the simplify tactic. The caller must use them at pre/post. - `discharger : α → tactic α` - tactic for dischaging hypothesis in conditional rewriting rules. The argument 'α' is the current user data. - `pre a s r p e` is invoked before visiting the children of subterm 'e'. + arguments: - `a` is the current user data - `s` is the updated set of lemmas if 'contextual' is `tt`, - `r` is the simplification relation being used, - `p` is the "parent" expression (if there is one). - `e` is the current subexpression in question. + if it succeeds the result is `(new_a, new_e, new_pr, flag)` where - `new_a` is the new value for the user data - `new_e` is a new expression s.t. `r e new_e` - `new_pr` is a proof for `r e new_e`, If it is none, the proof is assumed to be by reflexivity - `flag` if tt `new_e` children should be visited, and `post` invoked. - `(post a s r p e)` is invoked after visiting the children of subterm `e`, The output is similar to `(pre a r s p e)`, but the 'flag' indicates whether the new expression should be revisited or not. - `r` is the simplification relation. Usually `=` or `↔`. - `e` is the input expression to be simplified. The method returns `(a,e,pr)` where - `a` is the final user data - `e` is the new expression - `pr` is the proof that the given expression equals the input expression. Note that `ext_simplify_core` will succeed even if `pre` and `post` fail, as failures are used to indicate that the method should move on to the next subterm. If it is desirable to propagate errors from `pre`, they can be propagated through the "user data". An easy way to do this is to call `tactic.capture (do ...)` in the parts of `pre`/`post` where errors matter, and then use `tactic.unwrap a` on the result. Additionally, `ext_simplify_core` does not propagate changes made to the tactic state by `pre` and `post. If it is desirable to propagate changes to the tactic state in addition to errors, use `tactic.resume` instead of `tactic.unwrap`. -/ meta constant ext_simplify_core {α : Type} (a : α) (c : simp_config) (s : simp_lemmas) (discharger : α → tactic α) (pre : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) (post : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) (r : name) : expr → tactic (α × expr × expr) private meta def is_equation : expr → bool | (expr.pi n bi d b) := is_equation b | e := match (expr.is_eq e) with (some a) := tt | none := ff end meta def collect_ctx_simps : tactic (list expr) := local_context section simp_intros meta def intro1_aux : bool → list name → tactic expr | ff _ := intro1 | tt (n::ns) := intro n | _ _ := failed structure simp_intros_config extends simp_config := (use_hyps := ff) meta def simp_intros_aux (cfg : simp_config) (use_hyps : bool) (to_unfold : list name) : simp_lemmas → bool → list name → tactic simp_lemmas | S tt [] := try (simp_target S to_unfold cfg) >> return S | S use_ns ns := do t ← target, if t.is_napp_of `not 1 then intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail else if t.is_arrow then do { d ← return t.binding_domain, (new_d, h_d_eq_new_d, lms) ← simplify S to_unfold d cfg, h_d ← intro1_aux use_ns ns, h_new_d ← mk_eq_mp h_d_eq_new_d h_d, assertv_core h_d.local_pp_name new_d h_new_d, clear h_d, h_new ← intro1, new_S ← if use_hyps then mcond (is_prop new_d) (S.add h_new ff) (return S) else return S, simp_intros_aux new_S use_ns ns.tail } <|> -- failed to simplify... we just introduce and continue (intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail) else if t.is_pi || t.is_let then intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail else do new_t ← whnf t reducible, if new_t.is_pi then unsafe_change new_t >> simp_intros_aux S use_ns ns else try (simp_target S to_unfold cfg) >> mcond (expr.is_pi <$> target) (simp_intros_aux S use_ns ns) (if use_ns ∧ ¬ns.empty then failed else return S) meta def simp_intros (s : simp_lemmas) (to_unfold : list name := []) (ids : list name := []) (cfg : simp_intros_config := {}) : tactic unit := step $ simp_intros_aux cfg.to_simp_config cfg.use_hyps to_unfold s (bnot ids.empty) ids end simp_intros meta def mk_eq_simp_ext (simp_ext : expr → tactic (expr × expr)) : tactic unit := do (lhs, rhs) ← target >>= match_eq, (new_rhs, heq) ← simp_ext lhs, unify rhs new_rhs, exact heq /-! Simp attribute support -/ meta def to_simp_lemmas : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (n::ns) := do S' ← (has_attribute `congr n >> S.add_congr n) <|> S.add_simp n ff, to_simp_lemmas S' ns meta def mk_simp_attr (attr_name : name) (attr_deps : list name := []) : command := do let t := `(user_attribute simp_lemmas), let v := `({name := attr_name, descr := "simplifier attribute", cache_cfg := { mk_cache := λ ns, do { s ← tactic.to_simp_lemmas simp_lemmas.mk ns, s ← attr_deps.mfoldl (λ s attr_name, do ns ← attribute.get_instances attr_name, to_simp_lemmas s ns) s, return s }, dependencies := `reducibility :: attr_deps}} : user_attribute simp_lemmas), let n := mk_simp_attr_decl_name attr_name, add_decl (declaration.defn n [] t v reducibility_hints.abbrev ff), attribute.register n /-- ### Example usage: ```lean -- make a new simp attribute called "my_reduction" run_cmd mk_simp_attr `my_reduction -- Add "my_reduction" attributes to these if-reductions attribute [my_reduction] if_pos if_neg dif_pos dif_neg -- will return the simp_lemmas with the `my_reduction` attribute. #eval get_user_simp_lemmas `my_reduction ``` -/ meta def get_user_simp_lemmas (attr_name : name) : tactic simp_lemmas := if attr_name = `default then simp_lemmas.mk_default else get_attribute_cache_dyn (mk_simp_attr_decl_name attr_name) meta def join_user_simp_lemmas_core : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (attr_name::R) := do S' ← get_user_simp_lemmas attr_name, join_user_simp_lemmas_core (S.join S') R meta def join_user_simp_lemmas (no_dflt : bool) (attrs : list name) : tactic simp_lemmas := do s ← simp_lemmas.mk_default, let s := if no_dflt then s.erase_simp_lemmas else s, join_user_simp_lemmas_core s attrs meta def simplify_top_down {α} (a : α) (pre : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← pre a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt)) (λ _ _ _ _ _, failed) `eq e meta def simp_top_down (pre : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit := do t ← target, (_, new_target, pr) ← simplify_top_down () (λ _ e, do (new_e, pr) ← pre e, return ((), new_e, pr)) t cfg, replace_target new_target pr ``id_tag.simp meta def simplify_bottom_up {α} (a : α) (post : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← post a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt)) `eq e meta def simp_bottom_up (post : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit := do t ← target, (_, new_target, pr) ← simplify_bottom_up () (λ _ e, do (new_e, pr) ← post e, return ((), new_e, pr)) t cfg, replace_target new_target pr ``id_tag.simp private meta def remove_deps (s : name_set) (h : expr) : name_set := if s.empty then s else h.fold s (λ e o s, if e.is_local_constant then s.erase e.local_uniq_name else s) /-- Return the list of hypothesis that are propositions and do not have forward dependencies. -/ meta def non_dep_prop_hyps : tactic (list expr) := do ctx ← local_context, s ← ctx.mfoldl (λ s h, do h_type ← infer_type h, let s := remove_deps s h_type, h_val ← head_zeta h, let s := if h_val =ₐ h then s else remove_deps s h_val, mcond (is_prop h_type) (return $ s.insert h.local_uniq_name) (return s)) mk_name_set, t ← target, let s := remove_deps s t, return $ ctx.filter (λ h, s.contains h.local_uniq_name) section simp_all meta structure simp_all_entry := (h : expr) -- hypothesis (new_type : expr) -- new type (pr : option expr) -- proof that type of h is equal to new_type (s : simp_lemmas) -- simplification lemmas for simplifying new_type private meta def update_simp_lemmas (es : list simp_all_entry) (h : expr) : tactic (list simp_all_entry) := es.mmap $ λ e, do new_s ← e.s.add h ff, return {s := new_s, ..e} /-- Helper tactic for `init`. Remark: the following tactic is quadratic on the length of list expr (the list of non dependent propositions). We can make it more efficient as soon as we have an efficient simp_lemmas.erase. -/ private meta def init_aux : list expr → simp_lemmas → list simp_all_entry → tactic (simp_lemmas × list simp_all_entry) | [] s r := return (s, r) | (h::hs) s r := do new_r ← update_simp_lemmas r h, new_s ← s.add h ff, h_type ← infer_type h, init_aux hs new_s (⟨h, h_type, none, s⟩::new_r) private meta def init (s : simp_lemmas) (hs : list expr) : tactic (simp_lemmas × list simp_all_entry) := init_aux hs s [] private meta def add_new_hyps (es : list simp_all_entry) : tactic unit := es.mmap' $ λ e, match e.pr with | none := return () | some pr := assert e.h.local_pp_name e.new_type >> mk_eq_mp pr e.h >>= exact end private meta def clear_old_hyps (es : list simp_all_entry) : tactic unit := es.mmap' $ λ e, when (e.pr ≠ none) (try (clear e.h)) private meta def join_pr : option expr → expr → tactic expr | none pr₂ := return pr₂ | (some pr₁) pr₂ := mk_eq_trans pr₁ pr₂ private meta def loop (cfg : simp_config) (discharger : tactic unit) (to_unfold : list name) : list simp_all_entry → list simp_all_entry → simp_lemmas → bool → tactic name_set | [] r s m := if m then loop r [] s ff else do add_new_hyps r, (lms, target_changed) ← (simp_target s to_unfold cfg discharger >>= λ ns, return (ns, tt)) <|> (return (mk_name_set, ff)), guard (cfg.fail_if_unchanged = ff ∨ target_changed ∨ r.any (λ e, e.pr ≠ none)) <|> fail "simp_all tactic failed to simplify", clear_old_hyps r, return lms | (e::es) r s m := do let ⟨h, h_type, h_pr, s'⟩ := e, (new_h_type, new_pr, lms) ← simplify s' to_unfold h_type {fail_if_unchanged := ff, ..cfg} `eq discharger, if h_type =ₐ new_h_type then do new_lms ← loop es (e::r) s m, return (new_lms.fold lms (λ n ns, name_set.insert ns n)) else do new_pr ← join_pr h_pr new_pr, new_fact_pr ← mk_eq_mp new_pr h, if new_h_type = `(false) then do tgt ← target, to_expr ``(@false.rec %%tgt %%new_fact_pr) >>= exact, return (mk_name_set) else do h0_type ← infer_type h, let new_fact_pr := mk_tagged_proof new_h_type new_fact_pr ``id_tag.simp, new_es ← update_simp_lemmas es new_fact_pr, new_r ← update_simp_lemmas r new_fact_pr, let new_r := {new_type := new_h_type, pr := new_pr, ..e} :: new_r, new_s ← s.add new_fact_pr ff, new_lms ← loop new_es new_r new_s tt, return (new_lms.fold lms (λ n ns, name_set.insert ns n)) meta def simp_all (s : simp_lemmas) (to_unfold : list name) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic name_set := do hs ← non_dep_prop_hyps, (s, es) ← init s hs, loop cfg discharger to_unfold es [] s ff end simp_all /-! debugging support for algebraic normalizer -/ meta constant trace_algebra_info : expr → tactic unit end tactic export tactic (mk_simp_attr) run_cmd mk_simp_attr `norm [`simp]
431af19718f40e0108071848c66872c5aa3fa78e
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/data/list/bigop.lean
89147bbb36838e5f88ac0574a84ff2e2f95e6bc7
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,348
lean
/- Copyright (c) 2015 Leonardo de Moura. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.list.bigop Authors: Leonardo de Moura Big operator for lists -/ import algebra.group data.list.comb data.list.set data.list.perm open algebra function binary quot namespace list variables {A B : Type} variable [g : group B] include g definition mulf (f : A → B) : B → A → B := λ b a, b * f a definition bigop (l : list A) (f : A → B) : B := foldl (mulf f) 1 l private theorem foldl_const (f : A → B) : ∀ (l : list A) (b : B), foldl (mulf f) b l = b * foldl (mulf f) 1 l | [] b := by rewrite [*foldl_nil, mul_one] | (a::l) b := by rewrite [*foldl_cons, foldl_const, {foldl _ (mulf f 1 a) _}foldl_const, ↑mulf, one_mul, mul.assoc] theorem bigop_nil (f : A → B) : bigop [] f = 1 := rfl theorem bigop_cons (f : A → B) (a : A) (l : list A) : bigop (a::l) f = f a * bigop l f := by rewrite [↑bigop, foldl_cons, foldl_const, ↑mulf, one_mul] theorem bigop_append : ∀ (l₁ l₂ : list A) (f : A → B), bigop (l₁++l₂) f = bigop l₁ f * bigop l₂ f | [] l₂ f := by rewrite [append_nil_left, bigop_nil, one_mul] | (a::l) l₂ f := by rewrite [append_cons, *bigop_cons, bigop_append, mul.assoc] section insert variable [H : decidable_eq A] include H theorem bigop_insert_of_mem (f : A → B) {a : A} {l : list A} : a ∈ l → bigop (insert a l) f = bigop l f := assume ainl, by rewrite [insert_eq_of_mem ainl] theorem bigop_insert_of_not_mem (f : A → B) {a : A} {l : list A} : a ∉ l → bigop (insert a l) f = f a * bigop l f := assume nainl, by rewrite [insert_eq_of_not_mem nainl, bigop_cons] end insert section union variable [H : decidable_eq A] include H definition bigop_union {l₁ l₂ : list A} (f : A → B) (d : disjoint l₁ l₂) : bigop (union l₁ l₂) f = bigop l₁ f * bigop l₂ f := by rewrite [union_eq_append d, bigop_append] end union end list namespace list open perm variables {A B : Type} variable [g : comm_group B] include g theorem mulf_rcomm (f : A → B) : right_commutative (mulf f) := right_commutative_compose_right (@has_mul.mul B g) f (@mul.right_comm B g) theorem bigop_of_perm (f : A → B) {l₁ l₂ : list A} : l₁ ~ l₂ → bigop l₁ f = bigop l₂ f := λ p, foldl_eq_of_perm (mulf_rcomm f) p 1 end list
eeb616fcfb2bf5a6aa572a6ae7d7e74b529cc054
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/int/modeq.lean
4518058ae396c5380c7972a8f24f2d974907768f
[ "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
6,052
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.basic data.nat.modeq import tactic namespace int def modeq (n a b : ℤ) := a % n = b % n notation a ` ≡ `:50 b ` [ZMOD `:50 n `]`:0 := modeq n a b namespace modeq variables {n m a b c d : ℤ} @[refl] protected theorem refl (a : ℤ) : a ≡ a [ZMOD n] := @rfl _ _ @[symm] protected theorem symm : a ≡ b [ZMOD n] → b ≡ a [ZMOD n] := eq.symm @[trans] protected theorem trans : a ≡ b [ZMOD n] → b ≡ c [ZMOD n] → a ≡ c [ZMOD n] := eq.trans lemma coe_nat_modeq_iff {a b n : ℕ} : a ≡ b [ZMOD n] ↔ a ≡ b [MOD n] := by unfold modeq nat.modeq; rw ← int.coe_nat_eq_coe_nat_iff; simp [int.coe_nat_mod] instance : decidable (a ≡ b [ZMOD n]) := by unfold modeq; apply_instance theorem modeq_zero_iff : a ≡ 0 [ZMOD n] ↔ n ∣ a := by rw [modeq, zero_mod, dvd_iff_mod_eq_zero] theorem modeq_iff_dvd : a ≡ b [ZMOD n] ↔ (n:ℤ) ∣ b - a := by rw [modeq, eq_comm]; simp [int.mod_eq_mod_iff_mod_sub_eq_zero, int.dvd_iff_mod_eq_zero, -euclidean_domain.mod_eq_zero] theorem modeq_of_dvd_of_modeq (d : m ∣ n) (h : a ≡ b [ZMOD n]) : a ≡ b [ZMOD m] := modeq_iff_dvd.2 $ dvd_trans d (modeq_iff_dvd.1 h) theorem modeq_mul_left' (hc : 0 ≤ c) (h : a ≡ b [ZMOD n]) : c * a ≡ c * b [ZMOD (c * n)] := or.cases_on (lt_or_eq_of_le hc) (λ hc, by unfold modeq; simp [mul_mod_mul_of_pos _ _ hc, (show _ = _, from h)] ) (λ hc, by simp [hc.symm]) theorem modeq_mul_right' (hc : 0 ≤ c) (h : a ≡ b [ZMOD n]) : a * c ≡ b * c [ZMOD (n * c)] := by rw [mul_comm a, mul_comm b, mul_comm n]; exact modeq_mul_left' hc h theorem modeq_add (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a + c ≡ b + d [ZMOD n] := modeq_iff_dvd.2 $ by {convert dvd_add (modeq_iff_dvd.1 h₁) (modeq_iff_dvd.1 h₂), ring} theorem modeq_add_cancel_left (h₁ : a ≡ b [ZMOD n]) (h₂ : a + c ≡ b + d [ZMOD n]) : c ≡ d [ZMOD n] := have d - c = b + d - (a + c) - (b - a) := by ring, modeq_iff_dvd.2 $ by { rw [this], exact dvd_sub (modeq_iff_dvd.1 h₂) (modeq_iff_dvd.1 h₁) } theorem modeq_add_cancel_right (h₁ : c ≡ d [ZMOD n]) (h₂ : a + c ≡ b + d [ZMOD n]) : a ≡ b [ZMOD n] := by rw [add_comm a, add_comm b] at h₂; exact modeq_add_cancel_left h₁ h₂ theorem mod_modeq (a n) : a % n ≡ a [ZMOD n] := int.mod_mod _ _ theorem modeq_neg (h : a ≡ b [ZMOD n]) : -a ≡ -b [ZMOD n] := modeq_add_cancel_left h (by simp) theorem modeq_sub (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a - c ≡ b - d [ZMOD n] := by rw [sub_eq_add_neg, sub_eq_add_neg]; exact modeq_add h₁ (modeq_neg h₂) theorem modeq_mul_left (c : ℤ) (h : a ≡ b [ZMOD n]) : c * a ≡ c * b [ZMOD n] := or.cases_on (le_total 0 c) (λ hc, modeq_of_dvd_of_modeq (dvd_mul_left _ _) (modeq_mul_left' hc h)) (λ hc, by rw [← neg_neg c, ← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul _ b]; exact modeq_neg (modeq_of_dvd_of_modeq (dvd_mul_left _ _) (modeq_mul_left' (neg_nonneg.2 hc) h))) theorem modeq_mul_right (c : ℤ) (h : a ≡ b [ZMOD n]) : a * c ≡ b * c [ZMOD n] := by rw [mul_comm a, mul_comm b]; exact modeq_mul_left c h theorem modeq_mul (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a * c ≡ b * d [ZMOD n] := (modeq_mul_left _ h₂).trans (modeq_mul_right _ h₁) theorem modeq_of_modeq_mul_left (m : ℤ) (h : a ≡ b [ZMOD m * n]) : a ≡ b [ZMOD n] := by rw [modeq_iff_dvd] at *; exact dvd.trans (dvd_mul_left n m) h theorem modeq_of_modeq_mul_right (m : ℤ) : a ≡ b [ZMOD n * m] → a ≡ b [ZMOD n] := mul_comm m n ▸ modeq_of_modeq_mul_left _ lemma modeq_and_modeq_iff_modeq_mul {a b m n : ℤ} (hmn : nat.coprime m.nat_abs n.nat_abs) : a ≡ b [ZMOD m] ∧ a ≡ b [ZMOD n] ↔ (a ≡ b [ZMOD m * n]) := ⟨λ h, begin rw [int.modeq.modeq_iff_dvd, int.modeq.modeq_iff_dvd] at h, rw [int.modeq.modeq_iff_dvd, ← int.nat_abs_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd, int.nat_abs_mul], refine hmn.mul_dvd_of_dvd_of_dvd _ _; rw [← int.coe_nat_dvd, int.nat_abs_dvd, int.dvd_nat_abs]; tauto end, λ h, ⟨int.modeq.modeq_of_modeq_mul_right _ h, int.modeq.modeq_of_modeq_mul_left _ h⟩⟩ lemma gcd_a_modeq (a b : ℕ) : (a : ℤ) * nat.gcd_a a b ≡ nat.gcd a b [ZMOD b] := by rw [← add_zero ((a : ℤ) * _), nat.gcd_eq_gcd_ab]; exact int.modeq.modeq_add rfl (int.modeq.modeq_zero_iff.2 (dvd_mul_right _ _)).symm theorem modeq_add_fac {a b n : ℤ} (c : ℤ) (ha : a ≡ b [ZMOD n]) : a + n*c ≡ b [ZMOD n] := calc a + n*c ≡ b + n*c [ZMOD n] : int.modeq.modeq_add ha (int.modeq.refl _) ... ≡ b + 0 [ZMOD n] : int.modeq.modeq_add (int.modeq.refl _) (int.modeq.modeq_zero_iff.2 (dvd_mul_right _ _)) ... ≡ b [ZMOD n] : by simp open nat lemma mod_coprime {a b : ℕ} (hab : coprime a b) : ∃ y : ℤ, a * y ≡ 1 [ZMOD b] := ⟨ gcd_a a b, have hgcd : nat.gcd a b = 1, from coprime.gcd_eq_one hab, calc ↑a * gcd_a a b ≡ ↑a*gcd_a a b + ↑b*gcd_b a b [ZMOD ↑b] : int.modeq.symm $ modeq_add_fac _ $ int.modeq.refl _ ... ≡ 1 [ZMOD ↑b] : by rw [←gcd_eq_gcd_ab, hgcd]; reflexivity ⟩ lemma exists_unique_equiv (a : ℤ) {b : ℤ} (hb : 0 < b) : ∃ z : ℤ, 0 ≤ z ∧ z < b ∧ z ≡ a [ZMOD b] := ⟨ a % b, int.mod_nonneg _ (ne_of_gt hb), have a % b < abs b, from int.mod_lt _ (ne_of_gt hb), by rwa abs_of_pos hb at this, by simp [int.modeq] ⟩ lemma exists_unique_equiv_nat (a : ℤ) {b : ℤ} (hb : 0 < b) : ∃ z : ℕ, ↑z < b ∧ ↑z ≡ a [ZMOD b] := let ⟨z, hz1, hz2, hz3⟩ := exists_unique_equiv a hb in ⟨z.nat_abs, by split; rw [←int.of_nat_eq_coe, int.of_nat_nat_abs_eq_of_nonneg hz1]; assumption⟩ end modeq @[simp] lemma mod_mul_right_mod (a b c : ℤ) : a % (b * c) % b = a % b := int.modeq.modeq_of_modeq_mul_right _ (int.modeq.mod_modeq _ _) @[simp] lemma mod_mul_left_mod (a b c : ℤ) : a % (b * c) % c = a % c := int.modeq.modeq_of_modeq_mul_left _ (int.modeq.mod_modeq _ _) end int
ce3c8ca4e55e3485c9bda17e9800013a16e8dc76
4727251e0cd73359b15b664c3170e5d754078599
/src/data/finset/fold.lean
725e3bfd48945d09d55e723c8ecd7c452fd0d076
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
8,127
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.finset.basic import data.multiset.fold /-! # The fold operation for a commutative associative operation over a finset. -/ namespace finset open multiset variables {α β γ : Type*} /-! ### fold -/ section fold variables (op : β → β → β) [hc : is_commutative β op] [ha : is_associative β op] local notation a * b := op a b include hc ha /-- `fold op b f s` folds the commutative associative operation `op` over the `f`-image of `s`, i.e. `fold (+) b f {1,2,3} = f 1 + f 2 + f 3 + b`. -/ def fold (b : β) (f : α → β) (s : finset α) : β := (s.1.map f).fold op b variables {op} {f : α → β} {b : β} {s : finset α} {a : α} @[simp] theorem fold_empty : (∅ : finset α).fold op b f = b := rfl @[simp] theorem fold_cons (h : a ∉ s) : (cons a s h).fold op b f = f a * s.fold op b f := by { dunfold fold, rw [cons_val, map_cons, fold_cons_left], } @[simp] theorem fold_insert [decidable_eq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f := by unfold fold; rw [insert_val, ndinsert_of_not_mem h, map_cons, fold_cons_left] @[simp] theorem fold_singleton : ({a} : finset α).fold op b f = f a * b := rfl @[simp] theorem fold_map {g : γ ↪ α} {s : finset γ} : (s.map g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, map, multiset.map_map] @[simp] theorem fold_image [decidable_eq α] {g : γ → α} {s : finset γ} (H : ∀ (x ∈ s) (y ∈ s), g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, image_val_of_inj_on H, multiset.map_map] @[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g := by rw [fold, fold, map_congr rfl H] theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} : s.fold op (b₁ * b₂) (λx, f x * g x) = s.fold op b₁ f * s.fold op b₂ g := by simp only [fold, fold_distrib] lemma fold_const [decidable (s = ∅)] (c : β) (h : op c (op b c) = op b c) : finset.fold op b (λ _, c) s = if s = ∅ then b else op b c := begin classical, unfreezingI { induction s using finset.induction_on with x s hx IH }, { simp }, { simp only [finset.fold_insert hx, IH, if_false, finset.insert_ne_empty], split_ifs, { rw hc.comm }, { exact h } } end theorem fold_hom {op' : γ → γ → γ} [is_commutative γ op'] [is_associative γ op'] {m : β → γ} (hm : ∀x y, m (op x y) = op' (m x) (m y)) : s.fold op' (m b) (λx, m (f x)) = m (s.fold op b f) := by rw [fold, fold, ← fold_hom op hm, multiset.map_map] theorem fold_union_inter [decidable_eq α] {s₁ s₂ : finset α} {b₁ b₂ : β} : (s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f = s₁.fold op b₂ f * s₂.fold op b₁ f := by unfold fold; rw [← fold_add op, ← multiset.map_add, union_val, inter_val, union_add_inter, multiset.map_add, hc.comm, fold_add] @[simp] theorem fold_insert_idem [decidable_eq α] [hi : is_idempotent β op] : (insert a s).fold op b f = f a * s.fold op b f := begin by_cases (a ∈ s), { rw [← insert_erase h], simp [← ha.assoc, hi.idempotent] }, { apply fold_insert h }, end theorem fold_image_idem [decidable_eq α] {g : γ → α} {s : finset γ} [hi : is_idempotent β op] : (image g s).fold op b f = s.fold op b (f ∘ g) := begin induction s using finset.cons_induction with x xs hx ih, { rw [fold_empty, image_empty, fold_empty] }, { haveI := classical.dec_eq γ, rw [fold_cons, cons_eq_insert, image_insert, fold_insert_idem, ih], } end /-- A stronger version of `finset.fold_ite`, but relies on an explicit proof of idempotency on the seed element, rather than relying on typeclass idempotency over the whole type. -/ lemma fold_ite' {g : α → β} (hb : op b b = b) (p : α → Prop) [decidable_pred p] : finset.fold op b (λ i, ite (p i) (f i) (g i)) s = op (finset.fold op b f (s.filter p)) (finset.fold op b g (s.filter (λ i, ¬ p i))) := begin classical, induction s using finset.induction_on with x s hx IH, { simp [hb] }, { simp only [finset.filter_congr_decidable, finset.fold_insert hx], split_ifs with h h, { have : x ∉ finset.filter p s, { simp [hx] }, simp [finset.filter_insert, h, finset.fold_insert this, ha.assoc, IH] }, { have : x ∉ finset.filter (λ i, ¬ p i) s, { simp [hx] }, simp [finset.filter_insert, h, finset.fold_insert this, IH, ←ha.assoc, hc.comm] } } end /-- A weaker version of `finset.fold_ite'`, relying on typeclass idempotency over the whole type, instead of solely on the seed element. However, this is easier to use because it does not generate side goals. -/ lemma fold_ite [is_idempotent β op] {g : α → β} (p : α → Prop) [decidable_pred p] : finset.fold op b (λ i, ite (p i) (f i) (g i)) s = op (finset.fold op b f (s.filter p)) (finset.fold op b g (s.filter (λ i, ¬ p i))) := fold_ite' (is_idempotent.idempotent _) _ lemma fold_op_rel_iff_and {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∧ r x z)) {c : β} : r c (s.fold op b f) ↔ (r c b ∧ ∀ x∈s, r c (f x)) := begin classical, apply finset.induction_on s, { simp }, clear s, intros a s ha IH, rw [finset.fold_insert ha, hr, IH, ← and_assoc, and_comm (r c (f a)), and_assoc], apply and_congr iff.rfl, split, { rintro ⟨h₁, h₂⟩, intros b hb, rw finset.mem_insert at hb, rcases hb with rfl|hb; solve_by_elim }, { intro h, split, { exact h a (finset.mem_insert_self _ _), }, { intros b hb, apply h b, rw finset.mem_insert, right, exact hb } } end lemma fold_op_rel_iff_or {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∨ r x z)) {c : β} : r c (s.fold op b f) ↔ (r c b ∨ ∃ x∈s, r c (f x)) := begin classical, apply finset.induction_on s, { simp }, clear s, intros a s ha IH, rw [finset.fold_insert ha, hr, IH, ← or_assoc, or_comm (r c (f a)), or_assoc], apply or_congr iff.rfl, split, { rintro (h₁|⟨x, hx, h₂⟩), { use a, simp [h₁] }, { refine ⟨x, by simp [hx], h₂⟩ } }, { rintro ⟨x, hx, h⟩, rw mem_insert at hx, cases hx, { left, rwa hx at h }, { right, exact ⟨x, hx, h⟩ } } end omit hc ha @[simp] lemma fold_union_empty_singleton [decidable_eq α] (s : finset α) : finset.fold (∪) ∅ singleton s = s := begin apply finset.induction_on s, { simp only [fold_empty], }, { intros a s has ih, rw [fold_insert has, ih, insert_eq], } end lemma fold_sup_bot_singleton [decidable_eq α] (s : finset α) : finset.fold (⊔) ⊥ singleton s = s := fold_union_empty_singleton s section order variables [linear_order β] (c : β) lemma le_fold_min : c ≤ s.fold min b f ↔ (c ≤ b ∧ ∀ x∈s, c ≤ f x) := fold_op_rel_iff_and $ λ x y z, le_min_iff lemma fold_min_le : s.fold min b f ≤ c ↔ (b ≤ c ∨ ∃ x∈s, f x ≤ c) := begin show _ ≥ _ ↔ _, apply fold_op_rel_iff_or, intros x y z, show _ ≤ _ ↔ _, exact min_le_iff end lemma lt_fold_min : c < s.fold min b f ↔ (c < b ∧ ∀ x∈s, c < f x) := fold_op_rel_iff_and $ λ x y z, lt_min_iff lemma fold_min_lt : s.fold min b f < c ↔ (b < c ∨ ∃ x∈s, f x < c) := begin show _ > _ ↔ _, apply fold_op_rel_iff_or, intros x y z, show _ < _ ↔ _, exact min_lt_iff end lemma fold_max_le : s.fold max b f ≤ c ↔ (b ≤ c ∧ ∀ x∈s, f x ≤ c) := begin show _ ≥ _ ↔ _, apply fold_op_rel_iff_and, intros x y z, show _ ≤ _ ↔ _, exact max_le_iff end lemma le_fold_max : c ≤ s.fold max b f ↔ (c ≤ b ∨ ∃ x∈s, c ≤ f x) := fold_op_rel_iff_or $ λ x y z, le_max_iff lemma fold_max_lt : s.fold max b f < c ↔ (b < c ∧ ∀ x∈s, f x < c) := begin show _ > _ ↔ _, apply fold_op_rel_iff_and, intros x y z, show _ < _ ↔ _, exact max_lt_iff end lemma lt_fold_max : c < s.fold max b f ↔ (c < b ∨ ∃ x∈s, c < f x) := fold_op_rel_iff_or $ λ x y z, lt_max_iff end order end fold end finset
e29df90fad8edc28d531009a6fc79bf8d1a2a6ed
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/ideal/operations.lean
aef44435a9b5a6370240e4c8ff14ce19ddade7f6
[ "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
79,216
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.ring.equiv import data.nat.choose.sum import linear_algebra.basis.bilinear import ring_theory.coprime.lemmas import ring_theory.ideal.basic import ring_theory.non_zero_divisors /-! # More operations on modules and ideals > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ universes u v w x open_locale big_operators pointwise namespace submodule variables {R : Type u} {M : Type v} {F : Type*} {G : Type*} section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [module R M] open_locale pointwise instance has_smul' : has_smul (ideal R) (submodule R M) := ⟨submodule.map₂ (linear_map.lsmul R M)⟩ /-- This duplicates the global `smul_eq_mul`, but doesn't have to unfold anywhere near as much to apply. -/ protected lemma _root_.ideal.smul_eq_mul (I J : ideal R) : I • J = I * J := rfl /-- `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 variables {I J : ideal R} {N 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 : M →ₗ[R] M)) ⊥ := mem_annihilator.trans ⟨λ H n hn, (mem_bot R).2 $ H n hn, λ H n hn, (mem_bot R).1 $ H hn⟩ lemma mem_annihilator_span (s : set M) (r : R) : r ∈ (submodule.span R s).annihilator ↔ ∀ n : s, r • (n : M) = 0 := begin rw submodule.mem_annihilator, split, { intros h n, exact h _ (submodule.subset_span n.prop) }, { intros h n hn, apply submodule.span_induction hn, { intros x hx, exact h ⟨x, hx⟩ }, { exact smul_zero _ }, { intros x y hx hy, rw [smul_add, hx, hy, zero_add] }, { intros a x hx, rw [smul_comm, hx, smul_zero] } } end lemma mem_annihilator_span_singleton (g : M) (r : R) : r ∈ (submodule.span R ({g} : set M)).annihilator ↔ r • g = 0 := by simp [mem_annihilator_span] 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 smul_mem_smul {r} {n} (hr : r ∈ I) (hn : n ∈ N) : r • n ∈ I • N := apply_mem_map₂ _ hr hn theorem smul_le {P : submodule R M} : I • N ≤ P ↔ ∀ (r ∈ I) (n ∈ N), r • n ∈ P := map₂_le @[elab_as_eliminator] theorem smul_induction_on {p : M → Prop} {x} (H : x ∈ I • N) (Hb : ∀ (r ∈ I) (n ∈ N), p (r • n)) (H1 : ∀ x y, p x → p y → p (x + y)) : p x := begin have H0 : p 0 := by simpa only [zero_smul] using Hb 0 I.zero_mem 0 N.zero_mem, refine submodule.supr_induction _ H _ H0 H1, rintros ⟨i, hi⟩ m ⟨j, hj, (rfl : i • _ = m) ⟩, exact Hb _ hi _ hj, end /-- Dependent version of `submodule.smul_induction_on`. -/ @[elab_as_eliminator] theorem smul_induction_on' {x : M} (hx : x ∈ I • N) {p : Π x, x ∈ I • N → Prop} (Hb : ∀ (r : R) (hr : r ∈ I) (n : M) (hn : n ∈ N), p (r • n) (smul_mem_smul hr hn)) (H1 : ∀ x hx y hy, p x hx → p y hy → p (x + y) (submodule.add_mem _ ‹_› ‹_›)) : p x hx := begin refine exists.elim _ (λ (h : x ∈ I • N) (H : p x h), H), exact smul_induction_on hx (λ a ha x hx, ⟨_, Hb _ ha _ hx⟩) (λ x y ⟨_, hx⟩ ⟨_, hy⟩, ⟨_, H1 _ _ _ _ hx hy⟩), end 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⟩) (λ m1 m2 ⟨y1, hyi1, hy1⟩ ⟨y2, hyi2, hy2⟩, ⟨y1 + y2, I.add_mem hyi1 hyi2, by rw [add_smul, hy1, hy2]⟩), λ ⟨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 := map₂_le_map₂ hij hnp theorem smul_mono_left (h : I ≤ J) : I • N ≤ J • N := map₂_le_map₂_left h theorem smul_mono_right (h : N ≤ P) : I • N ≤ I • P := map₂_le_map₂_right h lemma map_le_smul_top (I : ideal R) (f : R →ₗ[R] M) : submodule.map f I ≤ I • (⊤ : submodule R M) := begin rintros _ ⟨y, hy, rfl⟩, rw [← mul_one y, ← smul_eq_mul, f.map_smul], exact smul_mem_smul hy mem_top end @[simp] theorem annihilator_smul (N : submodule R M) : annihilator N • N = ⊥ := eq_bot_iff.2 (smul_le.2 (λ r, mem_annihilator.1)) @[simp] theorem annihilator_mul (I : ideal R) : annihilator I * I = ⊥ := annihilator_smul I @[simp] theorem mul_annihilator (I : ideal R) : I * annihilator I = ⊥ := by rw [mul_comm, annihilator_mul] variables (I J N P) @[simp] theorem smul_bot : I • (⊥ : submodule R M) = ⊥ := map₂_bot_right _ _ @[simp] theorem bot_smul : (⊥ : ideal R) • N = ⊥ := map₂_bot_left _ _ @[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 := map₂_sup_right _ _ _ _ theorem sup_smul : (I ⊔ J) • N = I • N ⊔ J • N := map₂_sup_left _ _ _ _ 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)) (λ x y, (add_smul x y t).symm ▸ submodule.add_mem _)) (smul_le.2 $ λ r hr sn hsn, suffices J • N ≤ submodule.comap (r • (linear_map.id : M →ₗ[R] M)) ((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) lemma smul_inf_le (M₁ M₂ : submodule R M) : I • (M₁ ⊓ M₂) ≤ I • M₁ ⊓ I • M₂ := le_inf (submodule.smul_mono_right inf_le_left) (submodule.smul_mono_right inf_le_right) lemma smul_supr {ι : Sort*} {I : ideal R} {t : ι → submodule R M} : I • supr t = ⨆ i, I • t i := map₂_supr_right _ _ _ lemma smul_infi_le {ι : Sort*} {I : ideal R} {t : ι → submodule R M} : I • infi t ≤ ⨅ i, I • t i := le_infi (λ i, smul_mono_right (infi_le _ _)) 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}) := (map₂_span_span _ _ _ _).trans $ congr_arg _ $ set.image2_eq_Union _ _ _ lemma ideal_span_singleton_smul (r : R) (N : submodule R M) : (ideal.span {r} : ideal R) • N = r • N := begin have : span R (⋃ (t : M) (x : t ∈ N), {r • t}) = r • N, { convert span_eq _, exact (set.image_eq_Union _ (N : set M)).symm }, conv_lhs { rw [← span_eq N, span_smul_span] }, simpa end lemma mem_of_span_top_of_smul_mem (M' : submodule R M) (s : set R) (hs : ideal.span s = ⊤) (x : M) (H : ∀ r : s, (r : R) • x ∈ M') : x ∈ M' := begin suffices : (⊤ : ideal R) • (span R ({x} : set M)) ≤ M', { rw top_smul at this, exact this (subset_span (set.mem_singleton x)) }, rw [← hs, span_smul_span, span_le], simpa using H end /-- Given `s`, a generating set of `R`, to check that an `x : M` falls in a submodule `M'` of `x`, we only need to show that `r ^ n • x ∈ M'` for some `n` for each `r : s`. -/ lemma mem_of_span_eq_top_of_smul_pow_mem (M' : submodule R M) (s : set R) (hs : ideal.span s = ⊤) (x : M) (H : ∀ r : s, ∃ (n : ℕ), (r ^ n : R) • x ∈ M') : x ∈ M' := begin obtain ⟨s', hs₁, hs₂⟩ := (ideal.span_eq_top_iff_finite _).mp hs, replace H : ∀ r : s', ∃ (n : ℕ), (r ^ n : R) • x ∈ M' := λ r, H ⟨_, hs₁ r.prop⟩, choose n₁ n₂ using H, let N := s'.attach.sup n₁, have hs' := ideal.span_pow_eq_top (s' : set R) hs₂ N, apply M'.mem_of_span_top_of_smul_mem _ hs', rintro ⟨_, r, hr, rfl⟩, convert M'.smul_mem (r ^ (N - n₁ ⟨r, hr⟩)) (n₂ ⟨r, hr⟩) using 1, simp only [subtype.coe_mk, smul_smul, ← pow_add], rw tsub_add_cancel_of_le (finset.le_sup (s'.mem_attach _) : n₁ ⟨r, hr⟩ ≤ N), end variables {M' : Type w} [add_comm_monoid 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) variables {I} lemma mem_smul_span {s : set M} {x : M} : x ∈ I • submodule.span R s ↔ x ∈ submodule.span R (⋃ (a ∈ I) (b ∈ s), ({a • b} : set M)) := by rw [← I.span_eq, submodule.span_smul_span, I.span_eq]; refl variables (I) /-- If `x` is an `I`-multiple of the submodule spanned by `f '' s`, then we can write `x` as an `I`-linear combination of the elements of `f '' s`. -/ lemma mem_ideal_smul_span_iff_exists_sum {ι : Type*} (f : ι → M) (x : M) : x ∈ I • span R (set.range f) ↔ ∃ (a : ι →₀ R) (ha : ∀ i, a i ∈ I), a.sum (λ i c, c • f i) = x := begin split, swap, { rintro ⟨a, ha, rfl⟩, exact submodule.sum_mem _ (λ c _, smul_mem_smul (ha c) $ subset_span $ set.mem_range_self _) }, refine λ hx, span_induction (mem_smul_span.mp hx) _ _ _ _, { simp only [set.mem_Union, set.mem_range, set.mem_singleton_iff], rintros x ⟨y, hy, x, ⟨i, rfl⟩, rfl⟩, refine ⟨finsupp.single i y, λ j, _, _⟩, { letI := classical.dec_eq ι, rw finsupp.single_apply, split_ifs, { assumption }, { exact I.zero_mem } }, refine @finsupp.sum_single_index ι R M _ _ i _ (λ i y, y • f i) _, simp }, { exact ⟨0, λ i, I.zero_mem, finsupp.sum_zero_index⟩ }, { rintros x y ⟨ax, hax, rfl⟩ ⟨ay, hay, rfl⟩, refine ⟨ax + ay, λ i, I.add_mem (hax i) (hay i), finsupp.sum_add_index' _ _⟩; intros; simp only [zero_smul, add_smul] }, { rintros c x ⟨a, ha, rfl⟩, refine ⟨c • a, λ i, I.mul_mem_left c (ha i), _⟩, rw [finsupp.sum_smul_index, finsupp.smul_sum]; intros; simp only [zero_smul, mul_smul] }, end theorem mem_ideal_smul_span_iff_exists_sum' {ι : Type*} (s : set ι) (f : ι → M) (x : M) : x ∈ I • span R (f '' s) ↔ ∃ (a : s →₀ R) (ha : ∀ i, a i ∈ I), a.sum (λ i c, c • f i) = x := by rw [← submodule.mem_ideal_smul_span_iff_exists_sum, ← set.image_eq_range] lemma mem_smul_top_iff (N : submodule R M) (x : N) : x ∈ I • (⊤ : submodule R N) ↔ (x : M) ∈ I • N := begin change _ ↔ N.subtype x ∈ I • N, have : submodule.map N.subtype (I • ⊤) = I • N, { rw [submodule.map_smul'', submodule.map_top, submodule.range_subtype] }, rw ← this, convert (function.injective.mem_set_image N.injective_subtype).symm using 1, refl, end @[simp] lemma smul_comap_le_comap_smul (f : M →ₗ[R] M') (S : submodule R M') (I : ideal R) : I • S.comap f ≤ (I • S).comap f := begin refine (submodule.smul_le.mpr (λ r hr x hx, _)), rw [submodule.mem_comap] at ⊢ hx, rw f.map_smul, exact submodule.smul_mem_smul hr hx end end comm_semiring section comm_ring variables [comm_ring R] [add_comm_group M] [module R M] variables {N N₁ N₂ P P₁ P₂ : submodule R M} /-- `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) 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 : M →ₗ[R] M)) 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) @[simp] lemma mem_colon_singleton {N : submodule R M} {x : M} {r : R} : r ∈ N.colon (submodule.span R {x}) ↔ r • x ∈ N := calc r ∈ N.colon (submodule.span R {x}) ↔ ∀ (a : R), r • (a • x) ∈ N : by simp [submodule.mem_colon, submodule.mem_span_singleton] ... ↔ r • x ∈ N : by { simp_rw [smul_comm r]; exact set_like.forall_smul_mem_iff } @[simp] lemma _root_.ideal.mem_colon_singleton {I : ideal R} {x r : R} : r ∈ I.colon (ideal.span {x}) ↔ r * x ∈ I := by simp [← ideal.submodule_span_eq, submodule.mem_colon_singleton, smul_eq_mul] end comm_ring end submodule namespace ideal section add variables {R : Type u} [semiring R] @[simp] lemma add_eq_sup {I J : ideal R} : I + J = I ⊔ J := rfl @[simp] lemma zero_eq_bot : (0 : ideal R) = ⊥ := rfl @[simp] lemma sum_eq_sup {ι : Type*} (s : finset ι) (f : ι → ideal R) : s.sum f = s.sup f := rfl end add section mul_and_radical variables {R : Type u} {ι : Type*} [comm_semiring R] variables {I J K L : ideal R} instance : has_mul (ideal R) := ⟨(•)⟩ @[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 := submodule.pow_mem_pow _ hx _ lemma prod_mem_prod {ι : Type*} {s : finset ι} {I : ι → ideal R} {x : ι → R} : (∀ i ∈ s, x i ∈ I i) → ∏ i in s, x i ∈ ∏ i in s, I i := begin classical, apply finset.induction_on s, { intro _, rw [finset.prod_empty, finset.prod_empty, one_eq_top], exact submodule.mem_top }, { intros a s ha IH h, rw [finset.prod_insert ha, finset.prod_insert ha], exact mul_mem_mul (h a $ finset.mem_insert_self a s) (IH $ λ i hi, h i $ finset.mem_insert_of_mem hi) } 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 span_singleton_mul_right_mono [is_domain R] {x : R} (hx : x ≠ 0) : span {x} * I ≤ span {x} * J ↔ I ≤ J := by simp_rw [span_singleton_mul_le_span_singleton_mul, mul_right_inj' hx, exists_prop, exists_eq_right', set_like.le_def] lemma span_singleton_mul_left_mono [is_domain R] {x : R} (hx : x ≠ 0) : I * span {x} ≤ J * span {x} ↔ I ≤ J := by simpa only [mul_comm I, mul_comm J] using span_singleton_mul_right_mono hx lemma span_singleton_mul_right_inj [is_domain R] {x : R} (hx : x ≠ 0) : span {x} * I = span {x} * J ↔ I = J := by simp only [le_antisymm_iff, span_singleton_mul_right_mono hx] lemma span_singleton_mul_left_inj [is_domain R] {x : R} (hx : x ≠ 0) : I * span {x} = J * span {x} ↔ I = J := by simp only [le_antisymm_iff, span_singleton_mul_left_mono hx] lemma span_singleton_mul_right_injective [is_domain R] {x : R} (hx : x ≠ 0) : function.injective ((*) (span {x} : ideal R)) := λ _ _, (span_singleton_mul_right_inj hx).mp lemma span_singleton_mul_left_injective [is_domain R] {x : R} (hx : x ≠ 0) : function.injective (λ I : ideal R, I * span {x}) := λ _ _, (span_singleton_mul_left_inj hx).mp 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] lemma prod_span {ι : Type*} (s : finset ι) (I : ι → set R) : (∏ i in s, ideal.span (I i)) = ideal.span (∏ i in s, I i) := submodule.prod_span s I lemma prod_span_singleton {ι : Type*} (s : finset ι) (I : ι → R) : (∏ i in s, ideal.span ({I i} : set R)) = ideal.span {∏ i in s, I i} := submodule.prod_span_singleton s I @[simp] lemma multiset_prod_span_singleton (m : multiset R) : (m.map (λ x, ideal.span {x})).prod = ideal.span ({multiset.prod m} : set R) := multiset.induction_on m (by simp) (λ a m ih, by simp only [multiset.map_cons, multiset.prod_cons, ih, ← ideal.span_singleton_mul_span_singleton]) lemma finset_inf_span_singleton {ι : Type*} (s : finset ι) (I : ι → R) (hI : set.pairwise ↑s (is_coprime on I)) : (s.inf $ λ i, ideal.span ({I i} : set R)) = ideal.span {∏ i in s, I i} := begin ext x, simp only [submodule.mem_finset_inf, ideal.mem_span_singleton], exact ⟨finset.prod_dvd_of_coprime hI, λ h i hi, (finset.dvd_prod_of_mem _ hi).trans h⟩ end lemma infi_span_singleton {ι : Type*} [fintype ι] (I : ι → R) (hI : ∀ i j (hij : i ≠ j), is_coprime (I i) (I j)): (⨅ i, ideal.span ({I i} : set R)) = ideal.span {∏ i, I i} := begin rw [← finset.inf_univ_eq_infi, finset_inf_span_singleton], rwa [finset.coe_univ, set.pairwise_univ] end lemma sup_eq_top_iff_is_coprime {R : Type*} [comm_semiring R] (x y : R) : span ({x} : set R) ⊔ span {y} = ⊤ ↔ is_coprime x y := begin rw [eq_top_iff_one, submodule.mem_sup], split, { rintro ⟨u, hu, v, hv, h1⟩, rw mem_span_singleton' at hu hv, rw [← hu.some_spec, ← hv.some_spec] at h1, exact ⟨_, _, h1⟩ }, { exact λ ⟨u, v, h1⟩, ⟨_, mem_span_singleton'.mpr ⟨_, rfl⟩, _, mem_span_singleton'.mpr ⟨_, rfl⟩, h1⟩ }, end 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_rfl 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) lemma sup_mul_eq_of_coprime_left (h : I ⊔ J = ⊤) : I ⊔ (J * K) = I ⊔ K := le_antisymm (sup_le_sup_left mul_le_left _) $ λ i hi, begin rw eq_top_iff_one at h, rw submodule.mem_sup at h hi ⊢, obtain ⟨i1, hi1, j, hj, h⟩ := h, obtain ⟨i', hi', k, hk, hi⟩ := hi, refine ⟨_, add_mem hi' (mul_mem_right k _ hi1), _, mul_mem_mul hj hk, _⟩, rw [add_assoc, ← add_mul, h, one_mul, hi] end lemma sup_mul_eq_of_coprime_right (h : I ⊔ K = ⊤) : I ⊔ (J * K) = I ⊔ J := by { rw mul_comm, exact sup_mul_eq_of_coprime_left h } lemma mul_sup_eq_of_coprime_left (h : I ⊔ J = ⊤) : (I * K) ⊔ J = K ⊔ J := by { rw sup_comm at h, rw [sup_comm, sup_mul_eq_of_coprime_left h, sup_comm] } lemma mul_sup_eq_of_coprime_right (h : K ⊔ J = ⊤) : (I * K) ⊔ J = I ⊔ J := by { rw sup_comm at h, rw [sup_comm, sup_mul_eq_of_coprime_right h, sup_comm] } lemma sup_prod_eq_top {s : finset ι} {J : ι → ideal R} (h : ∀ i, i ∈ s → I ⊔ J i = ⊤) : I ⊔ ∏ i in s, J i = ⊤ := finset.prod_induction _ (λ J, I ⊔ J = ⊤) (λ J K hJ hK, (sup_mul_eq_of_coprime_left hJ).trans hK) (by rw [one_eq_top, sup_top_eq]) h lemma sup_infi_eq_top {s : finset ι} {J : ι → ideal R} (h : ∀ i, i ∈ s → I ⊔ J i = ⊤) : I ⊔ (⨅ i ∈ s, J i) = ⊤ := eq_top_iff.mpr $ le_of_eq_of_le (sup_prod_eq_top h).symm $ sup_le_sup_left (le_of_le_of_eq prod_le_inf $ finset.inf_eq_infi _ _) _ lemma prod_sup_eq_top {s : finset ι} {J : ι → ideal R} (h : ∀ i, i ∈ s → J i ⊔ I = ⊤) : (∏ i in s, J i) ⊔ I = ⊤ := sup_comm.trans (sup_prod_eq_top $ λ i hi, sup_comm.trans $ h i hi) lemma infi_sup_eq_top {s : finset ι} {J : ι → ideal R} (h : ∀ i, i ∈ s → J i ⊔ I = ⊤) : (⨅ i ∈ s, J i) ⊔ I = ⊤ := sup_comm.trans (sup_infi_eq_top $ λ i hi, sup_comm.trans $ h i hi) lemma sup_pow_eq_top {n : ℕ} (h : I ⊔ J = ⊤) : I ⊔ (J ^ n) = ⊤ := by { rw [← finset.card_range n, ← finset.prod_const], exact sup_prod_eq_top (λ _ _, h) } lemma pow_sup_eq_top {n : ℕ} (h : I ⊔ J = ⊤) : (I ^ n) ⊔ J = ⊤ := by { rw [← finset.card_range n, ← finset.prod_const], exact prod_sup_eq_top (λ _ _, h) } lemma pow_sup_pow_eq_top {m n : ℕ} (h : I ⊔ J = ⊤) : (I ^ m) ⊔ (J ^ n) = ⊤ := sup_pow_eq_top (pow_sup_eq_top h) variables (I) @[simp] theorem mul_bot : I * ⊥ = ⊥ := submodule.smul_bot I @[simp] theorem bot_mul : ⊥ * I = ⊥ := submodule.bot_smul I @[simp] theorem mul_top : I * ⊤ = I := ideal.mul_comm ⊤ I ▸ submodule.top_smul I @[simp] 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 pow_le_self {n : ℕ} (hn : n ≠ 0) : I^n ≤ I := calc I^n ≤ I ^ 1 : pow_le_pow (nat.pos_of_ne_zero hn) ... = I : pow_one _ lemma pow_mono {I J : ideal R} (e : I ≤ J) (n : ℕ) : I ^ n ≤ J ^ n := begin induction n, { rw [pow_zero, pow_zero], exact rfl.le }, { rw [pow_succ, pow_succ], exact ideal.mul_mono e n_ih } end lemma mul_eq_bot {R : Type*} [comm_semiring R] [no_zero_divisors 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*} [comm_semiring R] [no_zero_divisors 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*} [comm_ring R] [is_domain R] {s : multiset (ideal R)} : s.prod = ⊥ ↔ ∃ I ∈ s, I = ⊥ := prod_zero_iff_exists_zero lemma span_pair_mul_span_pair (w x y z : R) : (span {w, x} : ideal R) * span {y, z} = span {w * y, w * z, x * y, x * z} := by simp_rw [span_insert, sup_mul, mul_sup, span_singleton_mul_span_singleton, sup_assoc] /-- 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 ▸ (add_tsub_assoc_of_le hcm n).symm ▸ (pow_add y n (m-c)).symm ▸ I.mul_mem_right _ hyni) (λ hmc, I.mul_mem_right _ $ I.mul_mem_right _ $ add_tsub_cancel_of_le 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⟩ } /-- An ideal is radical if it contains its radical. -/ def is_radical (I : ideal R) : Prop := I.radical ≤ I theorem le_radical : I ≤ radical I := λ r hri, ⟨1, (pow_one r).symm ▸ hri⟩ /-- An ideal is radical iff it is equal to its radical. -/ theorem radical_eq_iff : I.radical = I ↔ I.is_radical := by rw [le_antisymm_iff, and_iff_left le_radical, is_radical] alias radical_eq_iff ↔ _ is_radical.radical 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_is_radical : (radical I).is_radical := λ r ⟨n, k, hrnki⟩, ⟨n * k, (pow_mul r n k).symm ▸ hrnki⟩ @[simp] theorem radical_idem : radical (radical I) = radical I := (radical_is_radical I).radical variables {I} theorem is_radical.radical_le_iff (hJ : J.is_radical) : radical I ≤ J ↔ I ≤ J := ⟨le_trans le_radical, λ h, hJ.radical ▸ radical_mono h⟩ theorem radical_le_radical_iff : radical I ≤ radical J ↔ I ≤ radical J := (radical_is_radical J).radical_le_iff 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.is_radical (H : is_prime I) : I.is_radical := λ r ⟨n, hrni⟩, H.mem_of_pow_mem n hrni theorem is_prime.radical (H : is_prime I) : radical I = I := H.is_radical.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) $ radical_le_radical_iff.2 $ sup_le (radical_mono le_sup_left) (radical_mono le_sup_right) 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 := hJ.is_radical.radical_le_iff 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_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 lemma is_radical_bot_of_no_zero_divisors {R} [comm_semiring R] [no_zero_divisors R] : (⊥ : ideal R).is_radical := λ x hx, hx.rec_on (λ n hn, pow_eq_zero hn) @[simp] lemma radical_bot_of_no_zero_divisors {R : Type u} [comm_semiring R] [no_zero_divisors R] : radical (⊥ : ideal R) = ⊥ := eq_bot_iff.2 is_radical_bot_of_no_zero_divisors instance : idem_comm_semiring (ideal R) := submodule.idem_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.cons_zero, 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 {R : Type u} [ring R] {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' {R : Type u} [comm_ring R] {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_Union₂ 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 {R : Type u} [comm_ring R] {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, by_cases has : a ∈ s, { unfreezingI { 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, { unfreezingI { 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)) _ _; unfreezingI { 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) _ _; unfreezingI { 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, { unfreezingI { 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) _ _; unfreezingI { 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, { substI 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, unfreezingI { 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) _ _; unfreezingI { 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 ((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} section semiring variables {F : Type*} [semiring R] [semiring S] variables [rc : ring_hom_class F R S] variables (f : F) variables {I J : ideal R} {K L : ideal S} include rc /-- `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, add_mem' := λ x y hx hy, by simp only [set.mem_preimage, set_like.mem_coe, map_add, add_mem hx hy] at *, zero_mem' := by simp only [set.mem_preimage, map_zero, set_like.mem_coe, submodule.zero_mem], smul_mem' := λ c x hx, by { simp only [smul_eq_mul, set.mem_preimage, map_mul, set_like.mem_coe] at *, exact mul_mem_left I _ 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 (f : F) {I : ideal R} {x : R} (h : x ∈ I) : f x ∈ map f I := subset_span ⟨x, h, rfl⟩ lemma apply_coe_mem_map (f : F) (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, map_one]; exact (ne_top_iff_one _).1 hK variables {G : Type*} [rcg : ring_hom_class G S R] include rcg lemma map_le_comap_of_inv_on (g : G) (I : ideal R) (hf : set.left_inv_on g f I) : I.map f ≤ I.comap g := begin refine ideal.span_le.2 _, rintros x ⟨x, hx, rfl⟩, rw [set_like.mem_coe, mem_comap, hf hx], exact hx, end lemma comap_le_map_of_inv_on (g : G) (I : ideal S) (hf : set.left_inv_on g f (f ⁻¹' I)) : I.comap f ≤ I.map g := λ x (hx : f x ∈ I), hf hx ▸ ideal.mem_map_of_mem g hx /-- The `ideal` version of `set.image_subset_preimage_of_inverse`. -/ lemma map_le_comap_of_inverse (g : G) (I : ideal R) (h : function.left_inverse g f) : I.map f ≤ I.comap g := map_le_comap_of_inv_on _ _ _ $ h.left_inv_on _ /-- The `ideal` version of `set.preimage_subset_image_of_inverse`. -/ lemma comap_le_map_of_inverse (g : G) (I : ideal S) (h : function.left_inverse g f) : I.comap f ≤ I.map g := comap_le_map_of_inv_on _ _ _ $ h.left_inv_on _ omit rcg 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, map_mul]; apply hK.2⟩ variables (I J K L) theorem map_top : map f ⊤ = ⊤ := (eq_top_iff_one _).2 $ subset_span ⟨1, trivial, map_one f⟩ variable (f) lemma gc_map_comap : galois_connection (ideal.map f) (ideal.comap f) := λ I J, ideal.map_le_iff_le_comap omit rc @[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*} [semiring 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*} [semiring 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 _ _) include rc lemma map_span (f : F) (s : set R) : map f (span s) = span (f '' s) := symm $ submodule.span_eq_of_le _ (λ y ⟨x, hy, x_eq⟩, x_eq ▸ mem_map_of_mem f (subset_span hy)) (map_le_iff_le_comap.2 $ span_le.2 $ set.image_subset_iff.1 subset_span) 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 (map_one f ▸ 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 := (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 := (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 : galois_connection (map f) (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 : galois_connection (map f) (comap f)).l_supr lemma comap_infi (K : ι → ideal S) : (infi K).comap f = ⨅ i, (K i).comap f := (gc_map_comap f : galois_connection (map f) (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 : galois_connection (map f) (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 : galois_connection (map f) (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, 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 : galois_connection (map f) (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 : galois_connection (map f) (comap f)).monotone_u.le_map_sup _ _ omit rc @[simp] lemma smul_top_eq_map {R S : Type*} [comm_semiring R] [comm_semiring S] [algebra R S] (I : ideal R) : I • (⊤ : submodule R S) = (I.map (algebra_map R S)).restrict_scalars R := begin refine le_antisymm (submodule.smul_le.mpr (λ r hr y _, _) ) (λ x hx, submodule.span_induction hx _ _ _ _), { rw algebra.smul_def, exact mul_mem_right _ _ (mem_map_of_mem _ hr) }, { rintros _ ⟨x, hx, rfl⟩, rw [← mul_one (algebra_map R S x), ← algebra.smul_def], exact submodule.smul_mem_smul hx submodule.mem_top }, { exact submodule.zero_mem _ }, { intros x y, exact submodule.add_mem _ }, intros a x hx, refine submodule.smul_induction_on hx _ _, { intros r hr s hs, rw smul_comm, exact submodule.smul_mem_smul hr submodule.mem_top }, { intros x y hx hy, rw smul_add, exact submodule.add_mem _ hx hy }, end @[simp] lemma coe_restrict_scalars {R S : Type*} [comm_semiring R] [semiring S] [algebra R S] (I : ideal S) : ((I.restrict_scalars R) : set S) = ↑I := rfl /-- The smallest `S`-submodule that contains all `x ∈ I * y ∈ J` is also the smallest `R`-submodule that does so. -/ @[simp] lemma restrict_scalars_mul {R S : Type*} [comm_semiring R] [comm_semiring S] [algebra R S] (I J : ideal S) : (I * J).restrict_scalars R = I.restrict_scalars R * J.restrict_scalars R := le_antisymm (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, submodule.mul_mem_mul hx hy) (λ x y, submodule.add_mem _)) (submodule.mul_le.mpr (λ x hx y hy, ideal.mul_mem_mul hx hy)) 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_rfl) (λ 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, map_zero f⟩ (λ y1 y2 ⟨x1, hx1i, hxy1⟩ ⟨x2, hx2i, hxy2⟩, ⟨x1 + x2, I.add_mem hx1i hx2i, hxy1 ▸ hxy2 ▸ map_add f _ _⟩) (λ c y ⟨x, hxi, hxy⟩, let ⟨d, hdc⟩ := hf c in ⟨d * x, I.mul_mem_left _ hxi, hdc ▸ hxy ▸ map_mul f _ _⟩) 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)⟩ 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 omit hf lemma map_eq_submodule_map (f : R →+* S) [h : ring_hom_surjective f] (I : ideal R) : I.map f = submodule.map f.to_semilinear_map I := submodule.ext (λ x, mem_map_iff_of_surjective f h.1) end surjective section injective variables (hf : function.injective f) include hf lemma comap_bot_le_of_injective : comap f ⊥ ≤ I := begin refine le_trans (λ x hx, _) bot_le, rw [mem_comap, submodule.mem_bot, ← map_zero f] at hx, exact eq.symm (hf hx) ▸ (submodule.zero_mem ⊥) end lemma comap_bot_of_injective : ideal.comap f ⊥ = ⊥ := le_bot_iff.mp (ideal.comap_bot_le_of_injective f hf) end injective end semiring section ring variables {F : Type*} [ring R] [ring S] variables [ring_hom_class F R S] (f : F) {I : ideal R} section surjective variables (hf : function.surjective f) include hf 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 [map_sub, hfsr, sub_self], add_sub_cancel'_right s r⟩) (sup_le (map_le_iff_le_comap.1 le_rfl) (comap_mono bot_le)) /-- 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_rfl 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 {I : ideal R} (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 {K : ideal S} [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 theorem comap_le_comap_iff_of_surjective (I J : ideal S) : comap f I ≤ comap f J ↔ I ≤ J := ⟨λ h, (map_comap_of_surjective f hf I).symm.le.trans (map_le_of_le_comap h), λ h, le_comap_of_map_le ((map_comap_of_surjective f hf I).le.trans h)⟩ 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 bijective variables (hf : function.bijective f) include hf /-- 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 {I : ideal R} {K : ideal S} : 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 {I : ideal R} (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 ring section comm_ring variables {F : Type*} [comm_ring R] [comm_ring S] variables [rc : ring_hom_class F R S] variables (f : F) variables {I J : ideal R} {K L : ideal S} variables (I J K L) include rc 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 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.Union₂_subset $ λ i ⟨r, hri, hfri⟩, set.Union₂_subset $ λ j ⟨s, hsj, hfsj⟩, set.singleton_subset_iff.2 $ hfri ▸ hfsj ▸ by rw [← map_mul]; exact mem_map_of_mem f (mul_mem_mul hri hsj)) /-- The pushforward `ideal.map` as a monoid-with-zero homomorphism. -/ @[simps] def map_hom : ideal R →*₀ ideal S := { to_fun := map f, map_mul' := λ I J, ideal.map_mul f I J, map_one' := by convert ideal.map_top f; exact one_eq_top, map_zero' := ideal.map_bot } protected theorem map_pow (n : ℕ) : map f (I^n) = (map f I)^n := map_pow (map_hom f) I n theorem comap_radical : comap f (radical K) = radical (comap f K) := by { ext, simpa only [radical, mem_comap, map_pow] } variable {K} theorem is_radical.comap (hK : K.is_radical) : (comap f K).is_radical := by { rw [←hK.radical, comap_radical], apply radical_is_radical } variables {I J L} theorem map_radical_le : map f (radical I) ≤ radical (map f I) := map_le_iff_le_comap.2 $ λ r ⟨n, hrni⟩, ⟨n, map_pow f 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_rfl) (map_le_iff_le_comap.2 $ le_rfl) lemma le_comap_pow (n : ℕ) : (K.comap f) ^ n ≤ (K ^ n).comap f := begin induction n, { rw [pow_zero, pow_zero, ideal.one_eq_top, ideal.one_eq_top], exact rfl.le }, { rw [pow_succ, pow_succ], exact (ideal.mul_mono_right n_ih).trans (ideal.le_comap_mul f) } end omit rc end comm_ring end map_and_comap section is_primary variables {R : Type u} [comm_semiring 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_prime.is_primary {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 section total variables (ι : Type*) variables (M : Type*) [add_comm_group M] {R : Type*} [comm_ring R] [module R M] (I : ideal R) variables (v : ι → M) (hv : submodule.span R (set.range v) = ⊤) open_locale big_operators /-- A variant of `finsupp.total` that takes in vectors valued in `I`. -/ noncomputable def finsupp_total : (ι →₀ I) →ₗ[R] M := (finsupp.total ι M R v).comp (finsupp.map_range.linear_map I.subtype) variables {ι M v} lemma finsupp_total_apply (f : ι →₀ I) : finsupp_total ι M I v f = f.sum (λ i x, (x : R) • v i) := begin dsimp [finsupp_total], rw [finsupp.total_apply, finsupp.sum_map_range_index], exact λ _, zero_smul _ _ end lemma finsupp_total_apply_eq_of_fintype [fintype ι] (f : ι →₀ I) : finsupp_total ι M I v f = ∑ i, (f i : R) • v i := by { rw [finsupp_total_apply, finsupp.sum_fintype], exact λ _, zero_smul _ _ } lemma range_finsupp_total : (finsupp_total ι M I v).range = I • (submodule.span R (set.range v)) := begin ext, rw submodule.mem_ideal_smul_span_iff_exists_sum, refine ⟨λ ⟨f, h⟩, ⟨finsupp.map_range.linear_map I.subtype f, λ i, (f i).2, h⟩, _⟩, rintro ⟨a, ha, rfl⟩, classical, refine ⟨a.map_range (λ r, if h : r ∈ I then ⟨r, h⟩ else 0) (by split_ifs; refl), _⟩, rw [finsupp_total_apply, finsupp.sum_map_range_index], { apply finsupp.sum_congr, intros i _, rw dif_pos (ha i), refl }, { exact λ _, zero_smul _ _ }, end end total section basis variables {ι R S : Type*} [comm_semiring R] [comm_ring S] [is_domain S] [algebra R S] /-- A basis on `S` gives a basis on `ideal.span {x}`, by multiplying everything by `x`. -/ noncomputable def basis_span_singleton (b : basis ι R S) {x : S} (hx : x ≠ 0) : basis ι R (span ({x} : set S)) := b.map $ ((linear_equiv.of_injective (algebra.lmul R S x) (linear_map.mul_injective hx)) ≪≫ₗ (linear_equiv.of_eq _ _ (by { ext, simp [mem_span_singleton', mul_comm] })) ≪≫ₗ ((submodule.restrict_scalars_equiv R S S (ideal.span ({x} : set S))).restrict_scalars R)) @[simp] lemma basis_span_singleton_apply (b : basis ι R S) {x : S} (hx : x ≠ 0) (i : ι) : (basis_span_singleton b hx i : S) = x * b i := begin simp only [basis_span_singleton, basis.map_apply, linear_equiv.trans_apply, submodule.restrict_scalars_equiv_apply, linear_equiv.of_injective_apply, linear_equiv.coe_of_eq_apply, linear_equiv.restrict_scalars_apply, algebra.coe_lmul_eq_mul, linear_map.mul_apply'] end @[simp] lemma constr_basis_span_singleton {N : Type*} [semiring N] [module N S] [smul_comm_class R N S] (b : basis ι R S) {x : S} (hx : x ≠ 0) : b.constr N (coe ∘ basis_span_singleton b hx) = algebra.lmul R S x := b.ext (λ i, by erw [basis.constr_basis, function.comp_app, basis_span_singleton_apply, linear_map.mul_apply']) end basis end ideal lemma associates.mk_ne_zero' {R : Type*} [comm_semiring R] {r : R} : (associates.mk (ideal.span {r} : ideal R)) ≠ 0 ↔ (r ≠ 0):= by rw [associates.mk_ne_zero, ideal.zero_eq_bot, ne.def, ideal.span_singleton_eq_bot] /-- If `I : ideal S` has a basis over `R`, `x ∈ I` iff it is a linear combination of basis vectors. -/ lemma basis.mem_ideal_iff {ι R S : Type*} [comm_ring R] [comm_ring S] [algebra R S] {I : ideal S} (b : basis ι R I) {x : S} : x ∈ I ↔ ∃ (c : ι →₀ R), x = finsupp.sum c (λ i x, x • b i) := (b.map ((I.restrict_scalars_equiv R _ _).restrict_scalars R).symm).mem_submodule_iff /-- If `I : ideal S` has a finite basis over `R`, `x ∈ I` iff it is a linear combination of basis vectors. -/ lemma basis.mem_ideal_iff' {ι R S : Type*} [fintype ι] [comm_ring R] [comm_ring S] [algebra R S] {I : ideal S} (b : basis ι R I) {x : S} : x ∈ I ↔ ∃ (c : ι → R), x = ∑ i, c i • b i := (b.map ((I.restrict_scalars_equiv R _ _).restrict_scalars R).symm).mem_submodule_iff' namespace ring_hom variables {R : Type u} {S : Type v} {T : Type w} section semiring variables {F : Type*} {G : Type*} [semiring R] [semiring S] [semiring T] variables [rcf : ring_hom_class F R S] [rcg : ring_hom_class G T S] (f : F) (g : G) include rcf /-- 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 : F) : ker f = ideal.comap f ⊥ := rfl omit rcf lemma comap_ker (f : S →+* R) (g : T →+* S) : f.ker.comap g = (f.comp g).ker := by rw [ring_hom.ker_eq_comap_bot, ideal.comap_comap, ring_hom.ker_eq_comap_bot] include rcf /-- If the target is not the zero ring, then one is not in the kernel.-/ lemma not_one_mem_ker [nontrivial S] (f : F) : (1:R) ∉ ker f := by { rw [mem_ker, map_one], exact one_ne_zero } lemma ker_ne_top [nontrivial S] (f : F) : ker f ≠ ⊤ := (ideal.ne_top_iff_one _).mpr $ not_one_mem_ker f omit rcf end semiring section ring variables {F : Type*} [ring R] [semiring S] [rc : ring_hom_class F R S] (f : F) include rc lemma injective_iff_ker_eq_bot : function.injective f ↔ ker f = ⊥ := by { rw [set_like.ext'_iff, ker_eq, set.ext_iff], exact injective_iff_map_eq_zero' f } lemma ker_eq_bot_iff_eq_zero : ker f = ⊥ ↔ ∀ x, f x = 0 → x = 0 := by { rw [← injective_iff_map_eq_zero f, injective_iff_ker_eq_bot] } omit rc @[simp] lemma ker_coe_equiv (f : R ≃+* S) : ker (f : R →+* S) = ⊥ := by simpa only [←injective_iff_ker_eq_bot] using equiv_like.injective f @[simp] lemma ker_equiv {F' : Type*} [ring_equiv_class F' R S] (f : F') : ker f = ⊥ := by simpa only [←injective_iff_ker_eq_bot] using equiv_like.injective f end ring section ring_ring variables {F : Type*} [ring R] [ring S] [rc : ring_hom_class F R S] (f : F) include rc theorem sub_mem_ker_iff {x y} : x - y ∈ ker f ↔ f x = f y := by rw [mem_ker, map_sub, sub_eq_zero] end ring_ring /-- The kernel of a homomorphism to a domain is a prime ideal. -/ lemma ker_is_prime {F : Type*} [ring R] [ring S] [is_domain S] [ring_hom_class F R S] (f : F) : (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, 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 F : Type*} [ring R] [field K] [ring_hom_class F R K] (f : F) (hf : function.surjective f) : (ker f).is_maximal := begin refine ideal.is_maximal_iff.mpr ⟨λ h1, one_ne_zero' K $ map_one f ▸ (mem_ker f).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 mem_ker, simp only [hy, map_sub, map_one, map_mul, inv_mul_cancel (mt (mem_ker f).mpr hxf), sub_self], end end ring_hom namespace ideal variables {R : Type*} {S : Type*} {F : Type*} section semiring variables [semiring R] [semiring S] [rc : ring_hom_class F R S] include rc lemma map_eq_bot_iff_le_ker {I : ideal R} (f : F) : I.map f = ⊥ ↔ I ≤ (ring_hom.ker f) := by rw [ring_hom.ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_le_comap {K : ideal S} (f : F) : ring_hom.ker f ≤ comap f K := λ x hx, mem_comap.2 (((ring_hom.mem_ker f).1 hx).symm ▸ K.zero_mem) end semiring section ring variables [ring R] [ring S] [rc : ring_hom_class F R S] include rc lemma map_Inf {A : set (ideal R)} {f : F} (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, map_sub, hx, sub_self] }, simpa only [sub_add_cancel] using J.add_mem this hx' } end theorem map_is_prime_of_surjective {f : F} (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, ← _root_.map_mul f, mem_map_iff_of_surjective _ hf] at hxy, rcases hxy with ⟨c, hc, hc'⟩, rw [← sub_eq_zero, ← map_sub] at hc', have : a * b ∈ I, { convert I.sub_mem hc (hk (hc' : c - a * b ∈ ring_hom.ker f)), 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 lemma map_eq_bot_iff_of_injective {I : ideal R} {f : F} (hf : function.injective f) : I.map f = ⊥ ↔ I = ⊥ := by rw [map_eq_bot_iff_le_ker, (ring_hom.injective_iff_ker_eq_bot f).mp hf, le_bot_iff] omit rc theorem map_is_prime_of_equiv {F' : Type*} [ring_equiv_class F' R S] (f : F') {I : ideal R} [is_prime I] : is_prime (map f I) := map_is_prime_of_surjective (equiv_like.surjective f) $ by simp only [ring_hom.ker_equiv, bot_le] end ring section comm_ring variables [comm_ring R] [comm_ring S] 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 end comm_ring end ideal namespace submodule variables {R : Type u} {M : Type v} variables [comm_semiring R] [add_comm_monoid 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
b5a7943e998e15220686df7594cea07344741253
bb31430994044506fa42fd667e2d556327e18dfe
/src/order/conditionally_complete_lattice/basic.lean
8eea89f3d5511024f4ff1039353dc2534bd7ae71
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
56,291
lean
/- Copyright (c) 2018 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 order.bounds.basic import order.well_founded import data.set.intervals.basic import data.set.lattice /-! # Theory of conditionally complete lattices. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A conditionally complete lattice is a lattice in which every non-empty bounded subset `s` has a least upper bound and a greatest lower bound, denoted below by `Sup s` and `Inf s`. Typical examples are `ℝ`, `ℕ`, and `ℤ` with their usual orders. The theory is very comparable to the theory of complete lattices, except that suitable boundedness and nonemptiness assumptions have to be added to most statements. We introduce two predicates `bdd_above` and `bdd_below` to express this boundedness, prove their basic properties, and then go on to prove most useful properties of `Sup` and `Inf` in conditionally complete lattices. To differentiate the statements between complete lattices and conditionally complete lattices, we prefix `Inf` and `Sup` in the statements by `c`, giving `cInf` and `cSup`. For instance, `Inf_le` is a statement in complete lattices ensuring `Inf s ≤ x`, while `cInf_le` is the same statement in conditionally complete lattices with an additional assumption that `s` is bounded below. -/ set_option old_structure_cmd true open function order_dual set variables {α β γ : Type*} {ι : Sort*} section /-! Extension of Sup and Inf from a preorder `α` to `with_top α` and `with_bot α` -/ open_locale classical noncomputable instance {α : Type*} [preorder α] [has_Sup α] : has_Sup (with_top α) := ⟨λ S, if ⊤ ∈ S then ⊤ else if bdd_above (coe ⁻¹' S : set α) then ↑(Sup (coe ⁻¹' S : set α)) else ⊤⟩ noncomputable instance {α : Type*} [has_Inf α] : has_Inf (with_top α) := ⟨λ S, if S ⊆ {⊤} then ⊤ else ↑(Inf (coe ⁻¹' S : set α))⟩ noncomputable instance {α : Type*} [has_Sup α] : has_Sup (with_bot α) := ⟨(@with_top.has_Inf αᵒᵈ _).Inf⟩ noncomputable instance {α : Type*} [preorder α] [has_Inf α] : has_Inf (with_bot α) := ⟨(@with_top.has_Sup αᵒᵈ _ _).Sup⟩ @[simp] theorem with_top.cInf_empty {α : Type*} [has_Inf α] : Inf (∅ : set (with_top α)) = ⊤ := if_pos $ set.empty_subset _ @[simp] theorem with_top.cinfi_empty {α : Type*} [is_empty ι] [has_Inf α] (f : ι → with_top α) : (⨅ i, f i) = ⊤ := by rw [infi, range_eq_empty, with_top.cInf_empty] lemma with_top.coe_Inf' [has_Inf α] {s : set α} (hs : s.nonempty) : ↑(Inf s) = (Inf (coe '' s) : with_top α) := begin obtain ⟨x, hx⟩ := hs, change _ = ite _ _ _, split_ifs, { cases h (mem_image_of_mem _ hx) }, { rw preimage_image_eq, exact option.some_injective _ }, end @[norm_cast] lemma with_top.coe_infi [nonempty ι] [has_Inf α] (f : ι → α) : ↑(⨅ i, f i) = (⨅ i, f i : with_top α) := by rw [infi, infi, with_top.coe_Inf' (range_nonempty f), range_comp] theorem with_top.coe_Sup' [preorder α] [has_Sup α] {s : set α} (hs : bdd_above s) : ↑(Sup s) = (Sup (coe '' s) : with_top α) := begin change _ = ite _ _ _, rw [if_neg, preimage_image_eq, if_pos hs], { exact option.some_injective _ }, { rintro ⟨x, h, ⟨⟩⟩ }, end @[norm_cast] lemma with_top.coe_supr [preorder α] [has_Sup α] (f : ι → α) (h : bdd_above (set.range f)) : ↑(⨆ i, f i) = (⨆ i, f i : with_top α) := by rw [supr, supr, with_top.coe_Sup' h, range_comp] @[simp] theorem with_bot.cSup_empty {α : Type*} [has_Sup α] : Sup (∅ : set (with_bot α)) = ⊥ := if_pos $ set.empty_subset _ @[simp] theorem with_bot.csupr_empty {α : Type*} [is_empty ι] [has_Sup α] (f : ι → with_bot α) : (⨆ i, f i) = ⊥ := @with_top.cinfi_empty _ αᵒᵈ _ _ _ @[norm_cast] lemma with_bot.coe_Sup' [has_Sup α] {s : set α} (hs : s.nonempty) : ↑(Sup s) = (Sup (coe '' s) : with_bot α) := @with_top.coe_Inf' αᵒᵈ _ _ hs @[norm_cast] lemma with_bot.coe_supr [nonempty ι] [has_Sup α] (f : ι → α) : ↑(⨆ i, f i) = (⨆ i, f i : with_bot α) := @with_top.coe_infi αᵒᵈ _ _ _ _ @[norm_cast] theorem with_bot.coe_Inf' [preorder α] [has_Inf α] {s : set α} (hs : bdd_below s) : ↑(Inf s) = (Inf (coe '' s) : with_bot α) := @with_top.coe_Sup' αᵒᵈ _ _ _ hs @[norm_cast] lemma with_bot.coe_infi [preorder α] [has_Inf α] (f : ι → α) (h : bdd_below (set.range f)) : ↑(⨅ i, f i) = (⨅ i, f i : with_bot α) := @with_top.coe_supr αᵒᵈ _ _ _ _ h end -- section /-- A conditionally complete lattice is a lattice in which every nonempty subset which is bounded above has a supremum, and every nonempty subset which is bounded below has an infimum. Typical examples are real numbers or natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete lattices, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of nonemptiness or boundedness.-/ class conditionally_complete_lattice (α : Type*) extends lattice α, has_Sup α, has_Inf α := (le_cSup : ∀ s a, bdd_above s → a ∈ s → a ≤ Sup s) (cSup_le : ∀ s a, set.nonempty s → a ∈ upper_bounds s → Sup s ≤ a) (cInf_le : ∀ s a, bdd_below s → a ∈ s → Inf s ≤ a) (le_cInf : ∀ s a, set.nonempty s → a ∈ lower_bounds s → a ≤ Inf s) /-- A conditionally complete linear order is a linear order in which every nonempty subset which is bounded above has a supremum, and every nonempty subset which is bounded below has an infimum. Typical examples are real numbers or natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete linear orders, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of nonemptiness or boundedness.-/ class conditionally_complete_linear_order (α : Type*) extends conditionally_complete_lattice α, linear_order α renaming max → sup min → inf /-- A conditionally complete linear order with `bot` is a linear order with least element, in which every nonempty subset which is bounded above has a supremum, and every nonempty subset (necessarily bounded below) has an infimum. A typical example is the natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete linear orders, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of nonemptiness or boundedness.-/ @[ancestor conditionally_complete_linear_order has_bot] class conditionally_complete_linear_order_bot (α : Type*) extends conditionally_complete_linear_order α, has_bot α := (bot_le : ∀ x : α, ⊥ ≤ x) (cSup_empty : Sup ∅ = ⊥) @[priority 100] -- see Note [lower instance priority] instance conditionally_complete_linear_order_bot.to_order_bot [h : conditionally_complete_linear_order_bot α] : order_bot α := { ..h } /-- A complete lattice is a conditionally complete lattice, as there are no restrictions on the properties of Inf and Sup in a complete lattice.-/ @[priority 100] -- see Note [lower instance priority] instance complete_lattice.to_conditionally_complete_lattice [complete_lattice α] : conditionally_complete_lattice α := { le_cSup := by intros; apply le_Sup; assumption, cSup_le := by intros; apply Sup_le; assumption, cInf_le := by intros; apply Inf_le; assumption, le_cInf := by intros; apply le_Inf; assumption, ..‹complete_lattice α› } @[priority 100] -- see Note [lower instance priority] instance complete_linear_order.to_conditionally_complete_linear_order_bot {α : Type*} [complete_linear_order α] : conditionally_complete_linear_order_bot α := { cSup_empty := Sup_empty, ..complete_lattice.to_conditionally_complete_lattice, .. ‹complete_linear_order α› } section open_locale classical /-- A well founded linear order is conditionally complete, with a bottom element. -/ @[reducible] noncomputable def is_well_order.conditionally_complete_linear_order_bot (α : Type*) [i₁ : linear_order α] [i₂ : order_bot α] [h : is_well_order α (<)] : conditionally_complete_linear_order_bot α := { Inf := λ s, if hs : s.nonempty then h.wf.min s hs else ⊥, cInf_le := λ s a hs has, begin have s_ne : s.nonempty := ⟨a, has⟩, simpa [s_ne] using not_lt.1 (h.wf.not_lt_min s s_ne has), end, le_cInf := λ s a hs has, begin simp only [hs, dif_pos], exact has (h.wf.min_mem s hs), end, Sup := λ s, if hs : (upper_bounds s).nonempty then h.wf.min _ hs else ⊥, le_cSup := λ s a hs has, begin have h's : (upper_bounds s).nonempty := hs, simp only [h's, dif_pos], exact h.wf.min_mem _ h's has, end, cSup_le := λ s a hs has, begin have h's : (upper_bounds s).nonempty := ⟨a, has⟩, simp only [h's, dif_pos], simpa using h.wf.not_lt_min _ h's has, end, cSup_empty := by simpa using eq_bot_iff.2 (not_lt.1 $ h.wf.not_lt_min _ _ $ mem_univ ⊥), ..i₁, ..i₂, ..linear_order.to_lattice } end section order_dual instance (α : Type*) [conditionally_complete_lattice α] : conditionally_complete_lattice αᵒᵈ := { le_cSup := @conditionally_complete_lattice.cInf_le α _, cSup_le := @conditionally_complete_lattice.le_cInf α _, le_cInf := @conditionally_complete_lattice.cSup_le α _, cInf_le := @conditionally_complete_lattice.le_cSup α _, ..order_dual.has_Inf α, ..order_dual.has_Sup α, ..order_dual.lattice α } instance (α : Type*) [conditionally_complete_linear_order α] : conditionally_complete_linear_order αᵒᵈ := { ..order_dual.conditionally_complete_lattice α, ..order_dual.linear_order α } end order_dual /-- Create a `conditionally_complete_lattice` from a `partial_order` and `Sup` function that returns the least upper bound of a nonempty set which is bounded above. Usually this constructor provides poor definitional equalities. If other fields are known explicitly, they should be provided; for example, if `inf` is known explicitly, construct the `conditionally_complete_lattice` instance as ``` instance : conditionally_complete_lattice my_T := { inf := better_inf, le_inf := ..., inf_le_right := ..., inf_le_left := ... -- don't care to fix sup, Inf ..conditionally_complete_lattice_of_Sup my_T _ } ``` -/ def conditionally_complete_lattice_of_Sup (α : Type*) [H1 : partial_order α] [H2 : has_Sup α] (bdd_above_pair : ∀ a b : α, bdd_above ({a, b} : set α)) (bdd_below_pair : ∀ a b : α, bdd_below ({a, b} : set α)) (is_lub_Sup : ∀ s : set α, bdd_above s → s.nonempty → is_lub s (Sup s)) : conditionally_complete_lattice α := { sup := λ a b, Sup {a, b}, le_sup_left := λ a b, (is_lub_Sup {a, b} (bdd_above_pair a b) (insert_nonempty _ _)).1 (mem_insert _ _), le_sup_right := λ a b, (is_lub_Sup {a, b} (bdd_above_pair a b) (insert_nonempty _ _)).1 (mem_insert_of_mem _ (mem_singleton _)), sup_le := λ a b c hac hbc, (is_lub_Sup {a, b} (bdd_above_pair a b) (insert_nonempty _ _)).2 (forall_insert_of_forall (forall_eq.mpr hbc) hac), inf := λ a b, Sup (lower_bounds {a, b}), inf_le_left := λ a b, (is_lub_Sup (lower_bounds {a, b}) (nonempty.bdd_above_lower_bounds ⟨a, mem_insert _ _⟩) (bdd_below_pair a b)).2 (λ c hc, hc $ mem_insert _ _), inf_le_right := λ a b, (is_lub_Sup (lower_bounds {a, b}) (nonempty.bdd_above_lower_bounds ⟨a, mem_insert _ _⟩) (bdd_below_pair a b)).2 (λ c hc, hc $ mem_insert_of_mem _ (mem_singleton _)), le_inf := λ c a b hca hcb, (is_lub_Sup (lower_bounds {a, b}) (nonempty.bdd_above_lower_bounds ⟨a, mem_insert _ _⟩) ⟨c, forall_insert_of_forall (forall_eq.mpr hcb) hca⟩).1 (forall_insert_of_forall (forall_eq.mpr hcb) hca), Inf := λ s, Sup (lower_bounds s), cSup_le := λ s a hs ha, (is_lub_Sup s ⟨a, ha⟩ hs).2 ha, le_cSup := λ s a hs ha, (is_lub_Sup s hs ⟨a, ha⟩).1 ha, cInf_le := λ s a hs ha, (is_lub_Sup (lower_bounds s) (nonempty.bdd_above_lower_bounds ⟨a, ha⟩) hs).2 (λ b hb, hb ha), le_cInf := λ s a hs ha, (is_lub_Sup (lower_bounds s) hs.bdd_above_lower_bounds ⟨a, ha⟩).1 ha, .. H1, .. H2 } /-- Create a `conditionally_complete_lattice_of_Inf` from a `partial_order` and `Inf` function that returns the greatest lower bound of a nonempty set which is bounded below. Usually this constructor provides poor definitional equalities. If other fields are known explicitly, they should be provided; for example, if `inf` is known explicitly, construct the `conditionally_complete_lattice` instance as ``` instance : conditionally_complete_lattice my_T := { inf := better_inf, le_inf := ..., inf_le_right := ..., inf_le_left := ... -- don't care to fix sup, Sup ..conditionally_complete_lattice_of_Inf my_T _ } ``` -/ def conditionally_complete_lattice_of_Inf (α : Type*) [H1 : partial_order α] [H2 : has_Inf α] (bdd_above_pair : ∀ a b : α, bdd_above ({a, b} : set α)) (bdd_below_pair : ∀ a b : α, bdd_below ({a, b} : set α)) (is_glb_Inf : ∀ s : set α, bdd_below s → s.nonempty → is_glb s (Inf s)) : conditionally_complete_lattice α := { inf := λ a b, Inf {a, b}, inf_le_left := λ a b, (is_glb_Inf {a, b} (bdd_below_pair a b) (insert_nonempty _ _)).1 (mem_insert _ _), inf_le_right := λ a b, (is_glb_Inf {a, b} (bdd_below_pair a b) (insert_nonempty _ _)).1 (mem_insert_of_mem _ (mem_singleton _)), le_inf := λ c a b hca hcb, (is_glb_Inf {a, b} (bdd_below_pair a b) (insert_nonempty _ _)).2 (forall_insert_of_forall (forall_eq.mpr hcb) hca), sup := λ a b, Inf (upper_bounds {a, b}), le_sup_left := λ a b, (is_glb_Inf (upper_bounds {a, b}) (nonempty.bdd_below_upper_bounds ⟨a, mem_insert _ _⟩) (bdd_above_pair a b)).2 (λ c hc, hc $ mem_insert _ _), le_sup_right := λ a b, (is_glb_Inf (upper_bounds {a, b}) (nonempty.bdd_below_upper_bounds ⟨a, mem_insert _ _⟩) (bdd_above_pair a b)).2 (λ c hc, hc $ mem_insert_of_mem _ (mem_singleton _)), sup_le := λ a b c hac hbc, (is_glb_Inf (upper_bounds {a, b}) (nonempty.bdd_below_upper_bounds ⟨a, mem_insert _ _⟩) ⟨c, forall_insert_of_forall (forall_eq.mpr hbc) hac⟩).1 (forall_insert_of_forall (forall_eq.mpr hbc) hac), Sup := λ s, Inf (upper_bounds s), le_cInf := λ s a hs ha, (is_glb_Inf s ⟨a, ha⟩ hs).2 ha, cInf_le := λ s a hs ha, (is_glb_Inf s hs ⟨a, ha⟩).1 ha, le_cSup := λ s a hs ha, (is_glb_Inf (upper_bounds s) (nonempty.bdd_below_upper_bounds ⟨a, ha⟩) hs).2 (λ b hb, hb ha), cSup_le := λ s a hs ha, (is_glb_Inf (upper_bounds s) hs.bdd_below_upper_bounds ⟨a, ha⟩).1 ha, .. H1, .. H2 } /-- A version of `conditionally_complete_lattice_of_Sup` when we already know that `α` is a lattice. This should only be used when it is both hard and unnecessary to provide `Inf` explicitly. -/ def conditionally_complete_lattice_of_lattice_of_Sup (α : Type*) [H1 : lattice α] [H2 : has_Sup α] (is_lub_Sup : ∀ s : set α, bdd_above s → s.nonempty → is_lub s (Sup s)) : conditionally_complete_lattice α := { ..H1, ..conditionally_complete_lattice_of_Sup α (λ a b, ⟨a ⊔ b, forall_insert_of_forall (forall_eq.mpr le_sup_right) le_sup_left⟩) (λ a b, ⟨a ⊓ b, forall_insert_of_forall (forall_eq.mpr inf_le_right) inf_le_left⟩) is_lub_Sup } /-- A version of `conditionally_complete_lattice_of_Inf` when we already know that `α` is a lattice. This should only be used when it is both hard and unnecessary to provide `Sup` explicitly. -/ def conditionally_complete_lattice_of_lattice_of_Inf (α : Type*) [H1 : lattice α] [H2 : has_Inf α] (is_glb_Inf : ∀ s : set α, bdd_below s → s.nonempty → is_glb s (Inf s)) : conditionally_complete_lattice α := { ..H1, ..conditionally_complete_lattice_of_Inf α (λ a b, ⟨a ⊔ b, forall_insert_of_forall (forall_eq.mpr le_sup_right) le_sup_left⟩) (λ a b, ⟨a ⊓ b, forall_insert_of_forall (forall_eq.mpr inf_le_right) inf_le_left⟩) is_glb_Inf } section conditionally_complete_lattice variables [conditionally_complete_lattice α] {s t : set α} {a b : α} theorem le_cSup (h₁ : bdd_above s) (h₂ : a ∈ s) : a ≤ Sup s := conditionally_complete_lattice.le_cSup s a h₁ h₂ theorem cSup_le (h₁ : s.nonempty) (h₂ : ∀ b ∈ s, b ≤ a) : Sup s ≤ a := conditionally_complete_lattice.cSup_le s a h₁ h₂ theorem cInf_le (h₁ : bdd_below s) (h₂ : a ∈ s) : Inf s ≤ a := conditionally_complete_lattice.cInf_le s a h₁ h₂ theorem le_cInf (h₁ : s.nonempty) (h₂ : ∀ b ∈ s, a ≤ b) : a ≤ Inf s := conditionally_complete_lattice.le_cInf s a h₁ h₂ theorem le_cSup_of_le (hs : bdd_above s) (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_cSup hs hb) theorem cInf_le_of_le (hs : bdd_below s) (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (cInf_le hs hb) h theorem cSup_le_cSup (ht : bdd_above t) (hs : s.nonempty) (h : s ⊆ t) : Sup s ≤ Sup t := cSup_le hs (λ a ha, le_cSup ht (h ha)) theorem cInf_le_cInf (ht : bdd_below t) (hs : s.nonempty) (h : s ⊆ t) : Inf t ≤ Inf s := le_cInf hs (λ a ha, cInf_le ht (h ha)) theorem le_cSup_iff (h : bdd_above s) (hs : s.nonempty) : a ≤ Sup s ↔ ∀ b, b ∈ upper_bounds s → a ≤ b := ⟨λ h b hb, le_trans h (cSup_le hs hb), λ hb, hb _ (λ x, le_cSup h)⟩ theorem cInf_le_iff (h : bdd_below s) (hs : s.nonempty) : Inf s ≤ a ↔ ∀ b ∈ lower_bounds s, b ≤ a := ⟨λ h b hb, le_trans (le_cInf hs hb) h, λ hb, hb _ (λ x, cInf_le h)⟩ lemma is_lub_cSup (ne : s.nonempty) (H : bdd_above s) : is_lub s (Sup s) := ⟨λ x, le_cSup H, λ x, cSup_le ne⟩ lemma is_lub_csupr [nonempty ι] {f : ι → α} (H : bdd_above (range f)) : is_lub (range f) (⨆ i, f i) := is_lub_cSup (range_nonempty f) H lemma is_lub_csupr_set {f : β → α} {s : set β} (H : bdd_above (f '' s)) (Hne : s.nonempty) : is_lub (f '' s) (⨆ i : s, f i) := by { rw ← Sup_image', exact is_lub_cSup (Hne.image _) H } lemma is_glb_cInf (ne : s.nonempty) (H : bdd_below s) : is_glb s (Inf s) := ⟨λ x, cInf_le H, λ x, le_cInf ne⟩ lemma is_glb_cinfi [nonempty ι] {f : ι → α} (H : bdd_below (range f)) : is_glb (range f) (⨅ i, f i) := is_glb_cInf (range_nonempty f) H lemma is_glb_cinfi_set {f : β → α} {s : set β} (H : bdd_below (f '' s)) (Hne : s.nonempty) : is_glb (f '' s) (⨅ i : s, f i) := @is_lub_csupr_set αᵒᵈ _ _ _ _ H Hne lemma csupr_le_iff [nonempty ι] {f : ι → α} {a : α} (hf : bdd_above (range f)) : supr f ≤ a ↔ ∀ i, f i ≤ a := (is_lub_le_iff $ is_lub_csupr hf).trans forall_range_iff lemma le_cinfi_iff [nonempty ι] {f : ι → α} {a : α} (hf : bdd_below (range f)) : a ≤ infi f ↔ ∀ i, a ≤ f i := (le_is_glb_iff $ is_glb_cinfi hf).trans forall_range_iff lemma csupr_set_le_iff {ι : Type*} {s : set ι} {f : ι → α} {a : α} (hs : s.nonempty) (hf : bdd_above (f '' s)) : (⨆ i : s, f i) ≤ a ↔ ∀ i ∈ s, f i ≤ a := (is_lub_le_iff $ is_lub_csupr_set hf hs).trans ball_image_iff lemma le_cinfi_set_iff {ι : Type*} {s : set ι} {f : ι → α} {a : α} (hs : s.nonempty) (hf : bdd_below (f '' s)) : a ≤ (⨅ i : s, f i) ↔ ∀ i ∈ s, a ≤ f i := (le_is_glb_iff $ is_glb_cinfi_set hf hs).trans ball_image_iff lemma is_lub.cSup_eq (H : is_lub s a) (ne : s.nonempty) : Sup s = a := (is_lub_cSup ne ⟨a, H.1⟩).unique H lemma is_lub.csupr_eq [nonempty ι] {f : ι → α} (H : is_lub (range f) a) : (⨆ i, f i) = a := H.cSup_eq (range_nonempty f) lemma is_lub.csupr_set_eq {s : set β} {f : β → α} (H : is_lub (f '' s) a) (Hne : s.nonempty) : (⨆ i : s, f i) = a := is_lub.cSup_eq (image_eq_range f s ▸ H) (image_eq_range f s ▸ Hne.image f) /-- A greatest element of a set is the supremum of this set. -/ lemma is_greatest.cSup_eq (H : is_greatest s a) : Sup s = a := H.is_lub.cSup_eq H.nonempty lemma is_greatest.Sup_mem (H : is_greatest s a) : Sup s ∈ s := H.cSup_eq.symm ▸ H.1 lemma is_glb.cInf_eq (H : is_glb s a) (ne : s.nonempty) : Inf s = a := (is_glb_cInf ne ⟨a, H.1⟩).unique H lemma is_glb.cinfi_eq [nonempty ι] {f : ι → α} (H : is_glb (range f) a) : (⨅ i, f i) = a := H.cInf_eq (range_nonempty f) lemma is_glb.cinfi_set_eq {s : set β} {f : β → α} (H : is_glb (f '' s) a) (Hne : s.nonempty) : (⨅ i : s, f i) = a := is_glb.cInf_eq (image_eq_range f s ▸ H) (image_eq_range f s ▸ Hne.image f) /-- A least element of a set is the infimum of this set. -/ lemma is_least.cInf_eq (H : is_least s a) : Inf s = a := H.is_glb.cInf_eq H.nonempty lemma is_least.Inf_mem (H : is_least s a) : Inf s ∈ s := H.cInf_eq.symm ▸ H.1 lemma subset_Icc_cInf_cSup (hb : bdd_below s) (ha : bdd_above s) : s ⊆ Icc (Inf s) (Sup s) := λ x hx, ⟨cInf_le hb hx, le_cSup ha hx⟩ theorem cSup_le_iff (hb : bdd_above s) (hs : s.nonempty) : Sup s ≤ a ↔ ∀ b ∈ s, b ≤ a := is_lub_le_iff (is_lub_cSup hs hb) theorem le_cInf_iff (hb : bdd_below s) (hs : s.nonempty) : a ≤ Inf s ↔ ∀ b ∈ s, a ≤ b := le_is_glb_iff (is_glb_cInf hs hb) lemma cSup_lower_bounds_eq_cInf {s : set α} (h : bdd_below s) (hs : s.nonempty) : Sup (lower_bounds s) = Inf s := (is_lub_cSup h $ hs.mono $ λ x hx y hy, hy hx).unique (is_glb_cInf hs h).is_lub lemma cInf_upper_bounds_eq_cSup {s : set α} (h : bdd_above s) (hs : s.nonempty) : Inf (upper_bounds s) = Sup s := (is_glb_cInf h $ hs.mono $ λ x hx y hy, hy hx).unique (is_lub_cSup hs h).is_glb lemma not_mem_of_lt_cInf {x : α} {s : set α} (h : x < Inf s) (hs : bdd_below s) : x ∉ s := λ hx, lt_irrefl _ (h.trans_le (cInf_le hs hx)) lemma not_mem_of_cSup_lt {x : α} {s : set α} (h : Sup s < x) (hs : bdd_above s) : x ∉ s := @not_mem_of_lt_cInf αᵒᵈ _ x s h hs /--Introduction rule to prove that `b` is the supremum of `s`: it suffices to check that `b` is larger than all elements of `s`, and that this is not the case of any `w<b`. See `Sup_eq_of_forall_le_of_forall_lt_exists_gt` for a version in complete lattices. -/ theorem cSup_eq_of_forall_le_of_forall_lt_exists_gt (hs : s.nonempty) (H : ∀ a ∈ s, a ≤ b) (H' : ∀ w, w < b → ∃ a ∈ s, w < a) : Sup s = b := eq_of_le_of_not_lt (cSup_le hs H) $ λ hb, let ⟨a, ha, ha'⟩ := H' _ hb in lt_irrefl _ $ ha'.trans_le $ le_cSup ⟨b, H⟩ ha /--Introduction rule to prove that `b` is the infimum of `s`: it suffices to check that `b` is smaller than all elements of `s`, and that this is not the case of any `w>b`. See `Inf_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in complete lattices. -/ theorem cInf_eq_of_forall_ge_of_forall_gt_exists_lt : s.nonempty → (∀ a ∈ s, b ≤ a) → (∀ w, b < w → ∃ a ∈ s, a < w) → Inf s = b := @cSup_eq_of_forall_le_of_forall_lt_exists_gt αᵒᵈ _ _ _ /--b < Sup s when there is an element a in s with b < a, when s is bounded above. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness above for one direction, nonemptiness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma lt_cSup_of_lt (hs : bdd_above s) (ha : a ∈ s) (h : b < a) : b < Sup s := lt_of_lt_of_le h (le_cSup hs ha) /--Inf s < b when there is an element a in s with a < b, when s is bounded below. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness below for one direction, nonemptiness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma cInf_lt_of_lt : bdd_below s → a ∈ s → a < b → Inf s < b := @lt_cSup_of_lt αᵒᵈ _ _ _ _ /-- If all elements of a nonempty set `s` are less than or equal to all elements of a nonempty set `t`, then there exists an element between these sets. -/ lemma exists_between_of_forall_le (sne : s.nonempty) (tne : t.nonempty) (hst : ∀ (x ∈ s) (y ∈ t), x ≤ y) : (upper_bounds s ∩ lower_bounds t).nonempty := ⟨Inf t, λ x hx, le_cInf tne $ hst x hx, λ y hy, cInf_le (sne.mono hst) hy⟩ /--The supremum of a singleton is the element of the singleton-/ @[simp] theorem cSup_singleton (a : α) : Sup {a} = a := is_greatest_singleton.cSup_eq /--The infimum of a singleton is the element of the singleton-/ @[simp] theorem cInf_singleton (a : α) : Inf {a} = a := is_least_singleton.cInf_eq @[simp] theorem cSup_pair (a b : α) : Sup {a, b} = a ⊔ b := (@is_lub_pair _ _ a b).cSup_eq (insert_nonempty _ _) @[simp] theorem cInf_pair (a b : α) : Inf {a, b} = a ⊓ b := (@is_glb_pair _ _ a b).cInf_eq (insert_nonempty _ _) /--If a set is bounded below and above, and nonempty, its infimum is less than or equal to its supremum.-/ theorem cInf_le_cSup (hb : bdd_below s) (ha : bdd_above s) (ne : s.nonempty) : Inf s ≤ Sup s := is_glb_le_is_lub (is_glb_cInf ne hb) (is_lub_cSup ne ha) ne /--The sup of a union of two sets is the max of the suprema of each subset, under the assumptions that all sets are bounded above and nonempty.-/ theorem cSup_union (hs : bdd_above s) (sne : s.nonempty) (ht : bdd_above t) (tne : t.nonempty) : Sup (s ∪ t) = Sup s ⊔ Sup t := ((is_lub_cSup sne hs).union (is_lub_cSup tne ht)).cSup_eq sne.inl /--The inf of a union of two sets is the min of the infima of each subset, under the assumptions that all sets are bounded below and nonempty.-/ theorem cInf_union (hs : bdd_below s) (sne : s.nonempty) (ht : bdd_below t) (tne : t.nonempty) : Inf (s ∪ t) = Inf s ⊓ Inf t := @cSup_union αᵒᵈ _ _ _ hs sne ht tne /--The supremum of an intersection of two sets is bounded by the minimum of the suprema of each set, if all sets are bounded above and nonempty.-/ theorem cSup_inter_le (hs : bdd_above s) (ht : bdd_above t) (hst : (s ∩ t).nonempty) : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := cSup_le hst $ λ x hx, le_inf (le_cSup hs hx.1) (le_cSup ht hx.2) /--The infimum of an intersection of two sets is bounded below by the maximum of the infima of each set, if all sets are bounded below and nonempty.-/ theorem le_cInf_inter : bdd_below s → bdd_below t → (s ∩ t).nonempty → Inf s ⊔ Inf t ≤ Inf (s ∩ t) := @cSup_inter_le αᵒᵈ _ _ _ /-- The supremum of insert a s is the maximum of a and the supremum of s, if s is nonempty and bounded above.-/ theorem cSup_insert (hs : bdd_above s) (sne : s.nonempty) : Sup (insert a s) = a ⊔ Sup s := ((is_lub_cSup sne hs).insert a).cSup_eq (insert_nonempty a s) /-- The infimum of insert a s is the minimum of a and the infimum of s, if s is nonempty and bounded below.-/ theorem cInf_insert (hs : bdd_below s) (sne : s.nonempty) : Inf (insert a s) = a ⊓ Inf s := @cSup_insert αᵒᵈ _ _ _ hs sne @[simp] lemma cInf_Icc (h : a ≤ b) : Inf (Icc a b) = a := (is_glb_Icc h).cInf_eq (nonempty_Icc.2 h) @[simp] lemma cInf_Ici : Inf (Ici a) = a := is_least_Ici.cInf_eq @[simp] lemma cInf_Ico (h : a < b) : Inf (Ico a b) = a := (is_glb_Ico h).cInf_eq (nonempty_Ico.2 h) @[simp] lemma cInf_Ioc [densely_ordered α] (h : a < b) : Inf (Ioc a b) = a := (is_glb_Ioc h).cInf_eq (nonempty_Ioc.2 h) @[simp] lemma cInf_Ioi [no_max_order α] [densely_ordered α] : Inf (Ioi a) = a := cInf_eq_of_forall_ge_of_forall_gt_exists_lt nonempty_Ioi (λ _, le_of_lt) (λ w hw, by simpa using exists_between hw) @[simp] lemma cInf_Ioo [densely_ordered α] (h : a < b) : Inf (Ioo a b) = a := (is_glb_Ioo h).cInf_eq (nonempty_Ioo.2 h) @[simp] lemma cSup_Icc (h : a ≤ b) : Sup (Icc a b) = b := (is_lub_Icc h).cSup_eq (nonempty_Icc.2 h) @[simp] lemma cSup_Ico [densely_ordered α] (h : a < b) : Sup (Ico a b) = b := (is_lub_Ico h).cSup_eq (nonempty_Ico.2 h) @[simp] lemma cSup_Iic : Sup (Iic a) = a := is_greatest_Iic.cSup_eq @[simp] lemma cSup_Iio [no_min_order α] [densely_ordered α] : Sup (Iio a) = a := cSup_eq_of_forall_le_of_forall_lt_exists_gt nonempty_Iio (λ _, le_of_lt) (λ w hw, by simpa [and_comm] using exists_between hw) @[simp] lemma cSup_Ioc (h : a < b) : Sup (Ioc a b) = b := (is_lub_Ioc h).cSup_eq (nonempty_Ioc.2 h) @[simp] lemma cSup_Ioo [densely_ordered α] (h : a < b) : Sup (Ioo a b) = b := (is_lub_Ioo h).cSup_eq (nonempty_Ioo.2 h) /--The indexed supremum of a function is bounded above by a uniform bound-/ lemma csupr_le [nonempty ι] {f : ι → α} {c : α} (H : ∀ x, f x ≤ c) : supr f ≤ c := cSup_le (range_nonempty f) (by rwa forall_range_iff) /--The indexed supremum of a function is bounded below by the value taken at one point-/ lemma le_csupr {f : ι → α} (H : bdd_above (range f)) (c : ι) : f c ≤ supr f := le_cSup H (mem_range_self _) lemma le_csupr_of_le {f : ι → α} (H : bdd_above (range f)) (c : ι) (h : a ≤ f c) : a ≤ supr f := le_trans h (le_csupr H c) /--The indexed supremum of two functions are comparable if the functions are pointwise comparable-/ lemma csupr_mono {f g : ι → α} (B : bdd_above (range g)) (H : ∀ x, f x ≤ g x) : supr f ≤ supr g := begin casesI is_empty_or_nonempty ι, { rw [supr_of_empty', supr_of_empty'] }, { exact csupr_le (λ x, le_csupr_of_le B x (H x)) }, end lemma le_csupr_set {f : β → α} {s : set β} (H : bdd_above (f '' s)) {c : β} (hc : c ∈ s) : f c ≤ ⨆ i : s, f i := (le_cSup H $ mem_image_of_mem f hc).trans_eq Sup_image' /--The indexed infimum of two functions are comparable if the functions are pointwise comparable-/ lemma cinfi_mono {f g : ι → α} (B : bdd_below (range f)) (H : ∀ x, f x ≤ g x) : infi f ≤ infi g := @csupr_mono αᵒᵈ _ _ _ _ B H /--The indexed minimum of a function is bounded below by a uniform lower bound-/ lemma le_cinfi [nonempty ι] {f : ι → α} {c : α} (H : ∀ x, c ≤ f x) : c ≤ infi f := @csupr_le αᵒᵈ _ _ _ _ _ H /--The indexed infimum of a function is bounded above by the value taken at one point-/ lemma cinfi_le {f : ι → α} (H : bdd_below (range f)) (c : ι) : infi f ≤ f c := @le_csupr αᵒᵈ _ _ _ H c lemma cinfi_le_of_le {f : ι → α} (H : bdd_below (range f)) (c : ι) (h : f c ≤ a) : infi f ≤ a := @le_csupr_of_le αᵒᵈ _ _ _ _ H c h lemma cinfi_set_le {f : β → α} {s : set β} (H : bdd_below (f '' s)) {c : β} (hc : c ∈ s) : (⨅ i : s, f i) ≤ f c := @le_csupr_set αᵒᵈ _ _ _ _ H _ hc @[simp] theorem csupr_const [hι : nonempty ι] {a : α} : (⨆ b : ι, a) = a := by rw [supr, range_const, cSup_singleton] @[simp] theorem cinfi_const [hι : nonempty ι] {a : α} : (⨅ b:ι, a) = a := @csupr_const αᵒᵈ _ _ _ _ @[simp] theorem supr_unique [unique ι] {s : ι → α} : (⨆ i, s i) = s default := have ∀ i, s i = s default := λ i, congr_arg s (unique.eq_default i), by simp only [this, csupr_const] @[simp] theorem infi_unique [unique ι] {s : ι → α} : (⨅ i, s i) = s default := @supr_unique αᵒᵈ _ _ _ _ @[simp] lemma csupr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp := by haveI := unique_prop hp; exact supr_unique @[simp] lemma cinfi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp := @csupr_pos αᵒᵈ _ _ _ hp /--Introduction rule to prove that `b` is the supremum of `f`: it suffices to check that `b` is larger than `f i` for all `i`, and that this is not the case of any `w<b`. See `supr_eq_of_forall_le_of_forall_lt_exists_gt` for a version in complete lattices. -/ theorem csupr_eq_of_forall_le_of_forall_lt_exists_gt [nonempty ι] {f : ι → α} (h₁ : ∀ i, f i ≤ b) (h₂ : ∀ w, w < b → (∃ i, w < f i)) : (⨆ (i : ι), f i) = b := cSup_eq_of_forall_le_of_forall_lt_exists_gt (range_nonempty f) (forall_range_iff.mpr h₁) (λ w hw, exists_range_iff.mpr $ h₂ w hw) /--Introduction rule to prove that `b` is the infimum of `f`: it suffices to check that `b` is smaller than `f i` for all `i`, and that this is not the case of any `w>b`. See `infi_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in complete lattices. -/ theorem cinfi_eq_of_forall_ge_of_forall_gt_exists_lt [nonempty ι] {f : ι → α} (h₁ : ∀ i, b ≤ f i) (h₂ : ∀ w, b < w → (∃ i, f i < w)) : (⨅ (i : ι), f i) = b := @csupr_eq_of_forall_le_of_forall_lt_exists_gt αᵒᵈ _ _ _ _ ‹_› ‹_› ‹_› /-- Nested intervals lemma: if `f` is a monotone sequence, `g` is an antitone sequence, and `f n ≤ g n` for all `n`, then `⨆ n, f n` belongs to all the intervals `[f n, g n]`. -/ lemma monotone.csupr_mem_Inter_Icc_of_antitone [semilattice_sup β] {f g : β → α} (hf : monotone f) (hg : antitone g) (h : f ≤ g) : (⨆ n, f n) ∈ ⋂ n, Icc (f n) (g n) := begin refine mem_Inter.2 (λ n, _), haveI : nonempty β := ⟨n⟩, have : ∀ m, f m ≤ g n := λ m, hf.forall_le_of_antitone hg h m n, exact ⟨le_csupr ⟨g $ n, forall_range_iff.2 this⟩ _, csupr_le this⟩ end /-- Nested intervals lemma: if `[f n, g n]` is an antitone sequence of nonempty closed intervals, then `⨆ n, f n` belongs to all the intervals `[f n, g n]`. -/ lemma csupr_mem_Inter_Icc_of_antitone_Icc [semilattice_sup β] {f g : β → α} (h : antitone (λ n, Icc (f n) (g n))) (h' : ∀ n, f n ≤ g n) : (⨆ n, f n) ∈ ⋂ n, Icc (f n) (g n) := monotone.csupr_mem_Inter_Icc_of_antitone (λ m n hmn, ((Icc_subset_Icc_iff (h' n)).1 (h hmn)).1) (λ m n hmn, ((Icc_subset_Icc_iff (h' n)).1 (h hmn)).2) h' /--Introduction rule to prove that b is the supremum of s: it suffices to check that 1) b is an upper bound 2) every other upper bound b' satisfies b ≤ b'.-/ theorem cSup_eq_of_is_forall_le_of_forall_le_imp_ge (hs : s.nonempty) (h_is_ub : ∀ a ∈ s, a ≤ b) (h_b_le_ub : ∀ub, (∀ a ∈ s, a ≤ ub) → (b ≤ ub)) : Sup s = b := (cSup_le hs h_is_ub).antisymm (h_b_le_ub _ $ λ a, le_cSup ⟨b, h_is_ub⟩) end conditionally_complete_lattice instance pi.conditionally_complete_lattice {ι : Type*} {α : Π i : ι, Type*} [Π i, conditionally_complete_lattice (α i)] : conditionally_complete_lattice (Π i, α i) := { le_cSup := λ s f ⟨g, hg⟩ hf i, le_cSup ⟨g i, set.forall_range_iff.2 $ λ ⟨f', hf'⟩, hg hf' i⟩ ⟨⟨f, hf⟩, rfl⟩, cSup_le := λ s f hs hf i, cSup_le (by haveI := hs.to_subtype; apply range_nonempty) $ λ b ⟨⟨g, hg⟩, hb⟩, hb ▸ hf hg i, cInf_le := λ s f ⟨g, hg⟩ hf i, cInf_le ⟨g i, set.forall_range_iff.2 $ λ ⟨f', hf'⟩, hg hf' i⟩ ⟨⟨f, hf⟩, rfl⟩, le_cInf := λ s f hs hf i, le_cInf (by haveI := hs.to_subtype; apply range_nonempty) $ λ b ⟨⟨g, hg⟩, hb⟩, hb ▸ hf hg i, .. pi.lattice, .. pi.has_Sup, .. pi.has_Inf } section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] {s t : set α} {a b : α} /-- When b < Sup s, there is an element a in s with b < a, if s is nonempty and the order is a linear order. -/ lemma exists_lt_of_lt_cSup (hs : s.nonempty) (hb : b < Sup s) : ∃ a ∈ s, b < a := by { contrapose! hb, exact cSup_le hs hb } /-- Indexed version of the above lemma `exists_lt_of_lt_cSup`. When `b < supr f`, there is an element `i` such that `b < f i`. -/ lemma exists_lt_of_lt_csupr [nonempty ι] {f : ι → α} (h : b < supr f) : ∃ i, b < f i := let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_lt_cSup (range_nonempty f) h in ⟨i, h⟩ /--When Inf s < b, there is an element a in s with a < b, if s is nonempty and the order is a linear order.-/ lemma exists_lt_of_cInf_lt (hs : s.nonempty) (hb : Inf s < b) : ∃ a ∈ s, a < b := @exists_lt_of_lt_cSup αᵒᵈ _ _ _ hs hb /-- Indexed version of the above lemma `exists_lt_of_cInf_lt` When `infi f < a`, there is an element `i` such that `f i < a`. -/ lemma exists_lt_of_cinfi_lt [nonempty ι] {f : ι → α} (h : infi f < a) : ∃ i, f i < a := @exists_lt_of_lt_csupr αᵒᵈ _ _ _ _ _ h open function variables [is_well_order α (<)] lemma Inf_eq_argmin_on (hs : s.nonempty) : Inf s = argmin_on id (@is_well_founded.wf α (<) _) s hs := is_least.cInf_eq ⟨argmin_on_mem _ _ _ _, λ a ha, argmin_on_le id _ _ ha⟩ lemma is_least_Inf (hs : s.nonempty) : is_least s (Inf s) := by { rw Inf_eq_argmin_on hs, exact ⟨argmin_on_mem _ _ _ _, λ a ha, argmin_on_le id _ _ ha⟩ } lemma le_cInf_iff' (hs : s.nonempty) : b ≤ Inf s ↔ b ∈ lower_bounds s := le_is_glb_iff (is_least_Inf hs).is_glb lemma Inf_mem (hs : s.nonempty) : Inf s ∈ s := (is_least_Inf hs).1 lemma infi_mem [nonempty ι] (f : ι → α) : infi f ∈ range f := Inf_mem (range_nonempty f) lemma monotone_on.map_Inf {β : Type*} [conditionally_complete_lattice β] {f : α → β} (hf : monotone_on f s) (hs : s.nonempty) : f (Inf s) = Inf (f '' s) := (hf.map_is_least (is_least_Inf hs)).cInf_eq.symm lemma monotone.map_Inf {β : Type*} [conditionally_complete_lattice β] {f : α → β} (hf : monotone f) (hs : s.nonempty) : f (Inf s) = Inf (f '' s) := (hf.map_is_least (is_least_Inf hs)).cInf_eq.symm end conditionally_complete_linear_order /-! ### Lemmas about a conditionally complete linear order with bottom element In this case we have `Sup ∅ = ⊥`, so we can drop some `nonempty`/`set.nonempty` assumptions. -/ section conditionally_complete_linear_order_bot variables [conditionally_complete_linear_order_bot α] @[simp] lemma cSup_empty : (Sup ∅ : α) = ⊥ := conditionally_complete_linear_order_bot.cSup_empty @[simp] lemma csupr_of_empty [is_empty ι] (f : ι → α) : (⨆ i, f i) = ⊥ := by rw [supr_of_empty', cSup_empty] @[simp] lemma csupr_false (f : false → α) : (⨆ i, f i) = ⊥ := csupr_of_empty f @[simp] lemma cInf_univ : Inf (univ : set α) = ⊥ := is_least_univ.cInf_eq lemma is_lub_cSup' {s : set α} (hs : bdd_above s) : is_lub s (Sup s) := begin rcases eq_empty_or_nonempty s with (rfl|hne), { simp only [cSup_empty, is_lub_empty] }, { exact is_lub_cSup hne hs } end lemma cSup_le_iff' {s : set α} (hs : bdd_above s) {a : α} : Sup s ≤ a ↔ ∀ x ∈ s, x ≤ a := is_lub_le_iff (is_lub_cSup' hs) lemma cSup_le' {s : set α} {a : α} (h : a ∈ upper_bounds s) : Sup s ≤ a := (cSup_le_iff' ⟨a, h⟩).2 h theorem le_cSup_iff' {s : set α} {a : α} (h : bdd_above s) : a ≤ Sup s ↔ ∀ b, b ∈ upper_bounds s → a ≤ b := ⟨λ h b hb, le_trans h (cSup_le' hb), λ hb, hb _ (λ x, le_cSup h)⟩ lemma le_csupr_iff' {s : ι → α} {a : α} (h : bdd_above (range s)) : a ≤ supr s ↔ ∀ b, (∀ i, s i ≤ b) → a ≤ b := by simp [supr, h, le_cSup_iff', upper_bounds] theorem le_cInf_iff'' {s : set α} {a : α} (ne : s.nonempty) : a ≤ Inf s ↔ ∀ (b : α), b ∈ s → a ≤ b := le_cInf_iff ⟨⊥, λ a _, bot_le⟩ ne theorem le_cinfi_iff' [nonempty ι] {f : ι → α} {a : α} : a ≤ infi f ↔ ∀ i, a ≤ f i := le_cinfi_iff ⟨⊥, λ a _, bot_le⟩ theorem cInf_le' {s : set α} {a : α} (h : a ∈ s) : Inf s ≤ a := cInf_le ⟨⊥, λ a _, bot_le⟩ h theorem cinfi_le' (f : ι → α) (i : ι) : infi f ≤ f i := cinfi_le ⟨⊥, λ a _, bot_le⟩ _ lemma exists_lt_of_lt_cSup' {s : set α} {a : α} (h : a < Sup s) : ∃ b ∈ s, a < b := by { contrapose! h, exact cSup_le' h } lemma csupr_le_iff' {f : ι → α} (h : bdd_above (range f)) {a : α} : (⨆ i, f i) ≤ a ↔ ∀ i, f i ≤ a := (cSup_le_iff' h).trans forall_range_iff lemma csupr_le' {f : ι → α} {a : α} (h : ∀ i, f i ≤ a) : (⨆ i, f i) ≤ a := cSup_le' $ forall_range_iff.2 h lemma exists_lt_of_lt_csupr' {f : ι → α} {a : α} (h : a < ⨆ i, f i) : ∃ i, a < f i := by { contrapose! h, exact csupr_le' h } lemma csupr_mono' {ι'} {f : ι → α} {g : ι' → α} (hg : bdd_above (range g)) (h : ∀ i, ∃ i', f i ≤ g i') : supr f ≤ supr g := csupr_le' $ λ i, exists.elim (h i) (le_csupr_of_le hg) lemma cInf_le_cInf' {s t : set α} (h₁ : t.nonempty) (h₂ : t ⊆ s) : Inf s ≤ Inf t := cInf_le_cInf (order_bot.bdd_below s) h₁ h₂ end conditionally_complete_linear_order_bot namespace with_top open_locale classical variables [conditionally_complete_linear_order_bot α] /-- The Sup of a non-empty set is its least upper bound for a conditionally complete lattice with a top. -/ lemma is_lub_Sup' {β : Type*} [conditionally_complete_lattice β] {s : set (with_top β)} (hs : s.nonempty) : is_lub s (Sup s) := begin split, { show ite _ _ _ ∈ _, split_ifs, { intros _ _, exact le_top }, { rintro (⟨⟩|a) ha, { contradiction }, apply some_le_some.2, exact le_cSup h_1 ha }, { intros _ _, exact le_top } }, { show ite _ _ _ ∈ _, split_ifs, { rintro (⟨⟩|a) ha, { exact le_rfl }, { exact false.elim (not_top_le_coe a (ha h)) } }, { rintro (⟨⟩|b) hb, { exact le_top }, refine some_le_some.2 (cSup_le _ _), { rcases hs with ⟨⟨⟩|b, hb⟩, { exact absurd hb h }, { exact ⟨b, hb⟩ } }, { intros a ha, exact some_le_some.1 (hb ha) } }, { rintro (⟨⟩|b) hb, { exact le_rfl }, { exfalso, apply h_1, use b, intros a ha, exact some_le_some.1 (hb ha) } } } end lemma is_lub_Sup (s : set (with_top α)) : is_lub s (Sup s) := begin cases s.eq_empty_or_nonempty with hs hs, { rw hs, show is_lub ∅ (ite _ _ _), split_ifs, { cases h }, { rw [preimage_empty, cSup_empty], exact is_lub_empty }, { exfalso, apply h_1, use ⊥, rintro a ⟨⟩ } }, exact is_lub_Sup' hs, end /-- The Inf of a bounded-below set is its greatest lower bound for a conditionally complete lattice with a top. -/ lemma is_glb_Inf' {β : Type*} [conditionally_complete_lattice β] {s : set (with_top β)} (hs : bdd_below s) : is_glb s (Inf s) := begin split, { show ite _ _ _ ∈ _, split_ifs, { intros a ha, exact top_le_iff.2 (set.mem_singleton_iff.1 (h ha)) }, { rintro (⟨⟩|a) ha, { exact le_top }, refine some_le_some.2 (cInf_le _ ha), rcases hs with ⟨⟨⟩|b, hb⟩, { exfalso, apply h, intros c hc, rw [mem_singleton_iff, ←top_le_iff], exact hb hc }, use b, intros c hc, exact some_le_some.1 (hb hc) } }, { show ite _ _ _ ∈ _, split_ifs, { intros _ _, exact le_top }, { rintro (⟨⟩|a) ha, { exfalso, apply h, intros b hb, exact set.mem_singleton_iff.2 (top_le_iff.1 (ha hb)) }, { refine some_le_some.2 (le_cInf _ _), { classical, contrapose! h, rintros (⟨⟩|a) ha, { exact mem_singleton ⊤ }, { exact (h ⟨a, ha⟩).elim }}, { intros b hb, rw ←some_le_some, exact ha hb } } } } end lemma is_glb_Inf (s : set (with_top α)) : is_glb s (Inf s) := begin by_cases hs : bdd_below s, { exact is_glb_Inf' hs }, { exfalso, apply hs, use ⊥, intros _ _, exact bot_le }, end noncomputable instance : complete_linear_order (with_top α) := { Sup := Sup, le_Sup := λ s, (is_lub_Sup s).1, Sup_le := λ s, (is_lub_Sup s).2, Inf := Inf, le_Inf := λ s, (is_glb_Inf s).2, Inf_le := λ s, (is_glb_Inf s).1, .. with_top.linear_order, ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } /-- A version of `with_top.coe_Sup'` with a more convenient but less general statement. -/ @[norm_cast] lemma coe_Sup {s : set α} (hb : bdd_above s) : ↑(Sup s) = (⨆ a ∈ s, ↑a : with_top α) := by rw [coe_Sup' hb, Sup_image] /-- A version of `with_top.coe_Inf'` with a more convenient but less general statement. -/ @[norm_cast] lemma coe_Inf {s : set α} (hs : s.nonempty) : ↑(Inf s) = (⨅ a ∈ s, ↑a : with_top α) := by rw [coe_Inf' hs, Inf_image] end with_top namespace monotone variables [preorder α] [conditionally_complete_lattice β] {f : α → β} (h_mono : monotone f) /-! A monotone function into a conditionally complete lattice preserves the ordering properties of `Sup` and `Inf`. -/ lemma le_cSup_image {s : set α} {c : α} (hcs : c ∈ s) (h_bdd : bdd_above s) : f c ≤ Sup (f '' s) := le_cSup (map_bdd_above h_mono h_bdd) (mem_image_of_mem f hcs) lemma cSup_image_le {s : set α} (hs : s.nonempty) {B : α} (hB: B ∈ upper_bounds s) : Sup (f '' s) ≤ f B := cSup_le (nonempty.image f hs) (h_mono.mem_upper_bounds_image hB) lemma cInf_image_le {s : set α} {c : α} (hcs : c ∈ s) (h_bdd : bdd_below s) : Inf (f '' s) ≤ f c := @le_cSup_image αᵒᵈ βᵒᵈ _ _ _ (λ x y hxy, h_mono hxy) _ _ hcs h_bdd lemma le_cInf_image {s : set α} (hs : s.nonempty) {B : α} (hB: B ∈ lower_bounds s) : f B ≤ Inf (f '' s) := @cSup_image_le αᵒᵈ βᵒᵈ _ _ _ (λ x y hxy, h_mono hxy) _ hs _ hB end monotone namespace galois_connection variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι] {l : α → β} {u : β → α} lemma l_cSup (gc : galois_connection l u) {s : set α} (hne : s.nonempty) (hbdd : bdd_above s) : l (Sup s) = ⨆ x : s, l x := eq.symm $ is_lub.csupr_set_eq (gc.is_lub_l_image $ is_lub_cSup hne hbdd) hne lemma l_cSup' (gc : galois_connection l u) {s : set α} (hne : s.nonempty) (hbdd : bdd_above s) : l (Sup s) = Sup (l '' s) := by rw [gc.l_cSup hne hbdd, Sup_image'] lemma l_csupr (gc : galois_connection l u) {f : ι → α} (hf : bdd_above (range f)) : l (⨆ i, f i) = ⨆ i, l (f i) := by rw [supr, gc.l_cSup (range_nonempty _) hf, supr_range'] lemma l_csupr_set (gc : galois_connection l u) {s : set γ} {f : γ → α} (hf : bdd_above (f '' s)) (hne : s.nonempty) : l (⨆ i : s, f i) = ⨆ i : s, l (f i) := by { haveI := hne.to_subtype, rw image_eq_range at hf, exact gc.l_csupr hf } lemma u_cInf (gc : galois_connection l u) {s : set β} (hne : s.nonempty) (hbdd : bdd_below s) : u (Inf s) = ⨅ x : s, u x := gc.dual.l_cSup hne hbdd lemma u_cInf' (gc : galois_connection l u) {s : set β} (hne : s.nonempty) (hbdd : bdd_below s) : u (Inf s) = Inf (u '' s) := gc.dual.l_cSup' hne hbdd lemma u_cinfi (gc : galois_connection l u) {f : ι → β} (hf : bdd_below (range f)) : u (⨅ i, f i) = ⨅ i, u (f i) := gc.dual.l_csupr hf lemma u_cinfi_set (gc : galois_connection l u) {s : set γ} {f : γ → β} (hf : bdd_below (f '' s)) (hne : s.nonempty) : u (⨅ i : s, f i) = ⨅ i : s, u (f i) := gc.dual.l_csupr_set hf hne end galois_connection namespace order_iso variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι] lemma map_cSup (e : α ≃o β) {s : set α} (hne : s.nonempty) (hbdd : bdd_above s) : e (Sup s) = ⨆ x : s, e x := e.to_galois_connection.l_cSup hne hbdd lemma map_cSup' (e : α ≃o β) {s : set α} (hne : s.nonempty) (hbdd : bdd_above s) : e (Sup s) = Sup (e '' s) := e.to_galois_connection.l_cSup' hne hbdd lemma map_csupr (e : α ≃o β) {f : ι → α} (hf : bdd_above (range f)) : e (⨆ i, f i) = ⨆ i, e (f i) := e.to_galois_connection.l_csupr hf lemma map_csupr_set (e : α ≃o β) {s : set γ} {f : γ → α} (hf : bdd_above (f '' s)) (hne : s.nonempty) : e (⨆ i : s, f i) = ⨆ i : s, e (f i) := e.to_galois_connection.l_csupr_set hf hne lemma map_cInf (e : α ≃o β) {s : set α} (hne : s.nonempty) (hbdd : bdd_below s) : e (Inf s) = ⨅ x : s, e x := e.dual.map_cSup hne hbdd lemma map_cInf' (e : α ≃o β) {s : set α} (hne : s.nonempty) (hbdd : bdd_below s) : e (Inf s) = Inf (e '' s) := e.dual.map_cSup' hne hbdd lemma map_cinfi (e : α ≃o β) {f : ι → α} (hf : bdd_below (range f)) : e (⨅ i, f i) = ⨅ i, e (f i) := e.dual.map_csupr hf lemma map_cinfi_set (e : α ≃o β) {s : set γ} {f : γ → α} (hf : bdd_below (f '' s)) (hne : s.nonempty) : e (⨅ i : s, f i) = ⨅ i : s, e (f i) := e.dual.map_csupr_set hf hne end order_iso /-! ### Supremum/infimum of `set.image2` A collection of lemmas showing what happens to the suprema/infima of `s` and `t` when mapped under a binary function whose partial evaluations are lower/upper adjoints of Galois connections. -/ section variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [conditionally_complete_lattice γ] {f : α → β → γ} {s : set α} {t : set β} variables {l u : α → β → γ} {l₁ u₁ : β → γ → α} {l₂ u₂ : α → γ → β} lemma cSup_image2_eq_cSup_cSup (h₁ : ∀ b, galois_connection (swap l b) (u₁ b)) (h₂ : ∀ a, galois_connection (l a) (u₂ a)) (hs₀ : s.nonempty) (hs₁ : bdd_above s) (ht₀ : t.nonempty) (ht₁ : bdd_above t) : Sup (image2 l s t) = l (Sup s) (Sup t) := begin refine eq_of_forall_ge_iff (λ c, _), rw [cSup_le_iff (hs₁.image2 (λ _, (h₁ _).monotone_l) (λ _, (h₂ _).monotone_l) ht₁) (hs₀.image2 ht₀), forall_image2_iff, forall₂_swap, (h₂ _).le_iff_le, cSup_le_iff ht₁ ht₀], simp_rw [←(h₂ _).le_iff_le, (h₁ _).le_iff_le, cSup_le_iff hs₁ hs₀], end lemma cSup_image2_eq_cSup_cInf (h₁ : ∀ b, galois_connection (swap l b) (u₁ b)) (h₂ : ∀ a, galois_connection (l a ∘ of_dual) (to_dual ∘ u₂ a)) : s.nonempty → bdd_above s → t.nonempty → bdd_below t → Sup (image2 l s t) = l (Sup s) (Inf t) := @cSup_image2_eq_cSup_cSup _ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma cSup_image2_eq_cInf_cSup (h₁ : ∀ b, galois_connection (swap l b ∘ of_dual) (to_dual ∘ u₁ b)) (h₂ : ∀ a, galois_connection (l a) (u₂ a)) : s.nonempty → bdd_below s → t.nonempty → bdd_above t → Sup (image2 l s t) = l (Inf s) (Sup t) := @cSup_image2_eq_cSup_cSup αᵒᵈ _ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma cSup_image2_eq_cInf_cInf (h₁ : ∀ b, galois_connection (swap l b ∘ of_dual) (to_dual ∘ u₁ b)) (h₂ : ∀ a, galois_connection (l a ∘ of_dual) (to_dual ∘ u₂ a)) : s.nonempty → bdd_below s → t.nonempty → bdd_below t → Sup (image2 l s t) = l (Inf s) (Inf t) := @cSup_image2_eq_cSup_cSup αᵒᵈ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma cInf_image2_eq_cInf_cInf (h₁ : ∀ b, galois_connection (l₁ b) (swap u b)) (h₂ : ∀ a, galois_connection (l₂ a) (u a)) : s.nonempty → bdd_below s → t.nonempty → bdd_below t → Inf (image2 u s t) = u (Inf s) (Inf t) := @cSup_image2_eq_cSup_cSup αᵒᵈ βᵒᵈ γᵒᵈ _ _ _ _ _ _ l₁ l₂ (λ _, (h₁ _).dual) (λ _, (h₂ _).dual) lemma cInf_image2_eq_cInf_cSup (h₁ : ∀ b, galois_connection (l₁ b) (swap u b)) (h₂ : ∀ a, galois_connection (to_dual ∘ l₂ a) (u a ∘ of_dual)) : s.nonempty → bdd_below s → t.nonempty → bdd_above t → Inf (image2 u s t) = u (Inf s) (Sup t) := @cInf_image2_eq_cInf_cInf _ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma cInf_image2_eq_cSup_cInf (h₁ : ∀ b, galois_connection (to_dual ∘ l₁ b) (swap u b ∘ of_dual)) (h₂ : ∀ a, galois_connection (l₂ a) (u a)) : s.nonempty → bdd_above s → t.nonempty → bdd_below t → Inf (image2 u s t) = u (Sup s) (Inf t) := @cInf_image2_eq_cInf_cInf αᵒᵈ _ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma cInf_image2_eq_cSup_cSup (h₁ : ∀ b, galois_connection (to_dual ∘ l₁ b) (swap u b ∘ of_dual)) (h₂ : ∀ a, galois_connection (to_dual ∘ l₂ a) (u a ∘ of_dual)) : s.nonempty → bdd_above s → t.nonempty → bdd_above t → Inf (image2 u s t) = u (Sup s) (Sup t) := @cInf_image2_eq_cInf_cInf αᵒᵈ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂ end section with_top_bot /-! ### Complete lattice structure on `with_top (with_bot α)` If `α` is a `conditionally_complete_lattice`, then we show that `with_top α` and `with_bot α` also inherit the structure of conditionally complete lattices. Furthermore, we show that `with_top (with_bot α)` and `with_bot (with_top α)` naturally inherit the structure of a complete lattice. Note that for `α` a conditionally complete lattice, `Sup` and `Inf` both return junk values for sets which are empty or unbounded. The extension of `Sup` to `with_top α` fixes the unboundedness problem and the extension to `with_bot α` fixes the problem with the empty set. This result can be used to show that the extended reals `[-∞, ∞]` are a complete linear order. -/ open_locale classical /-- Adding a top element to a conditionally complete lattice gives a conditionally complete lattice -/ noncomputable instance with_top.conditionally_complete_lattice {α : Type*} [conditionally_complete_lattice α] : conditionally_complete_lattice (with_top α) := { le_cSup := λ S a hS haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS, cSup_le := λ S a hS haS, (with_top.is_lub_Sup' hS).2 haS, cInf_le := λ S a hS haS, (with_top.is_glb_Inf' hS).1 haS, le_cInf := λ S a hS haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS, ..with_top.lattice, ..with_top.has_Sup, ..with_top.has_Inf } /-- Adding a bottom element to a conditionally complete lattice gives a conditionally complete lattice -/ noncomputable instance with_bot.conditionally_complete_lattice {α : Type*} [conditionally_complete_lattice α] : conditionally_complete_lattice (with_bot α) := { le_cSup := (@with_top.conditionally_complete_lattice αᵒᵈ _).cInf_le, cSup_le := (@with_top.conditionally_complete_lattice αᵒᵈ _).le_cInf, cInf_le := (@with_top.conditionally_complete_lattice αᵒᵈ _).le_cSup, le_cInf := (@with_top.conditionally_complete_lattice αᵒᵈ _).cSup_le, ..with_bot.lattice, ..with_bot.has_Sup, ..with_bot.has_Inf } noncomputable instance with_top.with_bot.complete_lattice {α : Type*} [conditionally_complete_lattice α] : complete_lattice (with_top (with_bot α)) := { le_Sup := λ S a haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS, Sup_le := λ S a ha, begin cases S.eq_empty_or_nonempty with h, { show ite _ _ _ ≤ a, split_ifs, { rw h at h_1, cases h_1 }, { convert bot_le, convert with_bot.cSup_empty, rw h, refl }, { exfalso, apply h_2, use ⊥, rw h, rintro b ⟨⟩ } }, { refine (with_top.is_lub_Sup' h).2 ha } end, Inf_le := λ S a haS, show ite _ _ _ ≤ a, begin split_ifs, { cases a with a, exact le_rfl, cases (h haS); tauto }, { cases a, { exact le_top }, { apply with_top.some_le_some.2, refine cInf_le _ haS, use ⊥, intros b hb, exact bot_le } } end, le_Inf := λ S a haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS, ..with_top.has_Inf, ..with_top.has_Sup, ..with_top.bounded_order, ..with_top.lattice } noncomputable instance with_top.with_bot.complete_linear_order {α : Type*} [conditionally_complete_linear_order α] : complete_linear_order (with_top (with_bot α)) := { .. with_top.with_bot.complete_lattice, .. with_top.linear_order } noncomputable instance with_bot.with_top.complete_lattice {α : Type*} [conditionally_complete_lattice α] : complete_lattice (with_bot (with_top α)) := { le_Sup := (@with_top.with_bot.complete_lattice αᵒᵈ _).Inf_le, Sup_le := (@with_top.with_bot.complete_lattice αᵒᵈ _).le_Inf, Inf_le := (@with_top.with_bot.complete_lattice αᵒᵈ _).le_Sup, le_Inf := (@with_top.with_bot.complete_lattice αᵒᵈ _).Sup_le, ..with_bot.has_Inf, ..with_bot.has_Sup, ..with_bot.bounded_order, ..with_bot.lattice } noncomputable instance with_bot.with_top.complete_linear_order {α : Type*} [conditionally_complete_linear_order α] : complete_linear_order (with_bot (with_top α)) := { .. with_bot.with_top.complete_lattice, .. with_bot.linear_order } lemma with_top.supr_coe_eq_top {ι : Sort*} {α : Type*} [conditionally_complete_linear_order_bot α] (f : ι → α) : (⨆ x, (f x : with_top α)) = ⊤ ↔ ¬ bdd_above (set.range f) := begin rw [supr_eq_top, not_bdd_above_iff], refine ⟨λ hf r, _, λ hf a ha, _⟩, { rcases hf r (with_top.coe_lt_top r) with ⟨i, hi⟩, exact ⟨f i, ⟨i, rfl⟩, with_top.coe_lt_coe.mp hi⟩ }, { rcases hf (a.untop ha.ne) with ⟨-, ⟨i, rfl⟩, hi⟩, exact ⟨i, by simpa only [with_top.coe_untop _ ha.ne] using with_top.coe_lt_coe.mpr hi⟩ }, end lemma with_top.supr_coe_lt_top {ι : Sort*} {α : Type*} [conditionally_complete_linear_order_bot α] (f : ι → α) : (⨆ x, (f x : with_top α)) < ⊤ ↔ bdd_above (set.range f) := lt_top_iff_ne_top.trans $ (with_top.supr_coe_eq_top f).not.trans not_not end with_top_bot -- Guard against import creep assert_not_exists multiset
17783f80e7f5f22315166c9bc309d0cbed7ea1c1
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/set/function.lean
f47b2c72c945e7873201ab8ba58ef803675c129e
[ "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
17,563
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Andrew Zipperer, Haitao Zhang, Minchao Wu, Yury Kudryashov -/ import data.set.basic logic.function /-! # Functions over sets ## Main definitions ### Predicate * `eq_on f₁ f₂ s` : functions `f₁` and `f₂` are equal at every point of `s`; * `maps_to f s t` : `f` sends every point of `s` to a point of `t`; * `inj_on f s` : restriction of `f` to `s` is injective; * `surj_on f s t` : every point in `s` has a preimage in `s`; * `bij_on f s t` : `f` is a bijection between `s` and `t`; * `left_inv_on f' f s` : for every `x ∈ s` we have `f' (f x) = x`; * `right_inv_on f' f t` : for every `y ∈ t` we have `f (f' y) = y`; * `inv_on f' f s t` : `f'` is a two-side inverse of `f` on `s` and `t`, i.e. we have `left_inv_on f' f s` and `right_inv_on f' f t`. ### Functions * `restrict f s` : restrict the domain of `f` to the set `s`; * `cod_restrict f s h` : given `h : ∀ x, f x ∈ s`, restrict the codomain of `f` to the set `s`; * `maps_to.restrict f s t h`: given `h : maps_to f s t`, restrict the domain of `f` to `s` and the codomain to `t`. -/ universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} open function namespace set /-! ### Restrict -/ /-- Restrict domain of a function `f` to a set `s`. Same as `subtype.restrict` but this version takes an argument `↥s` instead of `subtype s`. -/ def restrict (f : α → β) (s : set α) : s → β := λ x, f x lemma restrict_eq (f : α → β) (s : set α) : s.restrict f = f ∘ coe := rfl @[simp] lemma restrict_apply (f : α → β) (s : set α) (x : s) : restrict f s x = f x := rfl @[simp] lemma range_restrict (f : α → β) (s : set α) : set.range (restrict f s) = f '' s := range_comp.trans $ congr_arg (('') f) s.range_coe_subtype /-- Restrict codomain of a function `f` to a set `s`. Same as `subtype.coind` but this version has codomain `↥s` instead of `subtype s`. -/ def cod_restrict (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) : α → s := λ x, ⟨f x, h x⟩ @[simp] lemma coe_cod_restrict_apply (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) (x : α) : (cod_restrict f s h x : β) = f x := rfl variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} {p : set γ} {f f₁ f₂ f₃ : α → β} {g : β → γ} {f' f₁' f₂' : β → α} {g' : γ → β} /-! ### Equality on a set -/ /-- Two functions `f₁ f₂ : α → β` are equal on `s` if `f₁ x = f₂ x` for all `x ∈ a`. -/ @[reducible] def eq_on (f₁ f₂ : α → β) (s : set α) : Prop := ∀ ⦃x⦄, x ∈ s → f₁ x = f₂ x @[symm] lemma eq_on.symm (h : eq_on f₁ f₂ s) : eq_on f₂ f₁ s := λ x hx, (h hx).symm lemma eq_on_comm : eq_on f₁ f₂ s ↔ eq_on f₂ f₁ s := ⟨eq_on.symm, eq_on.symm⟩ @[refl] lemma eq_on_refl (f : α → β) (s : set α) : eq_on f f s := λ _ _, rfl @[trans] lemma eq_on.trans (h₁ : eq_on f₁ f₂ s) (h₂ : eq_on f₂ f₃ s) : eq_on f₁ f₃ s := λ x hx, (h₁ hx).trans (h₂ hx) theorem eq_on.image_eq (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s := image_congr heq lemma eq_on.mono (hs : s₁ ⊆ s₂) (hf : eq_on f₁ f₂ s₂) : eq_on f₁ f₂ s₁ := λ x hx, hf (hs hx) /-! ### maps to -/ /-- `maps_to f a b` means that the image of `a` is contained in `b`. -/ @[reducible] def maps_to (f : α → β) (s : set α) (t : set β) : Prop := s ⊆ f ⁻¹' t /-- Given a map `f` sending `s : set α` into `t : set β`, restrict domain of `f` to `s` and the codomain to `t`. Same as `subtype.map`. -/ def maps_to.restrict (f : α → β) (s : set α) (t : set β) (h : maps_to f s t) : s → t := subtype.map f h @[simp] lemma maps_to.coe_restrict_apply (h : maps_to f s t) (x : s) : (h.restrict f s t x : β) = f x := rfl theorem maps_to' : maps_to f s t ↔ f '' s ⊆ t := image_subset_iff.symm theorem maps_to_empty (f : α → β) (t : set β) : maps_to f ∅ t := empty_subset _ theorem maps_to.image_subset (h : maps_to f s t) : f '' s ⊆ t := maps_to'.1 h theorem maps_to.congr (h₁ : maps_to f₁ s t) (h : eq_on f₁ f₂ s) : maps_to f₂ s t := λ x hx, by rw [mem_preimage, ← h hx]; exact h₁ hx theorem eq_on.maps_to_iff (H : eq_on f₁ f₂ s) : maps_to f₁ s t ↔ maps_to f₂ s t := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ theorem maps_to.comp (h₁ : maps_to g t p) (h₂ : maps_to f s t) : maps_to (g ∘ f) s p := λ x h, h₁ (h₂ h) theorem maps_to.iterate {f : α → α} {s : set α} (h : maps_to f s s) : ∀ n, maps_to (f^[n]) s s | 0 := λ _, id | (n+1) := (maps_to.iterate n).comp h theorem maps_to.iterate_restrict {f : α → α} {s : set α} (h : maps_to f s s) (n : ℕ) : (h.restrict f s s^[n]) = (h.iterate n).restrict _ _ _ := begin funext x, rw [subtype.coe_ext, maps_to.coe_restrict_apply], induction n with n ihn generalizing x, { refl }, { simp [nat.iterate, ihn] } end theorem maps_to.mono (hs : s₂ ⊆ s₁) (ht : t₁ ⊆ t₂) (hf : maps_to f s₁ t₁) : maps_to f s₂ t₂ := λ x hx, ht (hf $ hs hx) theorem maps_to_univ (f : α → β) (s : set α) : maps_to f s univ := λ x h, trivial theorem maps_to_image (f : α → β) (s : set α) : maps_to f s (f '' s) := by rw maps_to' theorem maps_to_preimage (f : α → β) (t : set β) : maps_to f (f ⁻¹' t) t := subset.refl _ theorem maps_to_range (f : set α) (s : set α) : maps_to f s (range f) := (maps_to_image f s).mono (subset.refl s) (image_subset_range _ _) /-! ### Injectivity on a set -/ /-- `f` is injective on `a` if the restriction of `f` to `a` is injective. -/ @[reducible] def inj_on (f : α → β) (s : set α) : Prop := ∀⦃x₁ x₂ : α⦄, x₁ ∈ s → x₂ ∈ s → f x₁ = f x₂ → x₁ = x₂ theorem inj_on_empty (f : α → β) : inj_on f ∅ := λ _ _ h₁ _ _, false.elim h₁ theorem inj_on.congr (h₁ : inj_on f₁ s) (h : eq_on f₁ f₂ s) : inj_on f₂ s := λ x y hx hy, h hx ▸ h hy ▸ h₁ hx hy theorem eq_on.inj_on_iff (H : eq_on f₁ f₂ s) : inj_on f₁ s ↔ inj_on f₂ s := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ theorem inj_on.mono (h : s₁ ⊆ s₂) (ht : inj_on f s₂) : inj_on f s₁ := λ x y hx hy H, ht (h hx) (h hy) H lemma injective_iff_inj_on_univ : injective f ↔ inj_on f univ := ⟨λ h x y hx hy hxy, h hxy, λ h _ _ heq, h trivial trivial heq⟩ theorem inj_on.comp (hg : inj_on g t) (hf: inj_on f s) (h : maps_to f s t) : inj_on (g ∘ f) s := λ x y hx hy heq, hf hx hy $ hg (h hx) (h hy) heq lemma inj_on_iff_injective : inj_on f s ↔ injective (restrict f s) := ⟨λ H a b h, subtype.eq $ H a.2 b.2 h, λ H a b as bs h, congr_arg subtype.val $ @H ⟨a, as⟩ ⟨b, bs⟩ h⟩ lemma inj_on.inv_fun_on_image [nonempty α] (h : inj_on f s₂) (ht : s₁ ⊆ s₂) : (inv_fun_on f s₂) '' (f '' s₁) = s₁ := begin have : eq_on ((inv_fun_on f s₂) ∘ f) id s₁, from λz hz, inv_fun_on_eq' h (ht hz), rw [← image_comp, this.image_eq, image_id] end lemma inj_on_preimage {B : set (set β)} (hB : B ⊆ powerset (range f)) : inj_on (preimage f) B := begin intros s t hs ht hst, rw [←image_preimage_eq_of_subset (hB hs), ←image_preimage_eq_of_subset (hB ht), hst] end /-! ### Surjectivity on a set -/ /-- `f` is surjective from `a` to `b` if `b` is contained in the image of `a`. -/ @[reducible] def surj_on (f : α → β) (s : set α) (t : set β) : Prop := t ⊆ f '' s theorem surj_on_empty (f : α → β) (s : set α) : surj_on f s ∅ := empty_subset _ theorem surj_on.comap_nonempty (h : surj_on f s t) (ht : t.nonempty) : s.nonempty := (ht.mono h).of_image theorem surj_on.congr (h : surj_on f₁ s t) (H : eq_on f₁ f₂ s) : surj_on f₂ s t := by rwa [surj_on, ← H.image_eq] theorem eq_on.surj_on_iff (h : eq_on f₁ f₂ s) : surj_on f₁ s t ↔ surj_on f₂ s t := ⟨λ H, H.congr h, λ H, H.congr h.symm⟩ theorem surj_on.mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) (hf : surj_on f s₁ t₂) : surj_on f s₂ t₁ := subset.trans ht $ subset.trans hf $ image_subset _ hs theorem surj_on.comp (hg : surj_on g t p) (hf : surj_on f s t) : surj_on (g ∘ f) s p := subset.trans hg $ subset.trans (image_subset g hf) $ (image_comp g f s) ▸ subset.refl _ lemma surjective_iff_surj_on_univ : surjective f ↔ surj_on f univ univ := by simp [surjective, surj_on, subset_def] lemma surj_on_iff_surjective : surj_on f s univ ↔ surjective (restrict f s) := ⟨λ H b, let ⟨a, as, e⟩ := @H b trivial in ⟨⟨a, as⟩, e⟩, λ H b _, let ⟨⟨a, as⟩, e⟩ := H b in ⟨a, as, e⟩⟩ lemma surj_on.image_eq_of_maps_to (h₁ : surj_on f s t) (h₂ : maps_to f s t) : f '' s = t := eq_of_subset_of_subset h₂.image_subset h₁ /-! ### Bijectivity -/ /-- `f` is bijective from `s` to `t` if `f` is injective on `s` and `f '' s = t`. -/ @[reducible] def bij_on (f : α → β) (s : set α) (t : set β) : Prop := maps_to f s t ∧ inj_on f s ∧ surj_on f s t lemma bij_on.maps_to (h : bij_on f s t) : maps_to f s t := h.left lemma bij_on.inj_on (h : bij_on f s t) : inj_on f s := h.right.left lemma bij_on.surj_on (h : bij_on f s t) : surj_on f s t := h.right.right lemma bij_on.mk (h₁ : maps_to f s t) (h₂ : inj_on f s) (h₃ : surj_on f s t) : bij_on f s t := ⟨h₁, h₂, h₃⟩ lemma bij_on_empty (f : α → β) : bij_on f ∅ ∅ := ⟨maps_to_empty f ∅, inj_on_empty f, surj_on_empty f ∅⟩ lemma inj_on.bij_on_image (h : inj_on f s) : bij_on f s (f '' s) := bij_on.mk (maps_to_image f s) h (subset.refl _) theorem bij_on.congr (h₁ : bij_on f₁ s t) (h : eq_on f₁ f₂ s) : bij_on f₂ s t := bij_on.mk (h₁.maps_to.congr h) (h₁.inj_on.congr h) (h₁.surj_on.congr h) theorem eq_on.bij_on_iff (H : eq_on f₁ f₂ s) : bij_on f₁ s t ↔ bij_on f₂ s t := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ lemma bij_on.image_eq (h : bij_on f s t) : f '' s = t := h.surj_on.image_eq_of_maps_to h.maps_to theorem bij_on.comp (hg : bij_on g t p) (hf : bij_on f s t) : bij_on (g ∘ f) s p := bij_on.mk (hg.maps_to.comp hf.maps_to) (hg.inj_on.comp hf.inj_on hf.maps_to) (hg.surj_on.comp hf.surj_on) lemma bijective_iff_bij_on_univ : bijective f ↔ bij_on f univ univ := iff.intro (λ h, let ⟨inj, surj⟩ := h in ⟨maps_to_univ f _, iff.mp injective_iff_inj_on_univ inj, iff.mp surjective_iff_surj_on_univ surj⟩) (λ h, let ⟨map, inj, surj⟩ := h in ⟨iff.mpr injective_iff_inj_on_univ inj, iff.mpr surjective_iff_surj_on_univ surj⟩) /-! ### left inverse -/ /-- `g` is a left inverse to `f` on `a` means that `g (f x) = x` for all `x ∈ a`. -/ @[reducible] def left_inv_on (f' : β → α) (f : α → β) (s : set α) : Prop := ∀ ⦃x⦄, x ∈ s → f' (f x) = x lemma left_inv_on.eq_on (h : left_inv_on f' f s) : eq_on (f' ∘ f) id s := h lemma left_inv_on.eq (h : left_inv_on f' f s) {x} (hx : x ∈ s) : f' (f x) = x := h hx lemma left_inv_on.congr_left (h₁ : left_inv_on f₁' f s) {t : set β} (h₁' : maps_to f s t) (heq : eq_on f₁' f₂' t) : left_inv_on f₂' f s := λ x hx, heq (h₁' hx) ▸ h₁ hx theorem left_inv_on.congr_right (h₁ : left_inv_on f₁' f₁ s) (heq : eq_on f₁ f₂ s) : left_inv_on f₁' f₂ s := λ x hx, heq hx ▸ h₁ hx theorem left_inv_on.inj_on (h : left_inv_on f₁' f s) : inj_on f s := λ x₁ x₂ h₁ h₂ heq, calc x₁ = f₁' (f x₁) : eq.symm $ h h₁ ... = f₁' (f x₂) : congr_arg f₁' heq ... = x₂ : h h₂ theorem left_inv_on.surj_on (h : left_inv_on f₁' f s) (hf : maps_to f s t) : surj_on f₁' t s := λ x hx, ⟨f x, hf hx, h hx⟩ theorem left_inv_on.comp (hf' : left_inv_on f' f s) (hg' : left_inv_on g' g t) (hf : maps_to f s t) : left_inv_on (f' ∘ g') (g ∘ f) s := λ x h, calc (f' ∘ g') ((g ∘ f) x) = f' (f x) : congr_arg f' (hg' (hf h)) ... = x : hf' h /-! ### Right inverse -/ /-- `g` is a right inverse to `f` on `b` if `f (g x) = x` for all `x ∈ b`. -/ @[reducible] def right_inv_on (f' : β → α) (f : α → β) (t : set β) : Prop := left_inv_on f f' t lemma right_inv_on.eq_on (h : right_inv_on f' f t) : eq_on (f ∘ f') id t := h lemma right_inv_on.eq (h : right_inv_on f' f t) {y} (hy : y ∈ t) : f (f' y) = y := h hy theorem right_inv_on.congr_left (h₁ : right_inv_on f₁' f t) (heq : eq_on f₁' f₂' t) : right_inv_on f₂' f t := h₁.congr_right heq theorem right_inv_on.congr_right (h₁ : right_inv_on f' f₁ t) (hg : maps_to f' t s) (heq : eq_on f₁ f₂ s) : right_inv_on f' f₂ t := left_inv_on.congr_left h₁ hg heq theorem right_inv_on.surj_on (hf : right_inv_on f' f t) (hf' : maps_to f' t s) : surj_on f s t := hf.surj_on hf' theorem right_inv_on.comp (hf : right_inv_on f' f t) (hg : right_inv_on g' g p) (g'pt : maps_to g' p t) : right_inv_on (f' ∘ g') (g ∘ f) p := hg.comp hf g'pt theorem inj_on.right_inv_on_of_left_inv_on (hf : inj_on f s) (hf' : left_inv_on f f' t) (h₁ : maps_to f s t) (h₂ : maps_to f' t s) : right_inv_on f f' s := λ x h, hf (h₂ $ h₁ h) h (hf' (h₁ h)) theorem eq_on_of_left_inv_of_right_inv (h₁ : left_inv_on f₁' f s) (h₂ : right_inv_on f₂' f t) (h : maps_to f₂' t s) : eq_on f₁' f₂' t := λ y hy, calc f₁' y = (f₁' ∘ f ∘ f₂') y : congr_arg f₁' (h₂ hy).symm ... = f₂' y : h₁ (h hy) theorem surj_on.left_inv_on_of_right_inv_on (hf : surj_on f s t) (hf' : right_inv_on f f' s) : left_inv_on f f' t := λ y hy, let ⟨x, hx, heq⟩ := hf hy in by rw [← heq, hf' hx] /-! ### Two-side inverses -/ /-- `g` is an inverse to `f` viewed as a map from `a` to `b` -/ @[reducible] def inv_on (g : β → α) (f : α → β) (s : set α) (t : set β) : Prop := left_inv_on g f s ∧ right_inv_on g f t lemma inv_on.symm (h : inv_on f' f s t) : inv_on f f' t s := ⟨h.right, h.left⟩ theorem inv_on.bij_on (h : inv_on f' f s t) (hf : maps_to f s t) (hf' : maps_to f' t s) : bij_on f s t := ⟨hf, h.left.inj_on, h.right.surj_on hf'⟩ /-! ### `inv_fun_on` is a left/right inverse -/ theorem inj_on.left_inv_on_inv_fun_on [nonempty α] (h : inj_on f s) : left_inv_on (inv_fun_on f s) f s := λ x hx, inv_fun_on_eq' h hx theorem surj_on.right_inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) : right_inv_on (inv_fun_on f s) f t := λ y hy, inv_fun_on_eq $ mem_image_iff_bex.1 $ h hy theorem bij_on.inv_on_inv_fun_on [nonempty α] (h : bij_on f s t) : inv_on (inv_fun_on f s) f s t := ⟨h.inj_on.left_inv_on_inv_fun_on, h.surj_on.right_inv_on_inv_fun_on⟩ theorem surj_on.inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) : inv_on (inv_fun_on f s) f (inv_fun_on f s '' t) t := begin refine ⟨_, h.right_inv_on_inv_fun_on⟩, rintros _ ⟨y, hy, rfl⟩, rw [h.right_inv_on_inv_fun_on hy] end theorem surj_on.maps_to_inv_fun_on [nonempty α] (h : surj_on f s t) : maps_to (inv_fun_on f s) t s := λ y hy, mem_preimage.2 $ inv_fun_on_mem $ mem_image_iff_bex.1 $ h hy theorem surj_on.bij_on_subset [nonempty α] (h : surj_on f s t) : bij_on f (inv_fun_on f s '' t) t := begin refine h.inv_on_inv_fun_on.bij_on _ (maps_to_image _ _), rintros _ ⟨y, hy, rfl⟩, rwa [mem_preimage, h.right_inv_on_inv_fun_on hy] end theorem surj_on_iff_exists_bij_on_subset : surj_on f s t ↔ ∃ s' ⊆ s, bij_on f s' t := begin split, { rcases eq_empty_or_nonempty t with rfl|ht, { exact λ _, ⟨∅, empty_subset _, bij_on_empty f⟩ }, { assume h, haveI : nonempty α := ⟨classical.some (h.comap_nonempty ht)⟩, exact ⟨_, h.maps_to_inv_fun_on.image_subset, h.bij_on_subset⟩ }}, { rintros ⟨s', hs', hfs'⟩, exact hfs'.surj_on.mono hs' (subset.refl _) } end end set /-! ### Piecewise defined function -/ namespace set variables {δ : α → Sort y} (s : set α) (f g : Πi, δ i) @[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : set α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (set.univ : set α))] : piecewise set.univ f g = f := by { ext i, simp [piecewise] } @[simp] lemma piecewise_insert_self {j : α} [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] variable [∀j, decidable (j ∈ s)] lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = function.update (s.piecewise f g) j (f j) := begin simp [piecewise], ext i, by_cases h : i = j, { rw h, simp }, { by_cases h' : i ∈ s; simp [h, h'] } end @[simp, priority 990] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := by simp [piecewise, hi] @[simp, priority 990] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := by simp [piecewise, hi] @[simp, priority 990] lemma piecewise_insert_of_ne {i j : α} (h : i ≠ j) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g i = s.piecewise f g i := by { simp [piecewise, h], congr } end set namespace function open set variables {f : α → β} {g : β → γ} {s : set α} lemma injective.inj_on (h : injective f) (s : set α) : s.inj_on f := λ _ _ _ _ heq, h heq lemma injective.comp_inj_on (hg : injective g) (hf : s.inj_on f) : s.inj_on (g ∘ f) := (hg.inj_on univ).comp hf (maps_to_univ _ _) lemma surjective.surj_on (hf : surjective f) (s : set β) : surj_on f univ s := (surjective_iff_surj_on_univ.1 hf).mono (subset.refl _) (subset_univ _) end function
32706da479d00b23f93371c4b6180a99dd2bfb93
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/set_theory/ordinal.lean
defcf542a2ac0d69b19bdb11de11b0146daaff6a
[ "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
58,136
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import set_theory.cardinal import order.conditionally_complete_lattice /-! # Ordinals Ordinals are defined as equivalences of well-ordered sets under order isomorphism. They are endowed with a total order, where an ordinal is smaller than another one if it embeds into it as an initial segment (or, equivalently, in any way). This total order is well founded. ## Main definitions * `initial_seg r s`: type of order embeddings of `r` into `s` for which the range is an initial segment (i.e., if `b` belongs to the range, then any `b' < b` also belongs to the range). It is denoted by `r ≼i s`. * `principal_seg r s`: Type of order embeddings of `r` into `s` for which the range is a principal segment, i.e., an interval of the form `(-∞, top)` for some element `top`. It is denoted by `r ≺i s`. * `ordinal`: the type of ordinals (in a given universe) * `ordinal.type r`: given a well-founded order `r`, this is the corresponding ordinal * `ordinal.typein r a`: given a well-founded order `r` on a type `α`, and `a : α`, the ordinal corresponding to all elements smaller than `a`. * `enum r o h`: given a well-order `r` on a type `α`, and an ordinal `o` strictly smaller than the ordinal corresponding to `r` (this is the assumption `h`), returns the `o`-th element of `α`. In other words, the elements of `α` can be enumerated using ordinals up to `type r`. * `ordinal.card o`: the cardinality of an ordinal `o`. * `ordinal.lift` lifts an ordinal in universe `u` to an ordinal in universe `max u v`. For a version registering additionally that this is an initial segment embedding, see `ordinal.lift.initial_seg`. For a version regiserting that it is a principal segment embedding if `u < v`, see `ordinal.lift.principal_seg`. * `ordinal.omega` is the first infinite ordinal. It is the order type of `ℕ`. * `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that every element of `o₁` is smaller than every element of `o₂`. The main properties of addition (and the other operations on ordinals) are stated and proved in `ordinal_arithmetic.lean`. Here, we only introduce it and prove its basic properties to deduce the fact that the order on ordinals is total (and well founded). * `succ o` is the successor of the ordinal `o`. * `ordinal.min`: the minimal element of a nonempty indexed family of ordinals * `ordinal.omin` : the minimal element of a nonempty set of ordinals * `cardinal.ord c`: when `c` is a cardinal, `ord c` is the smallest ordinal with this cardinality. It is the canonical way to represent a cardinal with an ordinal. A conditionally complete linear order with bot structure is registered on ordinals, where `⊥` is `0`, the ordinal corresponding to the empty type, and `Inf` is `ordinal.omin` for nonempty sets and `0` for the empty set by convention. ## Notations * `r ≼i s`: the type of initial segment embeddings of `r` into `s`. * `r ≺i s`: the type of principal segment embeddings of `r` into `s`. * `ω` is a notation for the first infinite ordinal in the locale `ordinal`. -/ noncomputable theory open function cardinal set equiv open_locale classical cardinal universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} /-! ### Initial segments Order embeddings whose range is an initial segment of `s` (i.e., if `b` belongs to the range, then any `b' < b` also belongs to the range). The type of these embeddings from `r` to `s` is called `initial_seg r s`, and denoted by `r ≼i s`. -/ /-- If `r` is a relation on `α` and `s` in a relation on `β`, then `f : r ≼i s` is an order embedding whose range is an initial segment. That is, whenever `b < f a` in `β` then `b` is in the range of `f`. -/ @[nolint has_inhabited_instance] structure initial_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ↪r s := (init : ∀ a b, s b (to_rel_embedding a) → ∃ a', to_rel_embedding a' = b) local infix ` ≼i `:25 := initial_seg namespace initial_seg instance : has_coe (r ≼i s) (r ↪r s) := ⟨initial_seg.to_rel_embedding⟩ instance : has_coe_to_fun (r ≼i s) := ⟨λ _, α → β, λ f x, (f : r ↪r s) x⟩ @[simp] theorem coe_fn_mk (f : r ↪r s) (o) : (@initial_seg.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_rel_embedding (f : r ≼i s) : (f.to_rel_embedding : α → β) = f := rfl @[simp] theorem coe_coe_fn (f : r ≼i s) : ((f : r ↪r s) : α → β) = f := rfl theorem init' (f : r ≼i s) {a : α} {b : β} : s b (f a) → ∃ a', f a' = b := f.init _ _ theorem init_iff (f : r ≼i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a := ⟨λ h, let ⟨a', e⟩ := f.init' h in ⟨a', e, (f : r ↪r s).map_rel_iff.1 (e.symm ▸ h)⟩, λ ⟨a', e, h⟩, e ▸ (f : r ↪r s).map_rel_iff.2 h⟩ /-- An order isomorphism is an initial segment -/ def of_iso (f : r ≃r s) : r ≼i s := ⟨f, λ a b h, ⟨f.symm b, rel_iso.apply_symm_apply f _⟩⟩ /-- The identity function shows that `≼i` is reflexive -/ @[refl] protected def refl (r : α → α → Prop) : r ≼i r := ⟨rel_embedding.refl _, λ a b h, ⟨_, rfl⟩⟩ /-- Composition of functions shows that `≼i` is transitive -/ @[trans] protected def trans (f : r ≼i s) (g : s ≼i t) : r ≼i t := ⟨f.1.trans g.1, λ a c h, begin simp at h ⊢, rcases g.2 _ _ h with ⟨b, rfl⟩, have h := g.1.map_rel_iff.1 h, rcases f.2 _ _ h with ⟨a', rfl⟩, exact ⟨a', rfl⟩ end⟩ @[simp] theorem refl_apply (x : α) : initial_seg.refl r x = x := rfl @[simp] theorem trans_apply (f : r ≼i s) (g : s ≼i t) (a : α) : (f.trans g) a = g (f a) := rfl theorem unique_of_extensional [is_extensional β s] : well_founded r → subsingleton (r ≼i s) | ⟨h⟩ := ⟨λ f g, begin suffices : (f : α → β) = g, { cases f, cases g, congr, exact rel_embedding.coe_fn_injective this }, funext a, have := h a, induction this with a H IH, refine @is_extensional.ext _ s _ _ _ (λ x, ⟨λ h, _, λ h, _⟩), { rcases f.init_iff.1 h with ⟨y, rfl, h'⟩, rw IH _ h', exact (g : r ↪r s).map_rel_iff.2 h' }, { rcases g.init_iff.1 h with ⟨y, rfl, h'⟩, rw ← IH _ h', exact (f : r ↪r s).map_rel_iff.2 h' } end⟩ instance [is_well_order β s] : subsingleton (r ≼i s) := ⟨λ a, @subsingleton.elim _ (unique_of_extensional (@rel_embedding.well_founded _ _ r s a is_well_order.wf)) a⟩ protected theorem eq [is_well_order β s] (f g : r ≼i s) (a) : f a = g a := by rw subsingleton.elim f g theorem antisymm.aux [is_well_order α r] (f : r ≼i s) (g : s ≼i r) : left_inverse g f := initial_seg.eq (f.trans g) (initial_seg.refl _) /-- If we have order embeddings between `α` and `β` whose images are initial segments, and `β` is a well-order then `α` and `β` are order-isomorphic. -/ def antisymm [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : r ≃r s := by haveI := f.to_rel_embedding.is_well_order; exact ⟨⟨f, g, antisymm.aux f g, antisymm.aux g f⟩, f.map_rel_iff'⟩ @[simp] theorem antisymm_to_fun [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : (antisymm f g : α → β) = f := rfl @[simp] theorem antisymm_symm [is_well_order α r] [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : (antisymm f g).symm = antisymm g f := rel_iso.coe_fn_injective rfl theorem eq_or_principal [is_well_order β s] (f : r ≼i s) : surjective f ∨ ∃ b, ∀ x, s x b ↔ ∃ y, f y = x := or_iff_not_imp_right.2 $ λ h b, acc.rec_on (is_well_order.wf.apply b : acc s b) $ λ x H IH, not_forall_not.1 $ λ hn, h ⟨x, λ y, ⟨(IH _), λ ⟨a, e⟩, by rw ← e; exact (trichotomous _ _).resolve_right (not_or (hn a) (λ hl, not_exists.2 hn (f.init' hl)))⟩⟩ /-- Restrict the codomain of an initial segment -/ def cod_restrict (p : set β) (f : r ≼i s) (H : ∀ a, f a ∈ p) : r ≼i subrel s p := ⟨rel_embedding.cod_restrict p f H, λ a ⟨b, m⟩ (h : s b (f a)), let ⟨a', e⟩ := f.init' h in ⟨a', by clear _let_match; subst e; refl⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r ≼i s) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl /-- Initial segment embedding of an order `r` into the disjoint union of `r` and `s`. -/ def le_add (r : α → α → Prop) (s : β → β → Prop) : r ≼i sum.lex r s := ⟨⟨⟨sum.inl, λ _ _, sum.inl.inj⟩, λ a b, sum.lex_inl_inl⟩, λ a b, by cases b; [exact λ _, ⟨_, rfl⟩, exact false.elim ∘ sum.lex_inr_inl]⟩ @[simp] theorem le_add_apply (r : α → α → Prop) (s : β → β → Prop) (a) : le_add r s a = sum.inl a := rfl end initial_seg /-! ### Principal segments Order embeddings whose range is a principal segment of `s` (i.e., an interval of the form `(-∞, top)` for some element `top` of `β`). The type of these embeddings from `r` to `s` is called `principal_seg r s`, and denoted by `r ≺i s`. Principal segments are in particular initial segments. -/ /-- If `r` is a relation on `α` and `s` in a relation on `β`, then `f : r ≺i s` is an order embedding whose range is an open interval `(-∞, top)` for some element `top` of `β`. Such order embeddings are called principal segments -/ @[nolint has_inhabited_instance] structure principal_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ↪r s := (top : β) (down : ∀ b, s b top ↔ ∃ a, to_rel_embedding a = b) local infix ` ≺i `:25 := principal_seg namespace principal_seg instance : has_coe (r ≺i s) (r ↪r s) := ⟨principal_seg.to_rel_embedding⟩ instance : has_coe_to_fun (r ≺i s) := ⟨λ _, α → β, λ f, f⟩ @[simp] theorem coe_fn_mk (f : r ↪r s) (t o) : (@principal_seg.mk _ _ r s f t o : α → β) = f := rfl @[simp] theorem coe_fn_to_rel_embedding (f : r ≺i s) : (f.to_rel_embedding : α → β) = f := rfl @[simp] theorem coe_coe_fn (f : r ≺i s) : ((f : r ↪r s) : α → β) = f := rfl theorem down' (f : r ≺i s) {b : β} : s b f.top ↔ ∃ a, f a = b := f.down _ theorem lt_top (f : r ≺i s) (a : α) : s (f a) f.top := f.down'.2 ⟨_, rfl⟩ theorem init [is_trans β s] (f : r ≺i s) {a : α} {b : β} (h : s b (f a)) : ∃ a', f a' = b := f.down'.1 $ trans h $ f.lt_top _ /-- A principal segment is in particular an initial segment. -/ instance has_coe_initial_seg [is_trans β s] : has_coe (r ≺i s) (r ≼i s) := ⟨λ f, ⟨f.to_rel_embedding, λ a b, f.init⟩⟩ theorem coe_coe_fn' [is_trans β s] (f : r ≺i s) : ((f : r ≼i s) : α → β) = f := rfl theorem init_iff [is_trans β s] (f : r ≺i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a := @initial_seg.init_iff α β r s f a b theorem irrefl (r : α → α → Prop) [is_well_order α r] (f : r ≺i r) : false := begin have := f.lt_top f.top, rw [show f f.top = f.top, from initial_seg.eq ↑f (initial_seg.refl r) f.top] at this, exact irrefl _ this end /-- Composition of a principal segment with an initial segment, as a principal segment -/ def lt_le (f : r ≺i s) (g : s ≼i t) : r ≺i t := ⟨@rel_embedding.trans _ _ _ r s t f g, g f.top, λ a, by simp only [g.init_iff, f.down', exists_and_distrib_left.symm, exists_swap, rel_embedding.trans_apply, exists_eq_right']; refl⟩ @[simp] theorem lt_le_apply (f : r ≺i s) (g : s ≼i t) (a : α) : (f.lt_le g) a = g (f a) := rel_embedding.trans_apply _ _ _ @[simp] theorem lt_le_top (f : r ≺i s) (g : s ≼i t) : (f.lt_le g).top = g f.top := rfl /-- Composition of two principal segments as a principal segment -/ @[trans] protected def trans [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : r ≺i t := lt_le f g @[simp] theorem trans_apply [is_trans γ t] (f : r ≺i s) (g : s ≺i t) (a : α) : (f.trans g) a = g (f a) := lt_le_apply _ _ _ @[simp] theorem trans_top [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : (f.trans g).top = g f.top := rfl /-- Composition of an order isomorphism with a principal segment, as a principal segment -/ def equiv_lt (f : r ≃r s) (g : s ≺i t) : r ≺i t := ⟨@rel_embedding.trans _ _ _ r s t f g, g.top, λ c, suffices (∃ (a : β), g a = c) ↔ ∃ (a : α), g (f a) = c, by simpa [g.down], ⟨λ ⟨b, h⟩, ⟨f.symm b, by simp only [h, rel_iso.apply_symm_apply, rel_iso.coe_coe_fn]⟩, λ ⟨a, h⟩, ⟨f a, h⟩⟩⟩ /-- Composition of a principal segment with an order isomorphism, as a principal segment -/ def lt_equiv {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} (f : principal_seg r s) (g : s ≃r t) : principal_seg r t := ⟨@rel_embedding.trans _ _ _ r s t f g, g f.top, begin intro x, rw [← g.apply_symm_apply x, g.map_rel_iff, f.down', exists_congr], intro y, exact ⟨congr_arg g, λ h, g.to_equiv.bijective.1 h⟩ end⟩ @[simp] theorem equiv_lt_apply (f : r ≃r s) (g : s ≺i t) (a : α) : (equiv_lt f g) a = g (f a) := rel_embedding.trans_apply _ _ _ @[simp] theorem equiv_lt_top (f : r ≃r s) (g : s ≺i t) : (equiv_lt f g).top = g.top := rfl /-- Given a well order `s`, there is a most one principal segment embedding of `r` into `s`. -/ instance [is_well_order β s] : subsingleton (r ≺i s) := ⟨λ f g, begin have ef : (f : α → β) = g, { show ((f : r ≼i s) : α → β) = g, rw @subsingleton.elim _ _ (f : r ≼i s) g, refl }, have et : f.top = g.top, { refine @is_extensional.ext _ s _ _ _ (λ x, _), simp only [f.down, g.down, ef, coe_fn_to_rel_embedding] }, cases f, cases g, have := rel_embedding.coe_fn_injective ef; congr' end⟩ theorem top_eq [is_well_order γ t] (e : r ≃r s) (f : r ≺i t) (g : s ≺i t) : f.top = g.top := by rw subsingleton.elim f (principal_seg.equiv_lt e g); refl lemma top_lt_top {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} [is_well_order γ t] (f : principal_seg r s) (g : principal_seg s t) (h : principal_seg r t) : t h.top g.top := by { rw [subsingleton.elim h (f.trans g)], apply principal_seg.lt_top } /-- Any element of a well order yields a principal segment -/ def of_element {α : Type*} (r : α → α → Prop) (a : α) : subrel r {b | r b a} ≺i r := ⟨subrel.rel_embedding _ _, a, λ b, ⟨λ h, ⟨⟨_, h⟩, rfl⟩, λ ⟨⟨_, h⟩, rfl⟩, h⟩⟩ @[simp] theorem of_element_apply {α : Type*} (r : α → α → Prop) (a : α) (b) : of_element r a b = b.1 := rfl @[simp] theorem of_element_top {α : Type*} (r : α → α → Prop) (a : α) : (of_element r a).top = a := rfl /-- Restrict the codomain of a principal segment -/ def cod_restrict (p : set β) (f : r ≺i s) (H : ∀ a, f a ∈ p) (H₂ : f.top ∈ p) : r ≺i subrel s p := ⟨rel_embedding.cod_restrict p f H, ⟨f.top, H₂⟩, λ ⟨b, h⟩, f.down'.trans $ exists_congr $ λ a, show (⟨f a, H a⟩ : p).1 = _ ↔ _, from ⟨subtype.eq, congr_arg _⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r ≺i s) (H H₂ a) : cod_restrict p f H H₂ a = ⟨f a, H a⟩ := rfl @[simp] theorem cod_restrict_top (p) (f : r ≺i s) (H H₂) : (cod_restrict p f H H₂).top = ⟨f.top, H₂⟩ := rfl end principal_seg /-! ### Properties of initial and principal segments -/ /-- To an initial segment taking values in a well order, one can associate either a principal segment (if the range is not everything, hence one can take as top the minimum of the complement of the range) or an order isomorphism (if the range is everything). -/ def initial_seg.lt_or_eq [is_well_order β s] (f : r ≼i s) : (r ≺i s) ⊕ (r ≃r s) := if h : surjective f then sum.inr (rel_iso.of_surjective f h) else have h' : _, from (initial_seg.eq_or_principal f).resolve_left h, sum.inl ⟨f, classical.some h', classical.some_spec h'⟩ theorem initial_seg.lt_or_eq_apply_left [is_well_order β s] (f : r ≼i s) (g : r ≺i s) (a : α) : g a = f a := @initial_seg.eq α β r s _ g f a theorem initial_seg.lt_or_eq_apply_right [is_well_order β s] (f : r ≼i s) (g : r ≃r s) (a : α) : g a = f a := initial_seg.eq (initial_seg.of_iso g) f a /-- Composition of an initial segment taking values in a well order and a principal segment. -/ def initial_seg.le_lt [is_well_order β s] [is_trans γ t] (f : r ≼i s) (g : s ≺i t) : r ≺i t := match f.lt_or_eq with | sum.inl f' := f'.trans g | sum.inr f' := principal_seg.equiv_lt f' g end @[simp] theorem initial_seg.le_lt_apply [is_well_order β s] [is_trans γ t] (f : r ≼i s) (g : s ≺i t) (a : α) : (f.le_lt g) a = g (f a) := begin delta initial_seg.le_lt, cases h : f.lt_or_eq with f' f', { simp only [principal_seg.trans_apply, f.lt_or_eq_apply_left] }, { simp only [principal_seg.equiv_lt_apply, f.lt_or_eq_apply_right] } end namespace rel_embedding /-- Given an order embedding into a well order, collapse the order embedding by filling the gaps, to obtain an initial segment. Here, we construct the collapsed order embedding pointwise, but the proof of the fact that it is an initial segment will be given in `collapse`. -/ def collapse_F [is_well_order β s] (f : r ↪r s) : Π a, {b // ¬ s (f a) b} := (rel_embedding.well_founded f $ is_well_order.wf).fix $ λ a IH, begin let S := {b | ∀ a h, s (IH a h).1 b}, have : f a ∈ S, from λ a' h, ((trichotomous _ _) .resolve_left $ λ h', (IH a' h).2 $ trans (f.map_rel_iff.2 h) h') .resolve_left $ λ h', (IH a' h).2 $ h' ▸ f.map_rel_iff.2 h, exact ⟨is_well_order.wf.min S ⟨_, this⟩, is_well_order.wf.not_lt_min _ _ this⟩ end theorem collapse_F.lt [is_well_order β s] (f : r ↪r s) {a : α} : ∀ {a'}, r a' a → s (collapse_F f a').1 (collapse_F f a).1 := show (collapse_F f a).1 ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, begin unfold collapse_F, rw well_founded.fix_eq, apply well_founded.min_mem _ _ end theorem collapse_F.not_lt [is_well_order β s] (f : r ↪r s) (a : α) {b} (h : ∀ a' (h : r a' a), s (collapse_F f a').1 b) : ¬ s b (collapse_F f a).1 := begin unfold collapse_F, rw well_founded.fix_eq, exact well_founded.not_lt_min _ _ _ (show b ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, from h) end /-- Construct an initial segment from an order embedding into a well order, by collapsing it to fill the gaps. -/ def collapse [is_well_order β s] (f : r ↪r s) : r ≼i s := by haveI := rel_embedding.is_well_order f; exact ⟨rel_embedding.of_monotone (λ a, (collapse_F f a).1) (λ a b, collapse_F.lt f), λ a b, acc.rec_on (is_well_order.wf.apply b : acc s b) (λ b H IH a h, begin let S := {a | ¬ s (collapse_F f a).1 b}, have : S.nonempty := ⟨_, asymm h⟩, existsi (is_well_order.wf : well_founded r).min S this, refine ((@trichotomous _ s _ _ _).resolve_left _).resolve_right _, { exact (is_well_order.wf : well_founded r).min_mem S this }, { refine collapse_F.not_lt f _ (λ a' h', _), by_contradiction hn, exact is_well_order.wf.not_lt_min S this hn h' } end) a⟩ theorem collapse_apply [is_well_order β s] (f : r ↪r s) (a) : collapse f a = (collapse_F f a).1 := rfl end rel_embedding /-! ### Well order on an arbitrary type -/ section well_ordering_thm parameter {σ : Type u} open function theorem nonempty_embedding_to_cardinal : nonempty (σ ↪ cardinal.{u}) := embedding.total.resolve_left $ λ ⟨⟨f, hf⟩⟩, let g : σ → cardinal.{u} := inv_fun f in let ⟨x, (hx : g x = 2 ^ sum g)⟩ := inv_fun_surjective hf (2 ^ sum g) in have g x ≤ sum g, from le_sum.{u u} g x, not_le_of_gt (by rw hx; exact cantor _) this /-- An embedding of any type to the set of cardinals. -/ def embedding_to_cardinal : σ ↪ cardinal.{u} := classical.choice nonempty_embedding_to_cardinal /-- Any type can be endowed with a well order, obtained by pulling back the well order over cardinals by some embedding. -/ def well_ordering_rel : σ → σ → Prop := embedding_to_cardinal ⁻¹'o (<) instance well_ordering_rel.is_well_order : is_well_order σ well_ordering_rel := (rel_embedding.preimage _ _).is_well_order end well_ordering_thm /-! ### Definition of ordinals -/ /-- Bundled structure registering a well order on a type. Ordinals will be defined as a quotient of this type. -/ structure Well_order : Type (u+1) := (α : Type u) (r : α → α → Prop) (wo : is_well_order α r) attribute [instance] Well_order.wo namespace Well_order instance : inhabited Well_order := ⟨⟨pempty, _, empty_relation.is_well_order⟩⟩ end Well_order /-- Equivalence relation on well orders on arbitrary types in universe `u`, given by order isomorphism. -/ instance ordinal.is_equivalent : setoid Well_order := { r := λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≃r s), iseqv := ⟨λ⟨α, r, _⟩, ⟨rel_iso.refl _⟩, λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, ⟨e.symm⟩, λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `ordinal.{u}` is the type of well orders in `Type u`, up to order isomorphism. -/ def ordinal : Type (u + 1) := quotient ordinal.is_equivalent namespace ordinal /-- The order type of a well order is an ordinal. -/ def type (r : α → α → Prop) [wo : is_well_order α r] : ordinal := ⟦⟨α, r, wo⟩⟧ /-- The order type of an element inside a well order. For the embedding as a principal segment, see `typein.principal_seg`. -/ def typein (r : α → α → Prop) [is_well_order α r] (a : α) : ordinal := type (subrel r {b | r b a}) theorem type_def (r : α → α → Prop) [wo : is_well_order α r] : @eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl @[simp] theorem type_def' (r : α → α → Prop) [is_well_order α r] {wo} : @eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl theorem type_eq {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r = type s ↔ nonempty (r ≃r s) := quotient.eq @[simp] lemma type_out (o : ordinal) : type o.out.r = o := by { refine eq.trans _ (by rw [←quotient.out_eq o]), cases quotient.out o, refl } @[elab_as_eliminator] theorem induction_on {C : ordinal → Prop} (o : ordinal) (H : ∀ α r [is_well_order α r], by exactI C (type r)) : C o := quot.induction_on o $ λ ⟨α, r, wo⟩, @H α r wo /-! ### The order on ordinals -/ /-- Ordinal less-equal is defined such that well orders `r` and `s` satisfy `type r ≤ type s` if there exists a function embedding `r` as an initial segment of `s`. -/ protected def le (a b : ordinal) : Prop := quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≼i s)) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, propext ⟨ λ ⟨h⟩, ⟨(initial_seg.of_iso f.symm).trans $ h.trans (initial_seg.of_iso g)⟩, λ ⟨h⟩, ⟨(initial_seg.of_iso f).trans $ h.trans (initial_seg.of_iso g.symm)⟩⟩ instance : has_le ordinal := ⟨ordinal.le⟩ theorem type_le {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r ≤ type s ↔ nonempty (r ≼i s) := iff.rfl theorem type_le' {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r ≤ type s ↔ nonempty (r ↪r s) := ⟨λ ⟨f⟩, ⟨f⟩, λ ⟨f⟩, ⟨f.collapse⟩⟩ /-- Ordinal less-than is defined such that well orders `r` and `s` satisfy `type r < type s` if there exists a function embedding `r` as a principal segment of `s`. -/ def lt (a b : ordinal) : Prop := quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≺i s)) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, by exactI propext ⟨ λ ⟨h⟩, ⟨principal_seg.equiv_lt f.symm $ h.lt_le (initial_seg.of_iso g)⟩, λ ⟨h⟩, ⟨principal_seg.equiv_lt f $ h.lt_le (initial_seg.of_iso g.symm)⟩⟩ instance : has_lt ordinal := ⟨ordinal.lt⟩ @[simp] theorem type_lt {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r < type s ↔ nonempty (r ≺i s) := iff.rfl instance : partial_order ordinal := { le := (≤), lt := (<), le_refl := quot.ind $ by exact λ ⟨α, r, wo⟩, ⟨initial_seg.refl _⟩, le_trans := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩ ⟨g⟩, ⟨f.trans g⟩, lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, by exactI ⟨λ ⟨f⟩, ⟨⟨f⟩, λ ⟨g⟩, (f.lt_le g).irrefl _⟩, λ ⟨⟨f⟩, h⟩, sum.rec_on f.lt_or_eq (λ g, ⟨g⟩) (λ g, (h ⟨initial_seg.of_iso g.symm⟩).elim)⟩, le_antisymm := λ x b, show x ≤ b → b ≤ x → x = b, from quotient.induction_on₂ x b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨h₁⟩ ⟨h₂⟩, by exactI quot.sound ⟨initial_seg.antisymm h₁ h₂⟩ } /-- Given two ordinals `α ≤ β`, then `initial_seg_out α β` is the initial segment embedding of `α` to `β`, as map from a model type for `α` to a model type for `β`. -/ def initial_seg_out {α β : ordinal} (h : α ≤ β) : initial_seg α.out.r β.out.r := begin rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h, cases quotient.out α, cases quotient.out β, exact classical.choice end /-- Given two ordinals `α < β`, then `principal_seg_out α β` is the principal segment embedding of `α` to `β`, as map from a model type for `α` to a model type for `β`. -/ def principal_seg_out {α β : ordinal} (h : α < β) : principal_seg α.out.r β.out.r := begin rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h, cases quotient.out α, cases quotient.out β, exact classical.choice end /-- Given two ordinals `α = β`, then `rel_iso_out α β` is the order isomorphism between two model types for `α` and `β`. -/ def rel_iso_out {α β : ordinal} (h : α = β) : α.out.r ≃r β.out.r := begin rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h, cases quotient.out α, cases quotient.out β, exact classical.choice ∘ quotient.exact end theorem typein_lt_type (r : α → α → Prop) [is_well_order α r] (a : α) : typein r a < type r := ⟨principal_seg.of_element _ _⟩ @[simp] theorem typein_top {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≺i s) : typein s f.top = type r := eq.symm $ quot.sound ⟨rel_iso.of_surjective (rel_embedding.cod_restrict _ f f.lt_top) (λ ⟨a, h⟩, by rcases f.down'.1 h with ⟨b, rfl⟩; exact ⟨b, rfl⟩)⟩ @[simp] theorem typein_apply {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≼i s) (a : α) : ordinal.typein s (f a) = ordinal.typein r a := eq.symm $ quotient.sound ⟨rel_iso.of_surjective (rel_embedding.cod_restrict _ ((subrel.rel_embedding _ _).trans f) (λ ⟨x, h⟩, by rw [rel_embedding.trans_apply]; exact f.to_rel_embedding.map_rel_iff.2 h)) (λ ⟨y, h⟩, by rcases f.init' h with ⟨a, rfl⟩; exact ⟨⟨a, f.to_rel_embedding.map_rel_iff.1 h⟩, subtype.eq $ rel_embedding.trans_apply _ _ _⟩)⟩ @[simp] theorem typein_lt_typein (r : α → α → Prop) [is_well_order α r] {a b : α} : typein r a < typein r b ↔ r a b := ⟨λ ⟨f⟩, begin have : f.top.1 = a, { let f' := principal_seg.of_element r a, let g' := f.trans (principal_seg.of_element r b), have : g'.top = f'.top, {rw subsingleton.elim f' g'}, exact this }, rw ← this, exact f.top.2 end, λ h, ⟨principal_seg.cod_restrict _ (principal_seg.of_element r a) (λ x, @trans _ r _ _ _ _ x.2 h) h⟩⟩ theorem typein_surj (r : α → α → Prop) [is_well_order α r] {o} (h : o < type r) : ∃ a, typein r a = o := induction_on o (λ β s _ ⟨f⟩, by exactI ⟨f.top, typein_top _⟩) h lemma typein_injective (r : α → α → Prop) [is_well_order α r] : injective (typein r) := injective_of_increasing r (<) (typein r) (λ x y, (typein_lt_typein r).2) theorem typein_inj (r : α → α → Prop) [is_well_order α r] {a b} : typein r a = typein r b ↔ a = b := injective.eq_iff (typein_injective r) /-! ### Enumerating elements in a well-order with ordinals. -/ /-- `enum r o h` is the `o`-th element of `α` ordered by `r`. That is, `enum` maps an initial segment of the ordinals, those less than the order type of `r`, to the elements of `α`. -/ def enum (r : α → α → Prop) [is_well_order α r] (o) : o < type r → α := quot.rec_on o (λ ⟨β, s, _⟩ h, (classical.choice h).top) $ λ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨h⟩, begin resetI, refine funext (λ (H₂ : type t < type r), _), have H₁ : type s < type r, {rwa type_eq.2 ⟨h⟩}, have : ∀ {o e} (H : o < type r), @@eq.rec (λ (o : ordinal), o < type r → α) (λ (h : type s < type r), (classical.choice h).top) e H = (classical.choice H₁).top, {intros, subst e}, exact (this H₂).trans (principal_seg.top_eq h (classical.choice H₁) (classical.choice H₂)) end theorem enum_type {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : s ≺i r) {h : type s < type r} : enum r (type s) h = f.top := principal_seg.top_eq (rel_iso.refl _) _ _ @[simp] theorem enum_typein (r : α → α → Prop) [is_well_order α r] (a : α) {h : typein r a < type r} : enum r (typein r a) h = a := enum_type (principal_seg.of_element r a) @[simp] theorem typein_enum (r : α → α → Prop) [is_well_order α r] {o} (h : o < type r) : typein r (enum r o h) = o := let ⟨a, e⟩ := typein_surj r h in by clear _let_match; subst e; rw enum_typein /-- A well order `r` is order isomorphic to the set of ordinals strictly smaller than the ordinal version of `r`. -/ def typein_iso (r : α → α → Prop) [is_well_order α r] : r ≃r subrel (<) (< type r) := ⟨⟨λ x, ⟨typein r x, typein_lt_type r x⟩, λ x, enum r x.1 x.2, λ y, enum_typein r y, λ ⟨y, hy⟩, subtype.eq (typein_enum r hy)⟩, λ a b, (typein_lt_typein r)⟩ theorem enum_lt {r : α → α → Prop} [is_well_order α r] {o₁ o₂ : ordinal} (h₁ : o₁ < type r) (h₂ : o₂ < type r) : r (enum r o₁ h₁) (enum r o₂ h₂) ↔ o₁ < o₂ := by rw [← typein_lt_typein r, typein_enum, typein_enum] lemma rel_iso_enum' {α β : Type u} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≃r s) (o : ordinal) : ∀(hr : o < type r) (hs : o < type s), f (enum r o hr) = enum s o hs := begin refine induction_on o _, rintros γ t wo ⟨g⟩ ⟨h⟩, resetI, rw [enum_type g, enum_type (principal_seg.lt_equiv g f)], refl end lemma rel_iso_enum {α β : Type u} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≃r s) (o : ordinal) (hr : o < type r) : f (enum r o hr) = enum s o (by {convert hr using 1, apply quotient.sound, exact ⟨f.symm⟩ }) := rel_iso_enum' _ _ _ _ theorem wf : @well_founded ordinal (<) := ⟨λ a, induction_on a $ λ α r wo, by exactI suffices ∀ a, acc (<) (typein r a), from ⟨_, λ o h, let ⟨a, e⟩ := typein_surj r h in e ▸ this a⟩, λ a, acc.rec_on (wo.wf.apply a) $ λ x H IH, ⟨_, λ o h, begin rcases typein_surj r (lt_trans h (typein_lt_type r _)) with ⟨b, rfl⟩, exact IH _ ((typein_lt_typein r).1 h) end⟩⟩ instance : has_well_founded ordinal := ⟨(<), wf⟩ /-- Reformulation of well founded induction on ordinals as a lemma that works with the `induction` tactic, as in `induction i using ordinal.induction with i IH`. -/ lemma induction {p : ordinal.{u} → Prop} (i : ordinal.{u}) (h : ∀ j, (∀ k, k < j → p k) → p j) : p i := ordinal.wf.induction i h /-- Principal segment version of the `typein` function, embedding a well order into ordinals as a principal segment. -/ def typein.principal_seg {α : Type u} (r : α → α → Prop) [is_well_order α r] : @principal_seg α ordinal.{u} r (<) := ⟨rel_embedding.of_monotone (typein r) (λ a b, (typein_lt_typein r).2), type r, λ b, ⟨λ h, ⟨enum r _ h, typein_enum r h⟩, λ ⟨a, e⟩, e ▸ typein_lt_type _ _⟩⟩ @[simp] theorem typein.principal_seg_coe (r : α → α → Prop) [is_well_order α r] : (typein.principal_seg r : α → ordinal) = typein r := rfl /-! ### Cardinality of ordinals -/ /-- The cardinal of an ordinal is the cardinal of any set with that order type. -/ def card (o : ordinal) : cardinal := quot.lift_on o (λ ⟨α, r, _⟩, #α) $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, quotient.sound ⟨e.to_equiv⟩ @[simp] theorem card_type (r : α → α → Prop) [is_well_order α r] : card (type r) = #α := rfl lemma card_typein {r : α → α → Prop} [wo : is_well_order α r] (x : α) : #{y // r y x} = (typein r x).card := rfl theorem card_le_card {o₁ o₂ : ordinal} : o₁ ≤ o₂ → card o₁ ≤ card o₂ := induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _ ⟨⟨⟨f, _⟩, _⟩⟩, ⟨f⟩ instance : has_zero ordinal := ⟨⟦⟨pempty, empty_relation, by apply_instance⟩⟧⟩ instance : inhabited ordinal := ⟨0⟩ theorem zero_eq_type_empty : 0 = @type empty empty_relation _ := quotient.sound ⟨⟨empty_equiv_pempty.symm, λ _ _, iff.rfl⟩⟩ @[simp] theorem card_zero : card 0 = 0 := rfl protected theorem zero_le (o : ordinal) : 0 ≤ o := induction_on o $ λ α r _, ⟨⟨⟨embedding.of_is_empty, is_empty_elim⟩, is_empty_elim⟩⟩ @[simp] protected theorem le_zero {o : ordinal} : o ≤ 0 ↔ o = 0 := by simp only [le_antisymm_iff, ordinal.zero_le, and_true] protected theorem pos_iff_ne_zero {o : ordinal} : 0 < o ↔ o ≠ 0 := by simp only [lt_iff_le_and_ne, ordinal.zero_le, true_and, ne.def, eq_comm] instance : has_one ordinal := ⟨⟦⟨punit, empty_relation, by apply_instance⟩⟧⟩ theorem one_eq_type_unit : 1 = @type unit empty_relation _ := quotient.sound ⟨⟨punit_equiv_punit, λ _ _, iff.rfl⟩⟩ @[simp] theorem card_one : card 1 = 1 := rfl /-! ### Lifting ordinals to a higher universe -/ /-- The universe lift operation for ordinals, which embeds `ordinal.{u}` as a proper initial segment of `ordinal.{v}` for `v > u`. For the initial segment version, see `lift.initial_seg`. -/ def lift (o : ordinal.{v}) : ordinal.{max v u} := quotient.lift_on o (λ ⟨α, r, wo⟩, @type _ _ (@rel_embedding.is_well_order _ _ (@equiv.ulift.{u} α ⁻¹'o r) r (rel_iso.preimage equiv.ulift.{u} r) wo)) $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨f⟩, quot.sound ⟨(rel_iso.preimage equiv.ulift r).trans $ f.trans (rel_iso.preimage equiv.ulift s).symm⟩ theorem lift_type {α} (r : α → α → Prop) [is_well_order α r] : ∃ wo', lift (type r) = @type _ (@equiv.ulift.{v} α ⁻¹'o r) wo' := ⟨_, rfl⟩ theorem lift_umax : lift.{(max u v) u} = lift.{v u} := funext $ λ a, induction_on a $ λ α r _, quotient.sound ⟨(rel_iso.preimage equiv.ulift r).trans (rel_iso.preimage equiv.ulift r).symm⟩ theorem lift_id' (a : ordinal) : lift a = a := induction_on a $ λ α r _, quotient.sound ⟨rel_iso.preimage equiv.ulift r⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : ordinal) : lift.{w} (lift.{v} a) = lift.{(max v w)} a := induction_on a $ λ α r _, quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans $ (rel_iso.preimage equiv.ulift _).trans (rel_iso.preimage equiv.ulift _).symm⟩ theorem lift_type_le {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{(max v w)} (type r) ≤ lift.{(max u w)} (type s) ↔ nonempty (r ≼i s) := ⟨λ ⟨f⟩, ⟨(initial_seg.of_iso (rel_iso.preimage equiv.ulift r).symm).trans $ f.trans (initial_seg.of_iso (rel_iso.preimage equiv.ulift s))⟩, λ ⟨f⟩, ⟨(initial_seg.of_iso (rel_iso.preimage equiv.ulift r)).trans $ f.trans (initial_seg.of_iso (rel_iso.preimage equiv.ulift s).symm)⟩⟩ theorem lift_type_eq {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{(max v w)} (type r) = lift.{(max u w)} (type s) ↔ nonempty (r ≃r s) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨(rel_iso.preimage equiv.ulift r).symm.trans $ f.trans (rel_iso.preimage equiv.ulift s)⟩, λ ⟨f⟩, ⟨(rel_iso.preimage equiv.ulift r).trans $ f.trans (rel_iso.preimage equiv.ulift s).symm⟩⟩ theorem lift_type_lt {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{(max v w)} (type r) < lift.{(max u w)} (type s) ↔ nonempty (r ≺i s) := by haveI := @rel_embedding.is_well_order _ _ (@equiv.ulift.{(max v w)} α ⁻¹'o r) r (rel_iso.preimage equiv.ulift.{(max v w)} r) _; haveI := @rel_embedding.is_well_order _ _ (@equiv.ulift.{(max u w)} β ⁻¹'o s) s (rel_iso.preimage equiv.ulift.{(max u w)} s) _; exact ⟨λ ⟨f⟩, ⟨(f.equiv_lt (rel_iso.preimage equiv.ulift r).symm).lt_le (initial_seg.of_iso (rel_iso.preimage equiv.ulift s))⟩, λ ⟨f⟩, ⟨(f.equiv_lt (rel_iso.preimage equiv.ulift r)).lt_le (initial_seg.of_iso (rel_iso.preimage equiv.ulift s).symm)⟩⟩ @[simp] theorem lift_le {a b : ordinal} : lift.{u v} a ≤ lift b ↔ a ≤ b := induction_on a $ λ α r _, induction_on b $ λ β s _, by rw ← lift_umax; exactI lift_type_le @[simp] theorem lift_inj {a b : ordinal} : lift a = lift b ↔ a = b := by simp only [le_antisymm_iff, lift_le] @[simp] theorem lift_lt {a b : ordinal} : lift a < lift b ↔ a < b := by simp only [lt_iff_le_not_le, lift_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans ⟨pempty_equiv_pempty, λ a b, iff.rfl⟩⟩ theorem zero_eq_lift_type_empty : 0 = lift.{u} (@type empty empty_relation _) := by rw [← zero_eq_type_empty, lift_zero] @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans ⟨punit_equiv_punit, λ a b, iff.rfl⟩⟩ theorem one_eq_lift_type_unit : 1 = lift.{u} (@type unit empty_relation _) := by rw [← one_eq_type_unit, lift_one] @[simp] theorem lift_card (a) : (card a).lift = card (lift a) := induction_on a $ λ α r _, rfl theorem lift_down' {a : cardinal.{u}} {b : ordinal.{max u v}} (h : card b ≤ a.lift) : ∃ a', lift a' = b := let ⟨c, e⟩ := cardinal.lift_down h in quotient.induction_on c (λ α, induction_on b $ λ β s _ e', begin resetI, rw [mk_def, card_type, ← cardinal.lift_id'.{(max u v) u} (#β), ← cardinal.lift_umax.{u v}, lift_mk_eq.{u (max u v) (max u v)}] at e', cases e' with f, have g := rel_iso.preimage f s, haveI := (g : ⇑f ⁻¹'o s ↪r s).is_well_order, have := lift_type_eq.{u (max u v) (max u v)}.2 ⟨g⟩, rw [lift_id, lift_umax.{u v}] at this, exact ⟨_, this⟩ end) e theorem lift_down {a : ordinal.{u}} {b : ordinal.{max u v}} (h : b ≤ lift a) : ∃ a', lift a' = b := @lift_down' (card a) _ (by rw lift_card; exact card_le_card h) theorem le_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ /-- Initial segment version of the lift operation on ordinals, embedding `ordinal.{u}` in `ordinal.{v}` as an initial segment when `u ≤ v`. -/ def lift.initial_seg : @initial_seg ordinal.{u} ordinal.{max u v} (<) (<) := ⟨⟨⟨lift.{v}, λ a b, lift_inj.1⟩, λ a b, lift_lt⟩, λ a b h, lift_down (le_of_lt h)⟩ @[simp] theorem lift.initial_seg_coe : (lift.initial_seg : ordinal → ordinal) = lift := rfl /-! ### The first infinite ordinal `omega` -/ /-- `ω` is the first infinite ordinal, defined as the order type of `ℕ`. -/ def omega : ordinal.{u} := lift $ @type ℕ (<) _ localized "notation `ω` := ordinal.omega.{0}" in ordinal theorem card_omega : card omega = cardinal.omega := rfl @[simp] theorem lift_omega : lift omega = omega := lift_lift _ /-! ### Definition and first properties of addition on ordinals In this paragraph, we introduce the addition on ordinals, and prove just enough properties to deduce that the order on ordinals is total (and therefore well-founded). Further properties of the addition, together with properties of the other operations, are proved in `ordinal_arithmetic.lean`. -/ /-- `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that every element of `o₁` is smaller than every element of `o₂`. -/ instance : has_add ordinal.{u} := ⟨λo₁ o₂, quotient.lift_on₂ o₁ o₂ (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨α ⊕ β, sum.lex r s, by exactI sum.lex.is_well_order⟩⟧ : Well_order → Well_order → ordinal) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, quot.sound ⟨rel_iso.sum_lex_congr f g⟩⟩ @[simp] theorem card_add (o₁ o₂ : ordinal) : card (o₁ + o₂) = card o₁ + card o₂ := induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _, rfl @[simp] theorem card_nat (n : ℕ) : card.{u} n = n := by induction n; [refl, simp only [card_add, card_one, nat.cast_succ, *]] @[simp] theorem type_add {α β : Type u} (r : α → α → Prop) (s : β → β → Prop) [is_well_order α r] [is_well_order β s] : type r + type s = type (sum.lex r s) := rfl /-- The ordinal successor is the smallest ordinal larger than `o`. It is defined as `o + 1`. -/ def succ (o : ordinal) : ordinal := o + 1 theorem succ_eq_add_one (o) : succ o = o + 1 := rfl instance : add_monoid ordinal.{u} := { add := (+), zero := 0, zero_add := λ o, induction_on o $ λ α r _, eq.symm $ quotient.sound ⟨⟨(empty_sum pempty α).symm, λ a b, sum.lex_inr_inr⟩⟩, add_zero := λ o, induction_on o $ λ α r _, eq.symm $ quotient.sound ⟨⟨(sum_empty α pempty).symm, λ a b, sum.lex_inl_inl⟩⟩, add_assoc := λ o₁ o₂ o₃, quotient.induction_on₃ o₁ o₂ o₃ $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quot.sound ⟨⟨sum_assoc _ _ _, λ a b, begin rcases a with ⟨a|a⟩|a; rcases b with ⟨b|b⟩|b; simp only [sum_assoc_apply_in1, sum_assoc_apply_in2, sum_assoc_apply_in3, sum.lex_inl_inl, sum.lex_inr_inr, sum.lex.sep, sum.lex_inr_inl] end⟩⟩ } theorem add_le_add_left {a b : ordinal} : a ≤ b → ∀ c, c + a ≤ c + b := induction_on a $ λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ λ β s _, ⟨⟨⟨(embedding.refl _).sum_map f, λ a b, match a, b with | sum.inl a, sum.inl b := sum.lex_inl_inl.trans sum.lex_inl_inl.symm | sum.inl a, sum.inr b := by apply iff_of_true; apply sum.lex.sep | sum.inr a, sum.inl b := by apply iff_of_false; exact sum.lex_inr_inl | sum.inr a, sum.inr b := sum.lex_inr_inr.trans $ fo.trans sum.lex_inr_inr.symm end⟩, λ a b H, match a, b, H with | _, sum.inl b, _ := ⟨sum.inl b, rfl⟩ | sum.inl a, sum.inr b, H := (sum.lex_inr_inl H).elim | sum.inr a, sum.inr b, H := let ⟨w, h⟩ := fi _ _ (sum.lex_inr_inr.1 H) in ⟨sum.inr w, congr_arg sum.inr h⟩ end⟩⟩ theorem le_add_right (a b : ordinal) : a ≤ a + b := by simpa only [add_zero] using add_le_add_left (ordinal.zero_le b) a theorem add_le_add_right {a b : ordinal} : a ≤ b → ∀ c, a + c ≤ b + c := induction_on a $ λ α₁ r₁ hr₁, induction_on b $ λ α₂ r₂ hr₂ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ λ β s hs, (@type_le' _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr₁ hs) (@sum.lex.is_well_order _ _ _ _ hr₂ hs)).2 ⟨⟨f.sum_map (embedding.refl _), λ a b, begin split; intro H, { cases a with a a; cases b with b b; cases H; constructor; [rwa ← fo, assumption] }, { cases H; constructor; [rwa fo, assumption] } end⟩⟩ theorem le_add_left (a b : ordinal) : a ≤ b + a := by simpa only [zero_add] using add_le_add_right (ordinal.zero_le b) a theorem lt_succ_self (o : ordinal.{u}) : o < succ o := induction_on o $ λ α r _, ⟨⟨⟨⟨λ x, sum.inl x, λ _ _, sum.inl.inj⟩, λ _ _, sum.lex_inl_inl⟩, sum.inr punit.star, λ b, sum.rec_on b (λ x, ⟨λ _, ⟨x, rfl⟩, λ _, sum.lex.sep _ _⟩) (λ x, sum.lex_inr_inr.trans ⟨false.elim, λ ⟨x, H⟩, sum.inl_ne_inr H⟩)⟩⟩ theorem succ_le {a b : ordinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), induction_on a $ λ α r hr, induction_on b $ λ β s hs ⟨⟨f, t, hf⟩⟩, begin refine ⟨⟨@rel_embedding.of_monotone (α ⊕ punit) β _ _ (@sum.lex.is_well_order _ _ _ _ hr _).1.1 (@is_asymm_of_is_trans_of_is_irrefl _ _ hs.1.2.2 hs.1.2.1) (sum.rec _ _) (λ a b, _), λ a b, _⟩⟩, { exact f }, { exact λ _, t }, { rcases a with a|_; rcases b with b|_, { simpa only [sum.lex_inl_inl] using f.map_rel_iff.2 }, { intro _, rw hf, exact ⟨_, rfl⟩ }, { exact false.elim ∘ sum.lex_inr_inl }, { exact false.elim ∘ sum.lex_inr_inr.1 } }, { rcases a with a|_, { intro h, have := @principal_seg.init _ _ _ _ hs.1.2.2 ⟨f, t, hf⟩ _ _ h, cases this with w h, exact ⟨sum.inl w, h⟩ }, { intro h, cases (hf b).1 h with w h, exact ⟨sum.inl w, h⟩ } } end⟩ theorem le_total (a b : ordinal) : a ≤ b ∨ b ≤ a := match lt_or_eq_of_le (le_add_left b a), lt_or_eq_of_le (le_add_right a b) with | or.inr h, _ := by rw h; exact or.inl (le_add_right _ _) | _, or.inr h := by rw h; exact or.inr (le_add_left _ _) | or.inl h₁, or.inl h₂ := induction_on a (λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨f⟩ ⟨g⟩, begin resetI, rw [← typein_top f, ← typein_top g, le_iff_lt_or_eq, le_iff_lt_or_eq, typein_lt_typein, typein_lt_typein], rcases trichotomous_of (sum.lex r₁ r₂) g.top f.top with h|h|h; [exact or.inl (or.inl h), {left, right, rw h}, exact or.inr (or.inl h)] end) h₁ h₂ end instance : linear_order ordinal := { le_total := le_total, decidable_le := classical.dec_rel _, ..ordinal.partial_order } instance : is_well_order ordinal (<) := ⟨wf⟩ @[simp] lemma typein_le_typein (r : α → α → Prop) [is_well_order α r] {x x' : α} : typein r x ≤ typein r x' ↔ ¬r x' x := by rw [←not_lt, typein_lt_typein] lemma enum_le_enum (r : α → α → Prop) [is_well_order α r] {o o' : ordinal} (ho : o < type r) (ho' : o' < type r) : ¬r (enum r o' ho') (enum r o ho) ↔ o ≤ o' := by rw [←@not_lt _ _ o' o, enum_lt ho'] /-- `univ.{u v}` is the order type of the ordinals of `Type u` as a member of `ordinal.{v}` (when `u < v`). It is an inaccessible cardinal. -/ @[nolint check_univs] -- intended to be used with explicit universe parameters def univ : ordinal.{max (u + 1) v} := lift.{v (u+1)} (@type ordinal.{u} (<) _) theorem univ_id : univ.{u (u+1)} = @type ordinal.{u} (<) _ := lift_id _ @[simp] theorem lift_univ : lift.{w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ /-- Principal segment version of the lift operation on ordinals, embedding `ordinal.{u}` in `ordinal.{v}` as a principal segment when `u < v`. -/ def lift.principal_seg : @principal_seg ordinal.{u} ordinal.{max (u+1) v} (<) (<) := ⟨↑lift.initial_seg.{u (max (u+1) v)}, univ.{u v}, begin refine λ b, induction_on b _, introsI β s _, rw [univ, ← lift_umax], split; intro h, { rw ← lift_id (type s) at h ⊢, cases lift_type_lt.1 h with f, cases f with f a hf, existsi a, revert hf, apply induction_on a, introsI α r _ hf, refine lift_type_eq.{u (max (u+1) v) (max (u+1) v)}.2 ⟨(rel_iso.of_surjective (rel_embedding.of_monotone _ _) _).symm⟩, { exact λ b, enum r (f b) ((hf _).2 ⟨_, rfl⟩) }, { refine λ a b h, (typein_lt_typein r).1 _, rw [typein_enum, typein_enum], exact f.map_rel_iff.2 h }, { intro a', cases (hf _).1 (typein_lt_type _ a') with b e, existsi b, simp, simp [e] } }, { cases h with a e, rw [← e], apply induction_on a, introsI α r _, exact lift_type_lt.{u (u+1) (max (u+1) v)}.2 ⟨typein.principal_seg r⟩ } end⟩ @[simp] theorem lift.principal_seg_coe : (lift.principal_seg.{u v} : ordinal → ordinal) = lift.{(max (u+1) v)} := rfl @[simp] theorem lift.principal_seg_top : lift.principal_seg.top = univ := rfl theorem lift.principal_seg_top' : lift.principal_seg.{u (u+1)}.top = @type ordinal.{u} (<) _ := by simp only [lift.principal_seg_top, univ_id] /-! ### Minimum -/ /-- The minimal element of a nonempty family of ordinals -/ def min {ι} (I : nonempty ι) (f : ι → ordinal) : ordinal := wf.min (set.range f) (let ⟨i⟩ := I in ⟨_, set.mem_range_self i⟩) theorem min_eq {ι} (I) (f : ι → ordinal) : ∃ i, min I f = f i := let ⟨i, e⟩ := wf.min_mem (set.range f) _ in ⟨i, e.symm⟩ theorem min_le {ι I} (f : ι → ordinal) (i) : min I f ≤ f i := le_of_not_gt $ wf.not_lt_min (set.range f) _ (set.mem_range_self i) theorem le_min {ι I} {f : ι → ordinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ /-- The minimal element of a nonempty set of ordinals -/ def omin (S : set ordinal.{u}) (H : ∃ x, x ∈ S) : ordinal.{u} := @min.{(u+2) u} S (let ⟨x, px⟩ := H in ⟨⟨x, px⟩⟩) subtype.val theorem omin_mem (S H) : omin S H ∈ S := let ⟨⟨i, h⟩, e⟩ := @min_eq S _ _ in (show omin S H = i, from e).symm ▸ h theorem le_omin {S H a} : a ≤ omin S H ↔ ∀ i ∈ S, a ≤ i := le_min.trans set_coe.forall theorem omin_le {S H i} (h : i ∈ S) : omin S H ≤ i := le_omin.1 (le_refl _) _ h @[simp] theorem lift_min {ι} (I) (f : ι → ordinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) instance : conditionally_complete_linear_order_bot ordinal := wf.conditionally_complete_linear_order_with_bot 0 $ le_antisymm (ordinal.zero_le _) $ not_lt.1 (wf.not_lt_min set.univ ⟨0, mem_univ _⟩ (mem_univ 0)) @[simp] lemma bot_eq_zero : (⊥ : ordinal) = 0 := rfl lemma Inf_eq_omin {s : set ordinal} (hs : s.nonempty) : Inf s = omin s hs := begin simp only [Inf, conditionally_complete_lattice.Inf, omin, conditionally_complete_linear_order.Inf, conditionally_complete_linear_order_bot.Inf, hs, dif_pos], congr, rw subtype.range_val, end lemma Inf_mem {s : set ordinal} (hs : s.nonempty) : Inf s ∈ s := by { rw Inf_eq_omin hs, exact omin_mem _ hs } instance : no_top_order ordinal := ⟨λ a, ⟨a.succ, lt_succ_self a⟩⟩ end ordinal /-! ### Representing a cardinal with an ordinal -/ namespace cardinal open ordinal /-- The ordinal corresponding to a cardinal `c` is the least ordinal whose cardinal is `c`. For the order-embedding version, see `ord.order_embedding`. -/ def ord (c : cardinal) : ordinal := begin let ι := λ α, {r // is_well_order α r}, have : Π α, ι α := λ α, ⟨well_ordering_rel, by apply_instance⟩, let F := λ α, ordinal.min ⟨this _⟩ (λ i:ι α, ⟦⟨α, i.1, i.2⟩⟧), refine quot.lift_on c F _, suffices : ∀ {α β}, α ≈ β → F α ≤ F β, from λ α β h, le_antisymm (this h) (this (setoid.symm h)), intros α β h, cases h with f, refine ordinal.le_min.2 (λ i, _), haveI := @rel_embedding.is_well_order _ _ (f ⁻¹'o i.1) _ ↑(rel_iso.preimage f i.1) i.2, rw ← show type (f ⁻¹'o i.1) = ⟦⟨β, i.1, i.2⟩⟧, from quot.sound ⟨rel_iso.preimage f i.1⟩, exact ordinal.min_le (λ i:ι α, ⟦⟨α, i.1, i.2⟩⟧) ⟨_, _⟩ end lemma ord_eq_min (α : Type u) : ord (#α) = @ordinal.min {r // is_well_order α r} ⟨⟨well_ordering_rel, by apply_instance⟩⟩ (λ i, ⟦⟨α, i.1, i.2⟩⟧) := rfl theorem ord_eq (α) : ∃ (r : α → α → Prop) [wo : is_well_order α r], ord (#α) = @type α r wo := let ⟨⟨r, wo⟩, h⟩ := @ordinal.min_eq {r // is_well_order α r} ⟨⟨well_ordering_rel, by apply_instance⟩⟩ (λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) in ⟨r, wo, h⟩ theorem ord_le_type (r : α → α → Prop) [is_well_order α r] : ord (#α) ≤ ordinal.type r := @ordinal.min_le {r // is_well_order α r} ⟨⟨well_ordering_rel, by apply_instance⟩⟩ (λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) ⟨r, _⟩ theorem ord_le {c o} : ord c ≤ o ↔ c ≤ o.card := quotient.induction_on c $ λ α, induction_on o $ λ β s _, let ⟨r, _, e⟩ := ord_eq α in begin resetI, simp only [mk_def, card_type], split; intro h, { rw e at h, exact let ⟨f⟩ := h in ⟨f.to_embedding⟩ }, { cases h with f, have g := rel_embedding.preimage f s, haveI := rel_embedding.is_well_order g, exact le_trans (ord_le_type _) (type_le'.2 ⟨g⟩) } end theorem lt_ord {c o} : o < ord c ↔ o.card < c := by rw [← not_le, ← not_le, ord_le] @[simp] theorem card_ord (c) : (ord c).card = c := quotient.induction_on c $ λ α, let ⟨r, _, e⟩ := ord_eq α in by simp only [mk_def, e, card_type] theorem ord_card_le (o : ordinal) : o.card.ord ≤ o := ord_le.2 (le_refl _) lemma lt_ord_succ_card (o : ordinal) : o < o.card.succ.ord := by { rw [lt_ord], apply cardinal.lt_succ_self } @[simp] theorem ord_le_ord {c₁ c₂} : ord c₁ ≤ ord c₂ ↔ c₁ ≤ c₂ := by simp only [ord_le, card_ord] @[simp] theorem ord_lt_ord {c₁ c₂} : ord c₁ < ord c₂ ↔ c₁ < c₂ := by simp only [lt_ord, card_ord] @[simp] theorem ord_zero : ord 0 = 0 := le_antisymm (ord_le.2 $ zero_le _) (ordinal.zero_le _) @[simp] theorem ord_nat (n : ℕ) : ord n = n := le_antisymm (ord_le.2 $ by simp only [card_nat]) $ begin induction n with n IH, { apply ordinal.zero_le }, { exact (@ordinal.succ_le n _).2 (lt_of_le_of_lt IH $ ord_lt_ord.2 $ nat_cast_lt.2 (nat.lt_succ_self n)) } end @[simp] theorem lift_ord (c) : (ord c).lift = ord (lift c) := eq_of_forall_ge_iff $ λ o, le_iff_le_iff_lt_iff_lt.2 $ begin split; intro h, { rcases ordinal.lt_lift_iff.1 h with ⟨a, e, h⟩, rwa [← e, lt_ord, ← lift_card, lift_lt, ← lt_ord] }, { rw lt_ord at h, rcases lift_down' (le_of_lt h) with ⟨o, rfl⟩, rw [← lift_card, lift_lt] at h, rwa [ordinal.lift_lt, lt_ord] } end lemma mk_ord_out (c : cardinal) : #c.ord.out.α = c := by rw [←card_type c.ord.out.r, type_out, card_ord] lemma card_typein_lt (r : α → α → Prop) [is_well_order α r] (x : α) (h : ord (#α) = type r) : card (typein r x) < #α := by { rw [←ord_lt_ord, h], refine lt_of_le_of_lt (ord_card_le _) (typein_lt_type r x) } lemma card_typein_out_lt (c : cardinal) (x : c.ord.out.α) : card (typein c.ord.out.r x) < c := by { convert card_typein_lt c.ord.out.r x _, rw [mk_ord_out], rw [type_out, mk_ord_out] } lemma ord_injective : injective ord := by { intros c c' h, rw [←card_ord c, ←card_ord c', h] } /-- The ordinal corresponding to a cardinal `c` is the least ordinal whose cardinal is `c`. This is the order-embedding version. For the regular function, see `ord`. -/ def ord.order_embedding : cardinal ↪o ordinal := rel_embedding.order_embedding_of_lt_embedding (rel_embedding.of_monotone cardinal.ord $ λ a b, cardinal.ord_lt_ord.2) @[simp] theorem ord.order_embedding_coe : (ord.order_embedding : cardinal → ordinal) = ord := rfl /-- The cardinal `univ` is the cardinality of ordinal `univ`, or equivalently the cardinal of `ordinal.{u}`, or `cardinal.{u}`, as an element of `cardinal.{v}` (when `u < v`). -/ @[nolint check_univs] -- intended to be used with explicit universe parameters def univ := lift.{v (u+1)} (#ordinal) theorem univ_id : univ.{u (u+1)} = #ordinal := lift_id _ @[simp] theorem lift_univ : lift.{w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ theorem lift_lt_univ (c : cardinal) : lift.{(u+1) u} c < univ.{u (u+1)} := by simpa only [lift.principal_seg_coe, lift_ord, lift_succ, ord_le, succ_le] using le_of_lt (lift.principal_seg.{u (u+1)}.lt_top (succ c).ord) theorem lift_lt_univ' (c : cardinal) : lift.{(max (u+1) v) u} c < univ.{u v} := by simpa only [lift_lift, lift_univ, univ_umax] using lift_lt.{_ (max (u+1) v)}.2 (lift_lt_univ c) @[simp] theorem ord_univ : ord univ.{u v} = ordinal.univ.{u v} := le_antisymm (ord_card_le _) $ le_of_forall_lt $ λ o h, lt_ord.2 begin rcases lift.principal_seg.{u v}.down'.1 (by simpa only [lift.principal_seg_coe] using h) with ⟨o', rfl⟩, simp only [lift.principal_seg_coe], rw [← lift_card], apply lift_lt_univ' end theorem lt_univ {c} : c < univ.{u (u+1)} ↔ ∃ c', c = lift.{(u+1) u} c' := ⟨λ h, begin have := ord_lt_ord.2 h, rw ord_univ at this, cases lift.principal_seg.{u (u+1)}.down'.1 (by simpa only [lift.principal_seg_top]) with o e, have := card_ord c, rw [← e, lift.principal_seg_coe, ← lift_card] at this, exact ⟨_, this.symm⟩ end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ _⟩ theorem lt_univ' {c} : c < univ.{u v} ↔ ∃ c', c = lift.{(max (u+1) v) u} c' := ⟨λ h, let ⟨a, e, h'⟩ := lt_lift_iff.1 h in begin rw [← univ_id] at h', rcases lt_univ.{u}.1 h' with ⟨c', rfl⟩, exact ⟨c', by simp only [e.symm, lift_lift]⟩ end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ' _⟩ end cardinal namespace ordinal @[simp] theorem card_univ : card univ = cardinal.univ := rfl end ordinal
6c7b058b9e3a32f9c4cb2b31bc5ff0a270db8846
df7bb3acd9623e489e95e85d0bc55590ab0bc393
/lean/love02_backward_proofs_exercise_sheet.lean
ff153709e559c8a54a7340f50fec0648a7d71159
[]
no_license
MaschavanderMarel/logical_verification_2020
a41c210b9237c56cb35f6cd399e3ac2fe42e775d
7d562ef174cc6578ca6013f74db336480470b708
refs/heads/master
1,692,144,223,196
1,634,661,675,000
1,634,661,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,388
lean
import .love02_backward_proofs_demo /- # LoVe Exercise 2: Backward Proofs -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe namespace backward_proofs /- ## Question 1: Connectives and Quantifiers 1.1. Carry out the following proofs using basic tactics. Hint: Some strategies for carrying out such proofs are described at the end of Section 2.3 in the Hitchhiker's Guide. -/ lemma I (a : Prop) : a → a := sorry lemma K (a b : Prop) : a → b → b := sorry lemma C (a b c : Prop) : (a → b → c) → b → a → c := sorry lemma proj_1st (a : Prop) : a → a → a := sorry /- Please give a different answer than for `proj_1st`: -/ lemma proj_2nd (a : Prop) : a → a → a := sorry lemma some_nonsense (a b c : Prop) : (a → b → c) → a → (a → c) → b → c := sorry /- 1.2. Prove the contraposition rule using basic tactics. -/ lemma contrapositive (a b : Prop) : (a → b) → ¬ b → ¬ a := sorry /- 1.3. Prove the distributivity of `∀` over `∧` using basic tactics. Hint: This exercise is tricky, especially the right-to-left direction. Some forward reasoning, like in the proof of `and_swap₂` in the lecture, might be necessary. -/ lemma forall_and {α : Type} (p q : α → Prop) : (∀x, p x ∧ q x) ↔ (∀x, p x) ∧ (∀x, q x) := sorry /- ## Question 2: Natural Numbers 2.1. Prove the following recursive equations on the first argument of the `mul` operator defined in lecture 1. -/ #check mul lemma mul_zero (n : ℕ) : mul 0 n = 0 := sorry lemma mul_succ (m n : ℕ) : mul (nat.succ m) n = add (mul m n) n := sorry /- 2.2. Prove commutativity and associativity of multiplication using the `induction'` tactic. Choose the induction variable carefully. -/ lemma mul_comm (m n : ℕ) : mul m n = mul n m := sorry lemma mul_assoc (l m n : ℕ) : mul (mul l m) n = mul l (mul m n) := sorry /- 2.3. Prove the symmetric variant of `mul_add` using `rw`. To apply commutativity at a specific position, instantiate the rule by passing some arguments (e.g., `mul_comm _ l`). -/ lemma add_mul (l m n : ℕ) : mul (add l m) n = add (mul n l) (mul n m) := sorry /- ## Question 3 (**optional**): Intuitionistic Logic Intuitionistic logic is extended to classical logic by assuming a classical axiom. There are several possibilities for the choice of axiom. In this question, we are concerned with the logical equivalence of three different axioms: -/ def excluded_middle := ∀a : Prop, a ∨ ¬ a def peirce := ∀a b : Prop, ((a → b) → a) → a def double_negation := ∀a : Prop, (¬¬ a) → a /- For the proofs below, please avoid using lemmas from Lean's `classical` namespace, because this would defeat the purpose of the exercise. 3.1 (**optional**). Prove the following implication using tactics. Hint: You will need `or.elim` and `false.elim`. You can use `rw excluded_middle` to unfold the definition of `excluded_middle`, and similarly for `peirce`. -/ lemma peirce_of_em : excluded_middle → peirce := sorry /- 3.2 (**optional**). Prove the following implication using tactics. -/ lemma dn_of_peirce : peirce → double_negation := sorry /- We leave the missing implication for the homework: -/ namespace sorry_lemmas lemma em_of_dn : double_negation → excluded_middle := sorry end sorry_lemmas end backward_proofs end LoVe
61032e48073d9915eea57fb5c7726287bea2aac9
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/tactic/solve_by_elim.lean
d53b9c7a72df2ebe59369c7e1fc01efe07805146
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
14,282
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Scott Morrison -/ import tactic.core /-! # solve_by_elim A depth-first search backwards reasoner. `solve_by_elim` takes a list of lemmas, and repeating tries to `apply` these against the goals, recursively acting on any generated subgoals. It accepts a variety of configuration options described below, enabling * backtracking across multiple goals, * pruning the search tree, and * invoking other tactics before or after trying to apply lemmas. At present it has no "premise selection", and simply tries the supplied lemmas in order at each step of the search. -/ namespace tactic namespace solve_by_elim /-- `mk_assumption_set` builds a collection of lemmas for use in the backtracking search in `solve_by_elim`. * By default, it includes all local hypotheses, along with `rfl`, `trivial`, `congr_fun` and `congr_arg`. * The flag `no_dflt` removes these. * The argument `hs` is a list of `simp_arg_type`s, and can be used to add, or remove, lemmas or expressions from the set. * The argument `attr : list name` adds all lemmas tagged with one of a specified list of attributes. `mk_assumption_set` returns not a `list expr`, but a `list (tactic expr)`. The problem here is that we may generate lemmas that have as yet unspecified implicit arguments, and these implicit arguments would be filled in by metavariables if we created the actual `expr` objects now. As an example, we have `def rfl : ∀ {α : Sort u} {a : α}, a = a`, which on elaboration will become `@rfl ?m_1 ?m_2`. Because `solve_by_elim` works by repeated application of lemmas against subgoals, the first time such a lemma is successfully applied, those metavariables will be unified, and thereafter have fixed values. This would make it impossible to apply the lemma a second time with different values of the metavariables. See https://github.com/leanprover-community/mathlib/issues/2269 As an optimisation, after we build the list of `tactic expr`s, we actually run them, and replace any that do not in fact produce metavariables with a simple `return` tactic. -/ meta def mk_assumption_set (no_dflt : bool) (hs : list simp_arg_type) (attr : list name) : tactic (list (tactic expr)) := -- We lock the tactic state so that any spurious goals generated during -- elaboration of pre-expressions are discarded lock_tactic_state $ do -- `hs` are expressions specified explicitly, -- `hex` are exceptions (specified via `solve_by_elim [-h]`) referring to local hypotheses, -- `gex` are the other exceptions (hs, gex, hex, all_hyps) ← decode_simp_arg_list hs, -- Recall, per the discussion above, we produce `tactic expr` thunks rather than actual `expr`s. -- Note that while we evaluate these thunks on two occasions below while preparing the list, -- this is a one-time cost during `mk_assumption_set`, rather than a cost proportional to the -- length of the search `solve_by_elim` executes. let hs := hs.map (λ h, i_to_expr_for_apply h), l ← attr.mmap $ λ a, attribute.get_instances a, let l := l.join, let m := l.map (λ h, mk_const h), -- In order to remove the expressions we need to evaluate the thunks. hs ← (hs ++ m).mfilter $ λ h, (do h ← h, return $ expr.const_name h ∉ gex), let hs := if no_dflt then hs else ([`rfl, `trivial, `congr_fun, `congr_arg].map (λ n, (mk_const n))) ++ hs, hs ← if ¬ no_dflt ∨ all_hyps then do ctx ← local_context, -- Remove local exceptions specified in `hex`: return $ hs.append ((ctx.filter (λ h : expr, h.local_uniq_name ∉ hex)).map return) else return hs, -- Finally, run all of the tactics: any that return an expression without metavariables can safely -- be replaced by a `return` tactic. hs.mmap (λ h, do e ← h, if e.has_meta_var then return h else return (return e)) /-- Configuration options for `solve_by_elim`. * `accept : list expr → tactic unit` determines whether the current branch should be explored. At each step, before the lemmas are applied, `accept` is passed the proof terms for the original goals, as reported by `get_goals` when `solve_by_elim` started. These proof terms may be metavariables (if no progress has been made on that goal) or may contain metavariables at some leaf nodes (if the goal has been partially solved by previous `apply` steps). If the `accept` tactic fails `solve_by_elim` aborts searching this branch and backtracks. By default `accept := λ _, skip` always succeeds. (There is an example usage in `tests/solve_by_elim.lean`.) * `pre_apply : tactic unit` specifies an additional tactic to run before each round of `apply`. * `discharger : tactic unit` specifies an additional tactic to apply on subgoals for which no lemma applies. If that tactic succeeds, `solve_by_elim` will continue applying lemmas on resulting goals. -/ meta structure basic_opt extends apply_any_opt := (accept : list expr → tactic unit := λ _, skip) (pre_apply : tactic unit := skip) (discharger : tactic unit := failed) (max_depth : ℕ := 3) declare_trace solve_by_elim -- trace attempted lemmas /-- A helper function for trace messages, prepending '....' depending on the current search depth. -/ meta def solve_by_elim_trace (n : ℕ) (f : format) : tactic unit := trace_if_enabled `solve_by_elim (format!"[solve_by_elim {(list.repeat '.' (n+1)).as_string} " ++ f ++ "]") /-- A helper function to generate trace messages on successful applications. -/ meta def on_success (g : format) (n : ℕ) (e : expr) : tactic unit := do pp ← pp e, solve_by_elim_trace n (format!"✅ `{pp}` solves `⊢ {g}`") /-- A helper function to generate trace messages on unsuccessful applications. -/ meta def on_failure (g : format) (n : ℕ) : tactic unit := solve_by_elim_trace n (format!"❌ failed to solve `⊢ {g}`") /-- A helper function to generate the tactic that print trace messages. This function exists to ensure the target is pretty printed only as necessary. -/ meta def trace_hooks (n : ℕ) : tactic ((expr → tactic unit) × tactic unit) := if is_trace_enabled_for `solve_by_elim then do g ← target >>= pp, return (on_success g n, on_failure g n) else return (λ _, skip, skip) /-- The internal implementation of `solve_by_elim`, with a limiting counter. -/ meta def solve_by_elim_aux (opt : basic_opt) (original_goals : list expr) (lemmas : list (tactic expr)) : ℕ → tactic unit | n := do -- First, check that progress so far is `accept`able. lock_tactic_state (original_goals.mmap instantiate_mvars >>= opt.accept), -- Then check if we've finished. (done >> solve_by_elim_trace (opt.max_depth - n) "success!") <|> (do -- Otherwise, if there's more time left, (guard (n > 0) <|> solve_by_elim_trace opt.max_depth "🛑 aborting, hit depth limit" >> failed), -- run the `pre_apply` tactic, then opt.pre_apply, -- try either applying a lemma and recursing, (on_success, on_failure) ← trace_hooks (opt.max_depth - n), (apply_any_thunk lemmas opt.to_apply_any_opt (solve_by_elim_aux (n-1)) on_success on_failure) <|> -- or if that doesn't work, run the discharger and recurse. (opt.discharger >> solve_by_elim_aux (n-1))) /-- Arguments for `solve_by_elim`: * By default `solve_by_elim` operates only on the first goal, but with `backtrack_all_goals := true`, it operates on all goals at once, backtracking across goals as needed, and only succeeds if it discharges all goals. * `lemmas` specifies the list of lemmas to use in the backtracking search. If `none`, `solve_by_elim` uses the local hypotheses, along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`. * `lemma_thunks` provides the lemmas as a list of `tactic expr`, which are used to regenerate the `expr` objects to avoid binding metavariables. (If both `lemmas` and `lemma_thunks` are specified, only `lemma_thunks` is used.) * `max_depth` bounds the depth of the search. -/ meta structure opt extends basic_opt := (backtrack_all_goals : bool := ff) (lemmas : option (list expr) := none) (lemma_thunks : option (list (tactic expr)) := lemmas.map (λ l, l.map return)) /-- If no lemmas have been specified, generate the default set (local hypotheses, along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`). -/ meta def opt.get_lemma_thunks (opt : opt) : tactic (list (tactic expr)) := match opt.lemma_thunks with | none := mk_assumption_set ff [] [] | some lemma_thunks := return lemma_thunks end end solve_by_elim open solve_by_elim /-- `solve_by_elim` repeatedly tries `apply`ing a lemma from the list of assumptions (passed via the `opt` argument), recursively operating on any generated subgoals, backtracking as necessary. `solve_by_elim` succeeds only if it discharges the goal. (By default, `solve_by_elim` focuses on the first goal, and only attempts to solve that. With the option `backtrack_all_goals := tt`, it attempts to solve all goals, and only succeeds if it does so. With `backtrack_all_goals := tt`, `solve_by_elim` will backtrack a solution it has found for one goal if it then can't discharge other goals.) If passed an empty list of assumptions, `solve_by_elim` builds a default set as per the interactive tactic, using the `local_context` along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`. To pass a particular list of assumptions, use the `lemmas` field in the configuration argument. This expects an `option (list expr)`. In certain situations it may be necessary to instead use the `lemma_thunks` field, which expects a `option (list (tactic expr))`. This allows for regenerating metavariables for each application, which might otherwise get stuck. See also the simpler tactic `apply_rules`, which does not perform backtracking. -/ meta def solve_by_elim (opt : opt := { }) : tactic unit := do tactic.fail_if_no_goals, lemmas ← opt.get_lemma_thunks, (if opt.backtrack_all_goals then id else focus1) $ (do gs ← get_goals, solve_by_elim_aux opt.to_basic_opt gs lemmas opt.max_depth <|> fail ("`solve_by_elim` failed.\n" ++ "Try `solve_by_elim { max_depth := N }` for `N > " ++ (to_string opt.max_depth) ++ "`\n" ++ "or use `set_option trace.solve_by_elim true` to view the search.")) open interactive lean.parser interactive.types local postfix `?`:9001 := optional namespace interactive /-- `apply_assumption` looks for an assumption of the form `... → ∀ _, ... → head` where `head` matches the current goal. If this fails, `apply_assumption` will call `symmetry` and try again. If this also fails, `apply_assumption` will call `exfalso` and try again, so that if there is an assumption of the form `P → ¬ Q`, the new tactic state will have two goals, `P` and `Q`. Optional arguments: - `lemmas`: a list of expressions to apply, instead of the local constants - `tac`: a tactic to run on each subgoal after applying an assumption; if this tactic fails, the corresponding assumption will be rejected and the next one will be attempted. -/ meta def apply_assumption (lemmas : option (list expr) := none) (opt : apply_any_opt := {}) (tac : tactic unit := skip) : tactic unit := do lemmas ← match lemmas with | none := local_context | some lemmas := return lemmas end, tactic.apply_any lemmas opt tac add_tactic_doc { name := "apply_assumption", category := doc_category.tactic, decl_names := [`tactic.interactive.apply_assumption], tags := ["context management", "lemma application"] } /-- `solve_by_elim` calls `apply` on the main goal to find an assumption whose head matches and then repeatedly calls `apply` on the generated subgoals until no subgoals remain, performing at most `max_depth` recursive steps. `solve_by_elim` discharges the current goal or fails. `solve_by_elim` performs back-tracking if subgoals can not be solved. By default, the assumptions passed to `apply` are the local context, `rfl`, `trivial`, `congr_fun` and `congr_arg`. The assumptions can be modified with similar syntax as for `simp`: * `solve_by_elim [h₁, h₂, ..., hᵣ]` also applies the named lemmas. * `solve_by_elim with attr₁ ... attrᵣ` also applies all lemmas tagged with the specified attributes. * `solve_by_elim only [h₁, h₂, ..., hᵣ]` does not include the local context, `rfl`, `trivial`, `congr_fun`, or `congr_arg` unless they are explicitly included. * `solve_by_elim [-id_1, ... -id_n]` uses the default assumptions, removing the specified ones. `solve_by_elim*` tries to solve all goals together, using backtracking if a solution for one goal makes other goals impossible. optional arguments passed via a configuration argument as `solve_by_elim { ... }` - max_depth: number of attempts at discharging generated sub-goals - discharger: a subsidiary tactic to try at each step when no lemmas apply (e.g. `cc` may be helpful). - pre_apply: a subsidiary tactic to run at each step before applying lemmas (e.g. `intros`). - accept: a subsidiary tactic `list expr → tactic unit` that at each step, before any lemmas are applied, is passed the original proof terms as reported by `get_goals` when `solve_by_elim` started (but which may by now have been partially solved by previous `apply` steps). If the `accept` tactic fails, `solve_by_elim` will abort searching the current branch and backtrack. This may be used to filter results, either at every step of the search, or filtering complete results (by testing for the absence of metavariables, and then the filtering condition). -/ meta def solve_by_elim (all_goals : parse $ (tk "*")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : solve_by_elim.opt := { }) : tactic unit := do lemma_thunks ← mk_assumption_set no_dflt hs attr_names, tactic.solve_by_elim { backtrack_all_goals := all_goals.is_some ∨ opt.backtrack_all_goals, lemma_thunks := some lemma_thunks, ..opt } add_tactic_doc { name := "solve_by_elim", category := doc_category.tactic, decl_names := [`tactic.interactive.solve_by_elim], tags := ["search"] } end interactive end tactic
6f8b0bef58b6f3131ac7e830dca8ab34ee576da5
7cef822f3b952965621309e88eadf618da0c8ae9
/src/ring_theory/maps.lean
476cdd1c542916fb77183c3800e390a9298d5839
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
5,153
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow, Kenny Lau -/ import data.equiv.algebra /-! # Ring antihomomorphisms, isomorphisms, antiisomorphisms and involutions This file defines ring antihomomorphisms, antiisomorphism and involutions and proves basic properties of them. ## Notations All types defined in this file are given a coercion to the underlying function. ## References * <https://en.wikipedia.org/wiki/Antihomomorphism> * <https://en.wikipedia.org/wiki/Involution_(mathematics)#Ring_theory> ## Tags Ring isomorphism, automorphism, antihomomorphism, antiisomorphism, antiautomorphism, involution -/ variables {R : Type*} {F : Type*} /- The Proposition that a function from a ring to a ring is an antihomomorphism -/ class is_ring_anti_hom [ring R] [ring F] (f : R → F) : Prop := (map_one : f 1 = 1) (map_mul : ∀ {x y : R}, f (x * y) = f y * f x) (map_add : ∀ {x y : R}, f (x + y) = f x + f y) namespace is_ring_anti_hom variables [ring R] [ring F] (f : R → F) [is_ring_anti_hom f] @[priority 100] -- see Note [lower instance priority] instance : is_add_group_hom f := { to_is_add_hom := ⟨λ x y, is_ring_anti_hom.map_add f⟩ } lemma map_zero : f 0 = 0 := is_add_group_hom.map_zero f lemma map_neg {x} : f (-x) = -f x := is_add_group_hom.map_neg f x lemma map_sub {x y} : f (x - y) = f x - f y := is_add_group_hom.map_sub f x y end is_ring_anti_hom variables (R F) namespace ring_equiv open ring_equiv variables {R F} [ring R] [ring F] (Hs : R ≃+* F) (x y : R) lemma bijective : function.bijective Hs := Hs.to_equiv.bijective lemma map_zero_iff {x : R} : Hs x = 0 ↔ x = 0 := ⟨λ H, Hs.bijective.1 $ H.symm ▸ Hs.map_zero.symm, λ H, H.symm ▸ Hs.map_zero⟩ end ring_equiv /-- A ring antiisomorphism -/ structure ring_anti_equiv [ring R] [ring F] extends R ≃ F := [anti_hom : is_ring_anti_hom to_fun] namespace ring_anti_equiv variables {R F} [ring R] [ring F] (Hs : ring_anti_equiv R F) (x y : R) instance : has_coe_to_fun (ring_anti_equiv R F) := ⟨_, λ Hs, Hs.to_fun⟩ instance : is_ring_anti_hom Hs := Hs.anti_hom lemma map_add : Hs (x + y) = Hs x + Hs y := is_ring_anti_hom.map_add Hs lemma map_zero : Hs 0 = 0 := is_ring_anti_hom.map_zero Hs lemma map_neg : Hs (-x) = -Hs x := is_ring_anti_hom.map_neg Hs lemma map_sub : Hs (x - y) = Hs x - Hs y := is_ring_anti_hom.map_sub Hs lemma map_mul : Hs (x * y) = Hs y * Hs x := is_ring_anti_hom.map_mul Hs lemma map_one : Hs 1 = 1 := is_ring_anti_hom.map_one Hs lemma map_neg_one : Hs (-1) = -1 := Hs.map_one ▸ Hs.map_neg 1 lemma bijective : function.bijective Hs := Hs.to_equiv.bijective lemma map_zero_iff {x : R} : Hs x = 0 ↔ x = 0 := ⟨λ H, Hs.bijective.1 $ H.symm ▸ Hs.map_zero.symm, λ H, H.symm ▸ Hs.map_zero⟩ end ring_anti_equiv /-- A ring involution -/ structure ring_invo [ring R] := (to_fun : R → R) [anti_hom : is_ring_anti_hom to_fun] (to_fun_to_fun : ∀ x, to_fun (to_fun x) = x) open ring_invo namespace ring_invo variables {R} [ring R] (Hi : ring_invo R) (x y : R) instance : has_coe_to_fun (ring_invo R) := ⟨_, λ Hi, Hi.to_fun⟩ instance : is_ring_anti_hom Hi := Hi.anti_hom def to_ring_anti_equiv : ring_anti_equiv R R := { inv_fun := Hi, left_inv := Hi.to_fun_to_fun, right_inv := Hi.to_fun_to_fun, .. Hi } lemma map_add : Hi (x + y) = Hi x + Hi y := Hi.to_ring_anti_equiv.map_add x y lemma map_zero : Hi 0 = 0 := Hi.to_ring_anti_equiv.map_zero lemma map_neg : Hi (-x) = -Hi x := Hi.to_ring_anti_equiv.map_neg x lemma map_sub : Hi (x - y) = Hi x - Hi y := Hi.to_ring_anti_equiv.map_sub x y lemma map_mul : Hi (x * y) = Hi y * Hi x := Hi.to_ring_anti_equiv.map_mul x y lemma map_one : Hi 1 = 1 := Hi.to_ring_anti_equiv.map_one lemma map_neg_one : Hi (-1) = -1 := Hi.to_ring_anti_equiv.map_neg_one lemma bijective : function.bijective Hi := Hi.to_ring_anti_equiv.bijective lemma map_zero_iff {x : R} : Hi x = 0 ↔ x = 0 := Hi.to_ring_anti_equiv.map_zero_iff end ring_invo section comm_ring variables (R F) [comm_ring R] [comm_ring F] protected def ring_invo.id : ring_invo R := { anti_hom := ⟨rfl, mul_comm, λ _ _, rfl⟩, to_fun_to_fun := λ _, rfl, .. equiv.refl R } protected def ring_anti_equiv.refl : ring_anti_equiv R R := (ring_invo.id R).to_ring_anti_equiv variables {R F} theorem comm_ring.hom_to_anti_hom (f : R → F) [is_ring_hom f] : is_ring_anti_hom f := { map_add := λ _ _, is_ring_hom.map_add f, map_mul := λ _ _, by rw [is_ring_hom.map_mul f, mul_comm], map_one := is_ring_hom.map_one f } theorem comm_ring.anti_hom_to_hom (f : R → F) [is_ring_anti_hom f] : is_ring_hom f := { map_add := λ _ _, is_ring_anti_hom.map_add f, map_mul := λ _ _, by rw [is_ring_anti_hom.map_mul f, mul_comm], map_one := is_ring_anti_hom.map_one f } def comm_ring.equiv_to_anti_equiv (Hs : R ≃+* F) : ring_anti_equiv R F := { anti_hom := comm_ring.hom_to_anti_hom Hs, .. Hs } def comm_ring.anti_equiv_to_equiv (Hs : ring_anti_equiv R F) : R ≃+* F := @ring_equiv.of' _ _ _ _ Hs.to_equiv (comm_ring.anti_hom_to_hom Hs) end comm_ring
9736e14fe341e31f0ad516a0a67183dfc2d79666
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/algebra/order/field.lean
58445c3027a37c7655566edf5e41f177f4d24287
[ "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
16,443
lean
/- Copyright (c) 2022 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson, Devon Tuma, Eric Rodriguez, Oliver Nash -/ import tactic.positivity import topology.algebra.order.basic import topology.algebra.field /-! # Topologies on linear ordered fields -/ open set filter topological_space open function open order_dual (to_dual of_dual) open_locale topological_space classical filter variables {α β : Type*} variables [linear_ordered_field α] [topological_space α] [order_topology α] variables {l : filter β} {f g : β → α} section continuous_mul lemma mul_tendsto_nhds_zero_right (x : α) : tendsto (uncurry ((*) : α → α → α)) (𝓝 0 ×ᶠ 𝓝 x) $ 𝓝 0 := begin have hx : 0 < 2 * (1 + |x|) := by positivity, rw ((nhds_basis_zero_abs_sub_lt α).prod $ nhds_basis_abs_sub_lt x).tendsto_iff (nhds_basis_zero_abs_sub_lt α), refine λ ε ε_pos, ⟨(ε/(2 * (1 + |x|)), 1), ⟨div_pos ε_pos hx, zero_lt_one⟩, _⟩, suffices : ∀ (a b : α), |a| < ε / (2 * (1 + |x|)) → |b - x| < 1 → |a| * |b| < ε, by simpa only [and_imp, prod.forall, mem_prod, ← abs_mul], intros a b h h', refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left _ (abs_nonneg a)) ((lt_div_iff hx).1 h), calc |b| = |(b - x) + x| : by rw sub_add_cancel b x ... ≤ |b - x| + |x| : abs_add (b - x) x ... ≤ 2 * (1 + |x|) : by linarith, end lemma mul_tendsto_nhds_zero_left (x : α) : tendsto (uncurry ((*) : α → α → α)) (𝓝 x ×ᶠ 𝓝 0) $ 𝓝 0 := begin intros s hs, have := mul_tendsto_nhds_zero_right x hs, rw [filter.mem_map, mem_prod_iff] at this ⊢, obtain ⟨U, hU, V, hV, h⟩ := this, exact ⟨V, hV, U, hU, λ y hy, ((mul_comm y.2 y.1) ▸ h (⟨hy.2, hy.1⟩ : (prod.mk y.2 y.1) ∈ U ×ˢ V) : y.1 * y.2 ∈ s)⟩, end lemma nhds_eq_map_mul_left_nhds_one {x₀ : α} (hx₀ : x₀ ≠ 0) : 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1) := begin have hx₀' : 0 < |x₀| := abs_pos.2 hx₀, refine filter.ext (λ t, _), simp only [exists_prop, set_of_subset_set_of, (nhds_basis_abs_sub_lt x₀).mem_iff, (nhds_basis_abs_sub_lt (1 : α)).mem_iff, filter.mem_map'], refine ⟨λ h, _, λ h, _⟩, { obtain ⟨i, hi, hit⟩ := h, refine ⟨i / (|x₀|), div_pos hi (abs_pos.2 hx₀), λ x hx, hit _⟩, calc |x₀ * x - x₀| = |x₀ * (x - 1)| : congr_arg abs (by ring_nf) ... = |x₀| * |x - 1| : abs_mul x₀ (x - 1) ... < |x₀| * (i / |x₀|) : mul_lt_mul' le_rfl hx (by positivity) (abs_pos.2 hx₀) ... = |x₀| * i / |x₀| : by ring ... = i : mul_div_cancel_left i (λ h, hx₀ (abs_eq_zero.1 h)) }, { obtain ⟨i, hi, hit⟩ := h, refine ⟨i * |x₀|, mul_pos hi (abs_pos.2 hx₀), λ x hx, _⟩, have : |x / x₀ - 1| < i, calc |x / x₀ - 1| = |x / x₀ - x₀ / x₀| : (by rw div_self hx₀) ... = |(x - x₀) / x₀| : congr_arg abs (sub_div x x₀ x₀).symm ... = |x - x₀| / |x₀| : abs_div (x - x₀) x₀ ... < i * |x₀| / |x₀| : div_lt_div_of_lt (abs_pos.2 hx₀) hx ... = i : by rw [← mul_div_assoc', div_self (ne_of_lt $ abs_pos.2 hx₀).symm, mul_one], specialize hit (x / x₀) this, rwa [mul_div_assoc', mul_div_cancel_left x hx₀] at hit } end lemma nhds_eq_map_mul_right_nhds_one {x₀ : α} (hx₀ : x₀ ≠ 0) : 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1) := by simp_rw [mul_comm _ x₀, nhds_eq_map_mul_left_nhds_one hx₀] lemma mul_tendsto_nhds_one_nhds_one : tendsto (uncurry ((*) : α → α → α)) (𝓝 1 ×ᶠ 𝓝 1) $ 𝓝 1 := begin rw ((nhds_basis_Ioo_pos (1 : α)).prod $ nhds_basis_Ioo_pos (1 : α)).tendsto_iff (nhds_basis_Ioo_pos_of_pos (zero_lt_one : (0 : α) < 1)), intros ε hε, have hε' : 0 ≤ 1 - ε / 4 := by linarith, have ε_pos : 0 < ε / 4 := by linarith, have ε_pos' : 0 < ε / 2 := by linarith, simp only [and_imp, prod.forall, mem_Ioo, function.uncurry_apply_pair, mem_prod, prod.exists], refine ⟨ε/4, ε/4, ⟨ε_pos, ε_pos⟩, λ a b ha ha' hb hb', _⟩, have ha0 : 0 ≤ a := le_trans hε' (le_of_lt ha), have hb0 : 0 ≤ b := le_trans hε' (le_of_lt hb), refine ⟨lt_of_le_of_lt _ (mul_lt_mul'' ha hb hε' hε'), lt_of_lt_of_le (mul_lt_mul'' ha' hb' ha0 hb0) _⟩, { calc 1 - ε = 1 - ε / 2 - ε/2 : by ring_nf ... ≤ 1 - ε/2 - ε/2 + (ε/2)*(ε/2) : le_add_of_nonneg_right (by positivity) ... = (1 - ε/2) * (1 - ε/2) : by ring_nf ... ≤ (1 - ε/4) * (1 - ε/4) : mul_le_mul (by linarith) (by linarith) (by linarith) hε' }, { calc (1 + ε/4) * (1 + ε/4) = 1 + ε/2 + (ε/4)*(ε/4) : by ring_nf ... = 1 + ε/2 + (ε * ε) / 16 : by ring_nf ... ≤ 1 + ε/2 + ε/2 : add_le_add_left (div_le_div (le_of_lt hε.1) (le_trans ((mul_le_mul_left hε.1).2 hε.2) (le_of_eq $ mul_one ε)) zero_lt_two (by linarith)) (1 + ε/2) ... ≤ 1 + ε : by ring_nf } end @[priority 100] -- see Note [lower instance priority] instance linear_ordered_field.has_continuous_mul : has_continuous_mul α := ⟨begin rw continuous_iff_continuous_at, rintro ⟨x₀, y₀⟩, by_cases hx₀ : x₀ = 0, { rw [hx₀, continuous_at, zero_mul, nhds_prod_eq], exact mul_tendsto_nhds_zero_right y₀ }, by_cases hy₀ : y₀ = 0, { rw [hy₀, continuous_at, mul_zero, nhds_prod_eq], exact mul_tendsto_nhds_zero_left x₀ }, have hxy : x₀ * y₀ ≠ 0 := mul_ne_zero hx₀ hy₀, have key : (λ p : α × α, x₀ * p.1 * (p.2 * y₀)) = ((λ x, x₀*x) ∘ (λ x, x*y₀)) ∘ (uncurry (*)), { ext p, simp [uncurry, mul_assoc] }, have key₂ : (λ x, x₀*x) ∘ (λ x, y₀*x) = λ x, (x₀ *y₀)*x, { ext x, simp }, calc map (uncurry (*)) (𝓝 (x₀, y₀)) = map (uncurry (*)) (𝓝 x₀ ×ᶠ 𝓝 y₀) : by rw nhds_prod_eq ... = map (λ (p : α × α), x₀ * p.1 * (p.2 * y₀)) ((𝓝 1) ×ᶠ (𝓝 1)) : by rw [uncurry, nhds_eq_map_mul_left_nhds_one hx₀, nhds_eq_map_mul_right_nhds_one hy₀, prod_map_map_eq, filter.map_map] ... = map ((λ x, x₀ * x) ∘ λ x, x * y₀) (map (uncurry (*)) (𝓝 1 ×ᶠ 𝓝 1)) : by rw [key, ← filter.map_map] ... ≤ map ((λ (x : α), x₀ * x) ∘ λ x, x * y₀) (𝓝 1) : map_mono (mul_tendsto_nhds_one_nhds_one) ... = 𝓝 (x₀*y₀) : by rw [← filter.map_map, ← nhds_eq_map_mul_right_nhds_one hy₀, nhds_eq_map_mul_left_nhds_one hy₀, filter.map_map, key₂, ← nhds_eq_map_mul_left_nhds_one hxy], end⟩ end continuous_mul /-- In a linearly ordered field with the order topology, if `f` tends to `at_top` and `g` tends to a positive constant `C` then `f * g` tends to `at_top`. -/ lemma filter.tendsto.at_top_mul {C : α} (hC : 0 < C) (hf : tendsto f l at_top) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, (f x * g x)) l at_top := begin refine tendsto_at_top_mono' _ _ (hf.at_top_mul_const (half_pos hC)), filter_upwards [hg.eventually (lt_mem_nhds (half_lt_self hC)), hf.eventually (eventually_ge_at_top 0)] with x hg hf using mul_le_mul_of_nonneg_left hg.le hf, end /-- In a linearly ordered field with the order topology, if `f` tends to a positive constant `C` and `g` tends to `at_top` then `f * g` tends to `at_top`. -/ lemma filter.tendsto.mul_at_top {C : α} (hC : 0 < C) (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_top) : tendsto (λ x, (f x * g x)) l at_top := by simpa only [mul_comm] using hg.at_top_mul hC hf /-- In a linearly ordered field with the order topology, if `f` tends to `at_top` and `g` tends to a negative constant `C` then `f * g` tends to `at_bot`. -/ lemma filter.tendsto.at_top_mul_neg {C : α} (hC : C < 0) (hf : tendsto f l at_top) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, (f x * g x)) l at_bot := by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg] using tendsto_neg_at_top_at_bot.comp (hf.at_top_mul (neg_pos.2 hC) hg.neg) /-- In a linearly ordered field with the order topology, if `f` tends to a negative constant `C` and `g` tends to `at_top` then `f * g` tends to `at_bot`. -/ lemma filter.tendsto.neg_mul_at_top {C : α} (hC : C < 0) (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_top) : tendsto (λ x, (f x * g x)) l at_bot := by simpa only [mul_comm] using hg.at_top_mul_neg hC hf /-- In a linearly ordered field with the order topology, if `f` tends to `at_bot` and `g` tends to a positive constant `C` then `f * g` tends to `at_bot`. -/ lemma filter.tendsto.at_bot_mul {C : α} (hC : 0 < C) (hf : tendsto f l at_bot) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, (f x * g x)) l at_bot := by simpa [(∘)] using tendsto_neg_at_top_at_bot.comp ((tendsto_neg_at_bot_at_top.comp hf).at_top_mul hC hg) /-- In a linearly ordered field with the order topology, if `f` tends to `at_bot` and `g` tends to a negative constant `C` then `f * g` tends to `at_top`. -/ lemma filter.tendsto.at_bot_mul_neg {C : α} (hC : C < 0) (hf : tendsto f l at_bot) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, (f x * g x)) l at_top := by simpa [(∘)] using tendsto_neg_at_bot_at_top.comp ((tendsto_neg_at_bot_at_top.comp hf).at_top_mul_neg hC hg) /-- In a linearly ordered field with the order topology, if `f` tends to a positive constant `C` and `g` tends to `at_bot` then `f * g` tends to `at_bot`. -/ lemma filter.tendsto.mul_at_bot {C : α} (hC : 0 < C) (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_bot) : tendsto (λ x, (f x * g x)) l at_bot := by simpa only [mul_comm] using hg.at_bot_mul hC hf /-- In a linearly ordered field with the order topology, if `f` tends to a negative constant `C` and `g` tends to `at_bot` then `f * g` tends to `at_top`. -/ lemma filter.tendsto.neg_mul_at_bot {C : α} (hC : C < 0) (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_bot) : tendsto (λ x, (f x * g x)) l at_top := by simpa only [mul_comm] using hg.at_bot_mul_neg hC hf /-- The function `x ↦ x⁻¹` tends to `+∞` on the right of `0`. -/ lemma tendsto_inv_zero_at_top : tendsto (λx:α, x⁻¹) (𝓝[>] (0:α)) at_top := begin refine (at_top_basis' 1).tendsto_right_iff.2 (λ b hb, _), have hb' : 0 < b := by positivity, filter_upwards [Ioc_mem_nhds_within_Ioi ⟨le_rfl, inv_pos.2 hb'⟩] with x hx using (le_inv hx.1 hb').1 hx.2, end /-- The function `r ↦ r⁻¹` tends to `0` on the right as `r → +∞`. -/ lemma tendsto_inv_at_top_zero' : tendsto (λr:α, r⁻¹) at_top (𝓝[>] (0:α)) := begin refine (has_basis.tendsto_iff at_top_basis ⟨λ s, mem_nhds_within_Ioi_iff_exists_Ioc_subset⟩).2 _, refine λ b hb, ⟨b⁻¹, trivial, λ x hx, _⟩, have : 0 < x := lt_of_lt_of_le (inv_pos.2 hb) hx, exact ⟨inv_pos.2 this, (inv_le this hb).2 hx⟩ end lemma tendsto_inv_at_top_zero : tendsto (λr:α, r⁻¹) at_top (𝓝 0) := tendsto_inv_at_top_zero'.mono_right inf_le_left lemma filter.tendsto.div_at_top [has_continuous_mul α] {f g : β → α} {l : filter β} {a : α} (h : tendsto f l (𝓝 a)) (hg : tendsto g l at_top) : tendsto (λ x, f x / g x) l (𝓝 0) := by { simp only [div_eq_mul_inv], exact mul_zero a ▸ h.mul (tendsto_inv_at_top_zero.comp hg) } lemma filter.tendsto.inv_tendsto_at_top (h : tendsto f l at_top) : tendsto (f⁻¹) l (𝓝 0) := tendsto_inv_at_top_zero.comp h lemma filter.tendsto.inv_tendsto_zero (h : tendsto f l (𝓝[>] 0)) : tendsto (f⁻¹) l at_top := tendsto_inv_zero_at_top.comp h /-- The function `x^(-n)` tends to `0` at `+∞` for any positive natural `n`. A version for positive real powers exists as `tendsto_rpow_neg_at_top`. -/ lemma tendsto_pow_neg_at_top {n : ℕ} (hn : n ≠ 0) : tendsto (λ x : α, x ^ (-(n:ℤ))) at_top (𝓝 0) := by simpa only [zpow_neg, zpow_coe_nat] using (@tendsto_pow_at_top α _ _ hn).inv_tendsto_at_top lemma tendsto_zpow_at_top_zero {n : ℤ} (hn : n < 0) : tendsto (λ x : α, x^n) at_top (𝓝 0) := begin lift -n to ℕ using le_of_lt (neg_pos.mpr hn) with N, rw [← neg_pos, ← h, nat.cast_pos] at hn, simpa only [h, neg_neg] using tendsto_pow_neg_at_top hn.ne' end lemma tendsto_const_mul_zpow_at_top_zero {n : ℤ} {c : α} (hn : n < 0) : tendsto (λ x, c * x ^ n) at_top (𝓝 0) := (mul_zero c) ▸ (filter.tendsto.const_mul c (tendsto_zpow_at_top_zero hn)) lemma tendsto_const_mul_pow_nhds_iff' {n : ℕ} {c d : α} : tendsto (λ x : α, c * x ^ n) at_top (𝓝 d) ↔ (c = 0 ∨ n = 0) ∧ c = d := begin rcases eq_or_ne n 0 with (rfl|hn), { simp [tendsto_const_nhds_iff] }, rcases lt_trichotomy c 0 with hc|rfl|hc, { have := tendsto_const_mul_pow_at_bot_iff.2 ⟨hn, hc⟩, simp [not_tendsto_nhds_of_tendsto_at_bot this, hc.ne, hn] }, { simp [tendsto_const_nhds_iff] }, { have := tendsto_const_mul_pow_at_top_iff.2 ⟨hn, hc⟩, simp [not_tendsto_nhds_of_tendsto_at_top this, hc.ne', hn] } end lemma tendsto_const_mul_pow_nhds_iff {n : ℕ} {c d : α} (hc : c ≠ 0) : tendsto (λ x : α, c * x ^ n) at_top (𝓝 d) ↔ n = 0 ∧ c = d := by simp [tendsto_const_mul_pow_nhds_iff', hc] lemma tendsto_const_mul_zpow_at_top_nhds_iff {n : ℤ} {c d : α} (hc : c ≠ 0) : tendsto (λ x : α, c * x ^ n) at_top (𝓝 d) ↔ (n = 0 ∧ c = d) ∨ (n < 0 ∧ d = 0) := begin refine ⟨λ h, _, λ h, _⟩, { by_cases hn : 0 ≤ n, { lift n to ℕ using hn, simp only [zpow_coe_nat] at h, rw [tendsto_const_mul_pow_nhds_iff hc, ← int.coe_nat_eq_zero] at h, exact or.inl h }, { rw not_le at hn, refine or.inr ⟨hn, tendsto_nhds_unique h (tendsto_const_mul_zpow_at_top_zero hn)⟩ } }, { cases h, { simp only [h.left, h.right, zpow_zero, mul_one], exact tendsto_const_nhds }, { exact h.2.symm ▸ tendsto_const_mul_zpow_at_top_zero h.1} } end -- TODO: With a different proof, this could be possibly generalised to only require a -- `linear_ordered_semifield` instance, which would also remove the need for the -- `nnreal` instance of `has_continuous_inv₀`. @[priority 100] -- see Note [lower instance priority] instance linear_ordered_field.to_topological_division_ring : topological_division_ring α := { continuous_at_inv₀ := begin suffices : ∀ {x : α}, 0 < x → continuous_at has_inv.inv x, { intros x hx, cases hx.symm.lt_or_lt, { exact this h }, convert (this $ neg_pos.mpr h).neg.comp continuous_neg.continuous_at, ext, simp [neg_inv] }, intros t ht, rw [continuous_at, (nhds_basis_Ioo_pos t).tendsto_iff $ nhds_basis_Ioo_pos_of_pos $ inv_pos.2 ht], rintros ε ⟨hε : ε > 0, hεt : ε ≤ t⁻¹⟩, refine ⟨min (t ^ 2 * ε / 2) (t / 2), by positivity, λ x h, _⟩, have hx : t / 2 < x, { rw [set.mem_Ioo, sub_lt_comm, lt_min_iff] at h, nlinarith }, have hx' : 0 < x := (half_pos ht).trans hx, have aux : 0 < 2 / t ^ 2 := by positivity, rw [set.mem_Ioo, ←sub_lt_iff_lt_add', sub_lt_comm, ←abs_sub_lt_iff] at h ⊢, rw [inv_sub_inv ht.ne' hx'.ne', abs_div, div_eq_mul_inv], suffices : |t * x|⁻¹ < 2 / t ^ 2, { rw [←abs_neg, neg_sub], refine (mul_lt_mul'' h this (by positivity) (by positivity)).trans_le _, rw [mul_comm, mul_min_of_nonneg _ _ aux.le], apply min_le_of_left_le, rw [←mul_div, ←mul_assoc, div_mul_cancel _ (sq_pos_of_pos ht).ne', mul_div_cancel' ε two_ne_zero] }, refine inv_lt_of_inv_lt aux _, rw [inv_div, abs_of_pos $ mul_pos ht hx', sq, ←mul_div_assoc'], exact mul_lt_mul_of_pos_left hx ht end } lemma nhds_within_pos_comap_mul_left {x : α} (hx : 0 < x) : comap (λ ε, x * ε) (𝓝[>] 0) = 𝓝[>] 0 := begin suffices : ∀ {x : α} (hx : 0 < x), 𝓝[>] 0 ≤ comap (λ ε, x * ε) (𝓝[>] 0), { refine le_antisymm _ (this hx), have hr : 𝓝[>] (0 : α) = ((𝓝[>] (0 : α)).comap (λ ε, x⁻¹ * ε)).comap (λ ε, x * ε), { simp [comap_comap, inv_mul_cancel hx.ne.symm, comap_id, one_mul_eq_id], }, conv_rhs { rw hr, }, rw comap_le_comap_iff (by convert univ_mem; exact (mul_left_surjective₀ hx.ne.symm).range_eq), exact this (inv_pos.mpr hx), }, intros x hx, convert nhds_within_le_comap (continuous_mul_left x).continuous_within_at, { exact (mul_zero _).symm, }, { rw image_const_mul_Ioi_zero hx, }, end lemma eventually_nhds_within_pos_mul_left {x : α} (hx : 0 < x) {p : α → Prop} (h : ∀ᶠ ε in 𝓝[>] 0, p ε) : ∀ᶠ ε in 𝓝[>] 0, p (x * ε) := begin convert h.comap (λ ε, x * ε), exact (nhds_within_pos_comap_mul_left hx).symm, end
110ec393a9bc2dd7eb32ac31c4fec8a95ede5c39
6094e25ea0b7699e642463b48e51b2ead6ddc23f
/library/data/nat/div.lean
200347eb07cd616e8b5722c78ad196cda9311170
[ "Apache-2.0" ]
permissive
gbaz/lean
a7835c4e3006fbbb079e8f8ffe18aacc45adebfb
a501c308be3acaa50a2c0610ce2e0d71becf8032
refs/heads/master
1,611,198,791,433
1,451,339,111,000
1,451,339,111,000
48,713,797
0
0
null
1,451,338,939,000
1,451,338,939,000
null
UTF-8
Lean
false
false
26,193
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 Definitions and properties of div and mod. Much of the development follows Isabelle's library. -/ import data.nat.sub open eq.ops well_founded decidable prod namespace nat /- div -/ -- auxiliary lemma used to justify div private definition div_rec_lemma {x y : nat} : 0 < y ∧ y ≤ x → x - y < x := and.rec (λ ypos ylex, sub_lt (lt_of_lt_of_le ypos ylex) ypos) private definition div.F (x : nat) (f : Π x₁, x₁ < x → nat → nat) (y : nat) : nat := if H : 0 < y ∧ y ≤ x then f (x - y) (div_rec_lemma H) y + 1 else zero protected definition div := fix div.F definition nat_has_divide [reducible] [instance] [priority nat.prio] : has_div nat := has_div.mk nat.div theorem div_def (x y : nat) : div x y = if 0 < y ∧ y ≤ x then div (x - y) y + 1 else 0 := congr_fun (fix_eq div.F x) y protected theorem div_zero (a : ℕ) : a / 0 = 0 := div_def a 0 ⬝ if_neg (!not_and_of_not_left (lt.irrefl 0)) theorem div_eq_zero_of_lt {a b : ℕ} (h : a < b) : a / b = 0 := div_def a b ⬝ if_neg (!not_and_of_not_right (not_le_of_gt h)) protected theorem zero_div (b : ℕ) : 0 / b = 0 := div_def 0 b ⬝ if_neg (and.rec not_le_of_gt) theorem div_eq_succ_sub_div {a b : ℕ} (h₁ : b > 0) (h₂ : a ≥ b) : a / b = succ ((a - b) / b) := div_def a b ⬝ if_pos (and.intro h₁ h₂) theorem add_div_self (x : ℕ) {z : ℕ} (H : z > 0) : (x + z) / z = succ (x / z) := calc (x + z) / z = if 0 < z ∧ z ≤ x + z then (x + z - z) / z + 1 else 0 : !div_def ... = (x + z - z) / z + 1 : if_pos (and.intro H (le_add_left z x)) ... = succ (x / z) : {!nat.add_sub_cancel} theorem add_div_self_left {x : ℕ} (z : ℕ) (H : x > 0) : (x + z) / x = succ (z / x) := !add.comm ▸ !add_div_self H theorem add_mul_div_self {x y z : ℕ} (H : z > 0) : (x + y * z) / z = x / z + y := nat.induction_on y (calc (x + 0 * z) / z = (x + 0) / z : zero_mul ... = x / z : add_zero ... = x / z + 0 : add_zero) (take y, assume IH : (x + y * z) / z = x / z + y, calc (x + succ y * z) / z = (x + (y * z + z)) / z : succ_mul ... = (x + y * z + z) / z : add.assoc ... = succ ((x + y * z) / z) : !add_div_self H ... = succ (x / z + y) : IH) theorem add_mul_div_self_left (x z : ℕ) {y : ℕ} (H : y > 0) : (x + y * z) / y = x / y + z := !mul.comm ▸ add_mul_div_self H protected theorem mul_div_cancel (m : ℕ) {n : ℕ} (H : n > 0) : m * n / n = m := calc m * n / n = (0 + m * n) / n : zero_add ... = 0 / n + m : add_mul_div_self H ... = 0 + m : nat.zero_div ... = m : zero_add protected theorem mul_div_cancel_left {m : ℕ} (n : ℕ) (H : m > 0) : m * n / m = n := !mul.comm ▸ !nat.mul_div_cancel H /- mod -/ private definition mod.F (x : nat) (f : Π x₁, x₁ < x → nat → nat) (y : nat) : nat := if H : 0 < y ∧ y ≤ x then f (x - y) (div_rec_lemma H) y else x protected definition mod := fix mod.F definition nat_has_mod [reducible] [instance] [priority nat.prio] : has_mod nat := has_mod.mk nat.mod notation [priority nat.prio] a ≡ b `[mod `:0 c:0 `]` := a % c = b % c theorem mod_def (x y : nat) : mod x y = if 0 < y ∧ y ≤ x then mod (x - y) y else x := congr_fun (fix_eq mod.F x) y theorem mod_zero (a : ℕ) : a % 0 = a := mod_def a 0 ⬝ if_neg (!not_and_of_not_left (lt.irrefl 0)) theorem mod_eq_of_lt {a b : ℕ} (h : a < b) : a % b = a := mod_def a b ⬝ if_neg (!not_and_of_not_right (not_le_of_gt h)) theorem zero_mod (b : ℕ) : 0 % b = 0 := mod_def 0 b ⬝ if_neg (λ h, and.rec_on h (λ l r, absurd (lt_of_lt_of_le l r) (lt.irrefl 0))) theorem mod_eq_sub_mod {a b : ℕ} (h₁ : b > 0) (h₂ : a ≥ b) : a % b = (a - b) % b := mod_def a b ⬝ if_pos (and.intro h₁ h₂) theorem add_mod_self (x z : ℕ) : (x + z) % z = x % z := by_cases_zero_pos z (by rewrite add_zero) (take z, assume H : z > 0, calc (x + z) % z = if 0 < z ∧ z ≤ x + z then (x + z - z) % z else _ : mod_def ... = (x + z - z) % z : if_pos (and.intro H (le_add_left z x)) ... = x % z : nat.add_sub_cancel) theorem add_mod_self_left (x z : ℕ) : (x + z) % x = z % x := !add.comm ▸ !add_mod_self theorem add_mul_mod_self (x y z : ℕ) : (x + y * z) % z = x % z := nat.induction_on y (calc (x + 0 * z) % z = (x + 0) % z : zero_mul ... = x % z : add_zero) (take y, assume IH : (x + y * z) % z = x % z, calc (x + succ y * z) % z = (x + (y * z + z)) % z : succ_mul ... = (x + y * z + z) % z : add.assoc ... = (x + y * z) % z : !add_mod_self ... = x % z : IH) theorem add_mul_mod_self_left (x y z : ℕ) : (x + y * z) % y = x % y := !mul.comm ▸ !add_mul_mod_self theorem mul_mod_left (m n : ℕ) : (m * n) % n = 0 := by rewrite [-zero_add (m * n), add_mul_mod_self, zero_mod] theorem mul_mod_right (m n : ℕ) : (m * n) % m = 0 := !mul.comm ▸ !mul_mod_left theorem mod_lt (x : ℕ) {y : ℕ} (H : y > 0) : x % y < y := nat.case_strong_induction_on x (show 0 % y < y, from !zero_mod⁻¹ ▸ H) (take x, assume IH : ∀x', x' ≤ x → x' % y < y, show succ x % y < y, from by_cases -- (succ x < y) (assume H1 : succ x < y, have succ x % y = succ x, from mod_eq_of_lt H1, show succ x % y < y, from this⁻¹ ▸ H1) (assume H1 : ¬ succ x < y, have y ≤ succ x, from le_of_not_gt H1, have h : succ x % y = (succ x - y) % y, from mod_eq_sub_mod H this, have succ x - y < succ x, from sub_lt !succ_pos H, have succ x - y ≤ x, from le_of_lt_succ this, show succ x % y < y, from h⁻¹ ▸ IH _ this)) theorem mod_one (n : ℕ) : n % 1 = 0 := have H1 : n % 1 < 1, from !mod_lt !succ_pos, eq_zero_of_le_zero (le_of_lt_succ H1) /- properties of div and mod -/ -- the quotient - remainder theorem theorem eq_div_mul_add_mod (x y : ℕ) : x = x / y * y + x % y := begin eapply by_cases_zero_pos y, show x = x / 0 * 0 + x % 0, from (calc x / 0 * 0 + x % 0 = 0 + x % 0 : mul_zero ... = x % 0 : zero_add ... = x : mod_zero)⁻¹, intro y H, show x = x / y * y + x % y, begin eapply nat.case_strong_induction_on x, show 0 = (0 / y) * y + 0 % y, by rewrite [zero_mod, add_zero, nat.zero_div, zero_mul], intro x IH, show succ x = succ x / y * y + succ x % y, from if H1 : succ x < y then assert H2 : succ x / y = 0, from div_eq_zero_of_lt H1, assert H3 : succ x % y = succ x, from mod_eq_of_lt H1, begin rewrite [H2, H3, zero_mul, zero_add] end else have H2 : y ≤ succ x, from le_of_not_gt H1, assert H3 : succ x / y = succ ((succ x - y) / y), from div_eq_succ_sub_div H H2, assert H4 : succ x % y = (succ x - y) % y, from mod_eq_sub_mod H H2, have H5 : succ x - y < succ x, from sub_lt !succ_pos H, assert H6 : succ x - y ≤ x, from le_of_lt_succ H5, (calc succ x / y * y + succ x % y = succ ((succ x - y) / y) * y + succ x % y : by rewrite H3 ... = ((succ x - y) / y) * y + y + succ x % y : by rewrite succ_mul ... = ((succ x - y) / y) * y + y + (succ x - y) % y : by rewrite H4 ... = ((succ x - y) / y) * y + (succ x - y) % y + y : add.right_comm ... = succ x - y + y : by rewrite -(IH _ H6) ... = succ x : nat.sub_add_cancel H2)⁻¹ end end theorem mod_eq_sub_div_mul (x y : ℕ) : x % y = x - x / y * y := nat.eq_sub_of_add_eq (!add.comm ▸ !eq_div_mul_add_mod)⁻¹ theorem mod_add_mod (m n k : ℕ) : (m % n + k) % n = (m + k) % n := by rewrite [eq_div_mul_add_mod m n at {2}, add.assoc, add.comm (m / n * n), add_mul_mod_self] theorem add_mod_mod (m n k : ℕ) : (m + n % k) % k = (m + n) % k := by rewrite [add.comm, mod_add_mod, add.comm] theorem add_mod_eq_add_mod_right {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rewrite [-mod_add_mod, -mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rewrite [add.comm, add_mod_eq_add_mod_right _ H, add.comm] theorem mod_eq_mod_of_add_mod_eq_add_mod_right {m n k i : ℕ} : (m + i) % n = (k + i) % n → m % n = k % n := by_cases_zero_pos n (by rewrite [*mod_zero]; apply eq_of_add_eq_add_right) (take n, assume npos : n > 0, assume H1 : (m + i) % n = (k + i) % n, have H2 : (m + i % n) % n = (k + i % n) % n, by rewrite [*add_mod_mod, H1], assert H3 : (m + i % n + (n - i % n)) % n = (k + i % n + (n - i % n)) % n, from add_mod_eq_add_mod_right _ H2, begin revert H3, rewrite [*add.assoc, add_sub_of_le (le_of_lt (!mod_lt npos)), *add_mod_self], intros, assumption end) theorem mod_eq_mod_of_add_mod_eq_add_mod_left {m n k i : ℕ} : (i + m) % n = (i + k) % n → m % n = k % n := by rewrite [add.comm i m, add.comm i k]; apply mod_eq_mod_of_add_mod_eq_add_mod_right theorem mod_le {x y : ℕ} : x % y ≤ x := !eq_div_mul_add_mod⁻¹ ▸ !le_add_left theorem eq_remainder {q1 r1 q2 r2 y : ℕ} (H1 : r1 < y) (H2 : r2 < y) (H3 : q1 * y + r1 = q2 * y + r2) : r1 = r2 := calc r1 = r1 % y : mod_eq_of_lt H1 ... = (r1 + q1 * y) % y : !add_mul_mod_self⁻¹ ... = (q1 * y + r1) % y : add.comm ... = (r2 + q2 * y) % y : by rewrite [H3, add.comm] ... = r2 % y : !add_mul_mod_self ... = r2 : mod_eq_of_lt H2 theorem eq_quotient {q1 r1 q2 r2 y : ℕ} (H1 : r1 < y) (H2 : r2 < y) (H3 : q1 * y + r1 = q2 * y + r2) : q1 = q2 := have H4 : q1 * y + r2 = q2 * y + r2, from (eq_remainder H1 H2 H3) ▸ H3, have H5 : q1 * y = q2 * y, from add.right_cancel H4, have H6 : y > 0, from lt_of_le_of_lt !zero_le H1, show q1 = q2, from eq_of_mul_eq_mul_right H6 H5 protected theorem mul_div_mul_left {z : ℕ} (x y : ℕ) (zpos : z > 0) : (z * x) / (z * y) = x / y := if H : y = 0 then by rewrite [H, mul_zero, *nat.div_zero] else have ypos : y > 0, from pos_of_ne_zero H, have zypos : z * y > 0, from mul_pos zpos ypos, have H1 : (z * x) % (z * y) < z * y, from !mod_lt zypos, have H2 : z * (x % y) < z * y, from mul_lt_mul_of_pos_left (!mod_lt ypos) zpos, eq_quotient H1 H2 (calc ((z * x) / (z * y)) * (z * y) + (z * x) % (z * y) = z * x : eq_div_mul_add_mod ... = z * (x / y * y + x % y) : eq_div_mul_add_mod ... = z * (x / y * y) + z * (x % y) : left_distrib ... = (x / y) * (z * y) + z * (x % y) : mul.left_comm) protected theorem mul_div_mul_right {x z y : ℕ} (zpos : z > 0) : (x * z) / (y * z) = x / y := !mul.comm ▸ !mul.comm ▸ !nat.mul_div_mul_left zpos theorem mul_mod_mul_left (z x y : ℕ) : (z * x) % (z * y) = z * (x % y) := or.elim (eq_zero_or_pos z) (assume H : z = 0, H⁻¹ ▸ calc (0 * x) % (z * y) = 0 % (z * y) : zero_mul ... = 0 : zero_mod ... = 0 * (x % y) : zero_mul) (assume zpos : z > 0, or.elim (eq_zero_or_pos y) (assume H : y = 0, by rewrite [H, mul_zero, *mod_zero]) (assume ypos : y > 0, have zypos : z * y > 0, from mul_pos zpos ypos, have H1 : (z * x) % (z * y) < z * y, from !mod_lt zypos, have H2 : z * (x % y) < z * y, from mul_lt_mul_of_pos_left (!mod_lt ypos) zpos, eq_remainder H1 H2 (calc ((z * x) / (z * y)) * (z * y) + (z * x) % (z * y) = z * x : eq_div_mul_add_mod ... = z * (x / y * y + x % y) : eq_div_mul_add_mod ... = z * (x / y * y) + z * (x % y) : left_distrib ... = (x / y) * (z * y) + z * (x % y) : mul.left_comm))) theorem mul_mod_mul_right (x z y : ℕ) : (x * z) % (y * z) = (x % y) * z := mul.comm z x ▸ mul.comm z y ▸ !mul.comm ▸ !mul_mod_mul_left theorem mod_self (n : ℕ) : n % n = 0 := nat.cases_on n (by rewrite zero_mod) (take n, by rewrite [-zero_add (succ n) at {1}, add_mod_self]) theorem mul_mod_eq_mod_mul_mod (m n k : nat) : (m * n) % k = ((m % k) * n) % k := calc (m * n) % k = (((m / k) * k + m % k) * n) % k : eq_div_mul_add_mod ... = ((m % k) * n) % k : by rewrite [right_distrib, mul.right_comm, add.comm, add_mul_mod_self] theorem mul_mod_eq_mul_mod_mod (m n k : nat) : (m * n) % k = (m * (n % k)) % k := !mul.comm ▸ !mul.comm ▸ !mul_mod_eq_mod_mul_mod protected theorem div_one (n : ℕ) : n / 1 = n := assert n / 1 * 1 + n % 1 = n, from !eq_div_mul_add_mod⁻¹, begin rewrite [-this at {2}, mul_one, mod_one] end protected theorem div_self {n : ℕ} (H : n > 0) : n / n = 1 := assert (n * 1) / (n * 1) = 1 / 1, from !nat.mul_div_mul_left H, by rewrite [nat.div_one at this, -this, *mul_one] theorem div_mul_cancel_of_mod_eq_zero {m n : ℕ} (H : m % n = 0) : m / n * n = m := by rewrite [eq_div_mul_add_mod m n at {2}, H, add_zero] theorem mul_div_cancel_of_mod_eq_zero {m n : ℕ} (H : m % n = 0) : n * (m / n) = m := !mul.comm ▸ div_mul_cancel_of_mod_eq_zero H /- dvd -/ theorem dvd_of_mod_eq_zero {m n : ℕ} (H : n % m = 0) : m ∣ n := dvd.intro (!mul.comm ▸ div_mul_cancel_of_mod_eq_zero H) theorem mod_eq_zero_of_dvd {m n : ℕ} (H : m ∣ n) : n % m = 0 := dvd.elim H (take z, assume H1 : n = m * z, H1⁻¹ ▸ !mul_mod_right) theorem dvd_iff_mod_eq_zero (m n : ℕ) : m ∣ n ↔ n % m = 0 := iff.intro mod_eq_zero_of_dvd dvd_of_mod_eq_zero definition dvd.decidable_rel [instance] : decidable_rel dvd := take m n, decidable_of_decidable_of_iff _ (iff.symm !dvd_iff_mod_eq_zero) protected theorem div_mul_cancel {m n : ℕ} (H : n ∣ m) : m / n * n = m := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {m n : ℕ} (H : n ∣ m) : n * (m / n) = m := !mul.comm ▸ nat.div_mul_cancel H theorem dvd_of_dvd_add_left {m n₁ n₂ : ℕ} (H₁ : m ∣ n₁ + n₂) (H₂ : m ∣ n₁) : m ∣ n₂ := obtain (c₁ : nat) (Hc₁ : n₁ + n₂ = m * c₁), from H₁, obtain (c₂ : nat) (Hc₂ : n₁ = m * c₂), from H₂, have aux : m * (c₁ - c₂) = n₂, from calc m * (c₁ - c₂) = m * c₁ - m * c₂ : nat.mul_sub_left_distrib ... = n₁ + n₂ - m * c₂ : Hc₁ ... = n₁ + n₂ - n₁ : Hc₂ ... = n₂ : nat.add_sub_cancel_left, dvd.intro aux theorem dvd_of_dvd_add_right {m n₁ n₂ : ℕ} (H : m ∣ n₁ + n₂) : m ∣ n₂ → m ∣ n₁ := nat.dvd_of_dvd_add_left (!add.comm ▸ H) theorem dvd_sub {m n₁ n₂ : ℕ} (H1 : m ∣ n₁) (H2 : m ∣ n₂) : m ∣ n₁ - n₂ := by_cases (assume H3 : n₁ ≥ n₂, have H4 : n₁ = n₁ - n₂ + n₂, from (nat.sub_add_cancel H3)⁻¹, show m ∣ n₁ - n₂, from nat.dvd_of_dvd_add_right (H4 ▸ H1) H2) (assume H3 : ¬ (n₁ ≥ n₂), have H4 : n₁ - n₂ = 0, from sub_eq_zero_of_le (le_of_lt (lt_of_not_ge H3)), show m ∣ n₁ - n₂, from H4⁻¹ ▸ dvd_zero _) theorem dvd.antisymm {m n : ℕ} : m ∣ n → n ∣ m → m = n := by_cases_zero_pos n (assume H1, assume H2 : 0 ∣ m, eq_zero_of_zero_dvd H2) (take n, assume Hpos : n > 0, assume H1 : m ∣ n, assume H2 : n ∣ m, obtain k (Hk : n = m * k), from exists_eq_mul_right_of_dvd H1, obtain l (Hl : m = n * l), from exists_eq_mul_right_of_dvd H2, have n * (l * k) = n, from !mul.assoc ▸ Hl ▸ Hk⁻¹, have l * k = 1, from eq_one_of_mul_eq_self_right Hpos this, have k = 1, from eq_one_of_mul_eq_one_left this, show m = n, from (mul_one m)⁻¹ ⬝ (this ▸ Hk⁻¹)) protected theorem mul_div_assoc (m : ℕ) {n k : ℕ} (H : k ∣ n) : m * n / k = m * (n / k) := or.elim (eq_zero_or_pos k) (assume H1 : k = 0, calc m * n / k = m * n / 0 : H1 ... = 0 : nat.div_zero ... = m * 0 : mul_zero m ... = m * (n / 0) : nat.div_zero ... = m * (n / k) : H1) (assume H1 : k > 0, have H2 : n = n / k * k, from (nat.div_mul_cancel H)⁻¹, calc m * n / k = m * (n / k * k) / k : H2 ... = m * (n / k) * k / k : mul.assoc ... = m * (n / k) : nat.mul_div_cancel _ H1) theorem dvd_of_mul_dvd_mul_left {m n k : ℕ} (kpos : k > 0) (H : k * m ∣ k * n) : m ∣ n := dvd.elim H (take l, assume H1 : k * n = k * m * l, have H2 : n = m * l, from eq_of_mul_eq_mul_left kpos (H1 ⬝ !mul.assoc), dvd.intro H2⁻¹) theorem dvd_of_mul_dvd_mul_right {m n k : ℕ} (kpos : k > 0) (H : m * k ∣ n * k) : m ∣ n := nat.dvd_of_mul_dvd_mul_left kpos (!mul.comm ▸ !mul.comm ▸ H) lemma dvd_of_eq_mul (i j n : nat) : n = j*i → j ∣ n := begin intros, subst n, apply dvd_mul_right end theorem div_dvd_div {k m n : ℕ} (H1 : k ∣ m) (H2 : m ∣ n) : m / k ∣ n / k := have H3 : m = m / k * k, from (nat.div_mul_cancel H1)⁻¹, have H4 : n = n / k * k, from (nat.div_mul_cancel (dvd.trans H1 H2))⁻¹, or.elim (eq_zero_or_pos k) (assume H5 : k = 0, have H6: n / k = 0, from (congr_arg _ H5 ⬝ !nat.div_zero), H6⁻¹ ▸ !dvd_zero) (assume H5 : k > 0, nat.dvd_of_mul_dvd_mul_right H5 (H3 ▸ H4 ▸ H2)) protected theorem div_eq_iff_eq_mul_right {m n : ℕ} (k : ℕ) (H : n > 0) (H' : n ∣ m) : m / n = k ↔ m = n * k := iff.intro (assume H1, by rewrite [-H1, nat.mul_div_cancel' H']) (assume H1, by rewrite [H1, !nat.mul_div_cancel_left H]) protected theorem div_eq_iff_eq_mul_left {m n : ℕ} (k : ℕ) (H : n > 0) (H' : n ∣ m) : m / n = k ↔ m = k * n := !mul.comm ▸ !nat.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_right {m n k : ℕ} (H1 : n ∣ m) (H2 : m / n = k) : m = n * k := calc m = n * (m / n) : nat.mul_div_cancel' H1 ... = n * k : H2 protected theorem div_eq_of_eq_mul_right {m n k : ℕ} (H1 : n > 0) (H2 : m = n * k) : m / n = k := calc m / n = n * k / n : H2 ... = k : !nat.mul_div_cancel_left H1 protected theorem eq_mul_of_div_eq_left {m n k : ℕ} (H1 : n ∣ m) (H2 : m / n = k) : m = k * n := !mul.comm ▸ !nat.eq_mul_of_div_eq_right H1 H2 protected theorem div_eq_of_eq_mul_left {m n k : ℕ} (H1 : n > 0) (H2 : m = k * n) : m / n = k := !nat.div_eq_of_eq_mul_right H1 (!mul.comm ▸ H2) lemma add_mod_eq_of_dvd (i j n : nat) : n ∣ j → (i + j) % n = i % n := assume h, obtain k (hk : j = n * k), from exists_eq_mul_right_of_dvd h, begin subst j, rewrite mul.comm, apply add_mul_mod_self end /- / and ordering -/ lemma le_of_dvd {m n : nat} : n > 0 → m ∣ n → m ≤ n := assume (h₁ : n > 0) (h₂ : m ∣ n), assert h₃ : n % m = 0, from mod_eq_zero_of_dvd h₂, by_contradiction (λ nle : ¬ m ≤ n, have h₄ : m > n, from lt_of_not_ge nle, assert h₅ : n % m = n, from mod_eq_of_lt h₄, begin rewrite h₃ at h₅, subst n, exact absurd h₁ (lt.irrefl 0) end) theorem div_mul_le (m n : ℕ) : m / n * n ≤ m := calc m = m / n * n + m % n : eq_div_mul_add_mod ... ≥ m / n * n : le_add_right protected theorem div_le_of_le_mul {m n k : ℕ} (H : m ≤ n * k) : m / k ≤ n := or.elim (eq_zero_or_pos k) (assume H1 : k = 0, calc m / k = m / 0 : H1 ... = 0 : nat.div_zero ... ≤ n : zero_le) (assume H1 : k > 0, le_of_mul_le_mul_right (calc m / k * k ≤ m / k * k + m % k : le_add_right ... = m : eq_div_mul_add_mod ... ≤ n * k : H) H1) protected theorem div_le_self (m n : ℕ) : m / n ≤ m := nat.cases_on n (!nat.div_zero⁻¹ ▸ !zero_le) take n, have H : m ≤ m * succ n, from calc m = m * 1 : mul_one ... ≤ m * succ n : !mul_le_mul_left (succ_le_succ !zero_le), nat.div_le_of_le_mul H protected theorem mul_le_of_le_div {m n k : ℕ} (H : m ≤ n / k) : m * k ≤ n := calc m * k ≤ n / k * k : !mul_le_mul_right H ... ≤ n : div_mul_le protected theorem le_div_of_mul_le {m n k : ℕ} (H1 : k > 0) (H2 : m * k ≤ n) : m ≤ n / k := have H3 : m * k < (succ (n / k)) * k, from calc m * k ≤ n : H2 ... = n / k * k + n % k : eq_div_mul_add_mod ... < n / k * k + k : add_lt_add_left (!mod_lt H1) ... = (succ (n / k)) * k : succ_mul, le_of_lt_succ (lt_of_mul_lt_mul_right H3) protected theorem le_div_iff_mul_le {m n k : ℕ} (H : k > 0) : m ≤ n / k ↔ m * k ≤ n := iff.intro !nat.mul_le_of_le_div (!nat.le_div_of_mul_le H) protected theorem div_le_div {m n : ℕ} (k : ℕ) (H : m ≤ n) : m / k ≤ n / k := by_cases_zero_pos k (by rewrite [*nat.div_zero]) (take k, assume H1 : k > 0, nat.le_div_of_mul_le H1 (le.trans !div_mul_le H)) protected theorem div_lt_of_lt_mul {m n k : ℕ} (H : m < n * k) : m / k < n := lt_of_mul_lt_mul_right (calc m / k * k ≤ m / k * k + m % k : le_add_right ... = m : eq_div_mul_add_mod ... < n * k : H) protected theorem lt_mul_of_div_lt {m n k : ℕ} (H1 : k > 0) (H2 : m / k < n) : m < n * k := assert H3 : succ (m / k) * k ≤ n * k, from !mul_le_mul_right (succ_le_of_lt H2), have H4 : m / k * k + k ≤ n * k, by rewrite [succ_mul at H3]; apply H3, calc m = m / k * k + m % k : eq_div_mul_add_mod ... < m / k * k + k : add_lt_add_left (!mod_lt H1) ... ≤ n * k : H4 protected theorem div_lt_iff_lt_mul {m n k : ℕ} (H : k > 0) : m / k < n ↔ m < n * k := iff.intro (!nat.lt_mul_of_div_lt H) !nat.div_lt_of_lt_mul protected theorem div_le_iff_le_mul_of_div {m n : ℕ} (k : ℕ) (H : n > 0) (H' : n ∣ m) : m / n ≤ k ↔ m ≤ k * n := by rewrite [propext (!le_iff_mul_le_mul_right H), !nat.div_mul_cancel H'] protected theorem le_mul_of_div_le_of_div {m n k : ℕ} (H1 : n > 0) (H2 : n ∣ m) (H3 : m / n ≤ k) : m ≤ k * n := iff.mp (!nat.div_le_iff_le_mul_of_div H1 H2) H3 -- needed for integer division theorem mul_sub_div_of_lt {m n k : ℕ} (H : k < m * n) : (m * n - (k + 1)) / m = n - k / m - 1 := begin have H1 : k / m < n, from nat.div_lt_of_lt_mul (!mul.comm ▸ H), have H2 : n - k / m ≥ 1, from nat.le_sub_of_add_le (calc 1 + k / m = succ (k / m) : add.comm ... ≤ n : succ_le_of_lt H1), have H3 : n - k / m = n - k / m - 1 + 1, from (nat.sub_add_cancel H2)⁻¹, have H4 : m > 0, from pos_of_ne_zero (assume H': m = 0, not_lt_zero k (begin rewrite [H' at H, zero_mul at H], exact H end)), have H5 : k % m + 1 ≤ m, from succ_le_of_lt (!mod_lt H4), have H6 : m - (k % m + 1) < m, from nat.sub_lt_self H4 !succ_pos, calc (m * n - (k + 1)) / m = (m * n - (k / m * m + k % m + 1)) / m : eq_div_mul_add_mod ... = (m * n - k / m * m - (k % m + 1)) / m : by rewrite [*nat.sub_sub] ... = ((n - k / m) * m - (k % m + 1)) / m : by rewrite [mul.comm m, nat.mul_sub_right_distrib] ... = ((n - k / m - 1) * m + m - (k % m + 1)) / m : by rewrite [H3 at {1}, right_distrib, nat.one_mul] ... = ((n - k / m - 1) * m + (m - (k % m + 1))) / m : {nat.add_sub_assoc H5 _} ... = (m - (k % m + 1)) / m + (n - k / m - 1) : by rewrite [add.comm, (add_mul_div_self H4)] ... = n - k / m - 1 : by rewrite [div_eq_zero_of_lt H6, zero_add] end private lemma div_div_aux (a b c : nat) : b > 0 → c > 0 → (a / b) / c = a / (b * c) := suppose b > 0, suppose c > 0, nat.strong_induction_on a (λ a ih, let k₁ := a / (b*c) in let k₂ := a %(b*c) in assert bc_pos : b*c > 0, from mul_pos `b > 0` `c > 0`, assert k₂ < b * c, from mod_lt _ bc_pos, assert k₂ ≤ a, from !mod_le, or.elim (eq_or_lt_of_le this) (suppose k₂ = a, assert i₁ : a < b * c, by rewrite -this; assumption, assert k₁ = 0, from div_eq_zero_of_lt i₁, assert a / b < c, by rewrite [mul.comm at i₁]; exact nat.div_lt_of_lt_mul i₁, begin rewrite [`k₁ = 0`], show (a / b) / c = 0, from div_eq_zero_of_lt `a / b < c` end) (suppose k₂ < a, assert a = k₁*(b*c) + k₂, from eq_div_mul_add_mod a (b*c), assert a / b = k₁*c + k₂ / b, by rewrite [this at {1}, mul.comm b c at {2}, -mul.assoc, add.comm, add_mul_div_self `b > 0`, add.comm], assert e₁ : (a / b) / c = k₁ + (k₂ / b) / c, by rewrite [this, add.comm, add_mul_div_self `c > 0`, add.comm], assert e₂ : (k₂ / b) / c = k₂ / (b * c), from ih k₂ `k₂ < a`, assert e₃ : k₂ / (b * c) = 0, from div_eq_zero_of_lt `k₂ < b * c`, assert (k₂ / b) / c = 0, by rewrite [e₂, e₃], show (a / b) / c = k₁, by rewrite [e₁, this])) protected lemma div_div_eq_div_mul (a b c : nat) : (a / b) / c = a / (b * c) := begin cases b with b, rewrite [zero_mul, *nat.div_zero, nat.zero_div], cases c with c, rewrite [mul_zero, *nat.div_zero], apply div_div_aux a (succ b) (succ c) dec_trivial dec_trivial end lemma div_lt_of_ne_zero : ∀ {n : nat}, n ≠ 0 → n / 2 < n | 0 h := absurd rfl h | (succ n) h := begin apply nat.div_lt_of_lt_mul, rewrite [-add_one, right_distrib], change n + 1 < (n * 1 + n) + (1 + 1), rewrite [mul_one, -add.assoc], apply add_lt_add_right, show n < n + n + 1, begin rewrite [add.assoc, -add_zero n at {1}], apply add_lt_add_left, apply zero_lt_succ end end end nat
17d039df9e00337532aa5de6c8b50f88b7fd0432
57c233acf9386e610d99ed20ef139c5f97504ba3
/test/library_search/basic.lean
e5c7e29ae2d4dfde984d5b0cd810dc7f808986f2
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
5,367
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.suggest -- No other imports, for fast testing /- Turn off trace messages so they don't pollute the test build: -/ set_option trace.silence_library_search true /- For debugging purposes, we can display the list of lemmas: -/ -- set_option trace.suggest true namespace test.library_search -- Check that `library_search` fails if there are no goals. example : true := begin trivial, success_if_fail { library_search }, end -- Verify that `library_search` solves goals via `solve_by_elim` when the library isn't -- even needed. example (P : Prop) (p : P) : P := by library_search example (P : Prop) (p : P) (np : ¬P) : false := by library_search example (X : Type) (P : Prop) (x : X) (h : Π x : X, x = x → P) : P := by library_search example (α : Prop) : α → α := by library_search -- says: `exact id` example (p : Prop) [decidable p] : (¬¬p) → p := by library_search -- says: `exact not_not.mp` example (a b : Prop) (h : a ∧ b) : a := by library_search -- says: `exact h.left` example (P Q : Prop) [decidable P] [decidable Q]: (¬ Q → ¬ P) → (P → Q) := by library_search -- says: `exact not_imp_not.mp` example (a b : ℕ) : a + b = b + a := by library_search -- says: `exact add_comm a b` example (n m k : ℕ) : n * (m - k) = n * m - n * k := by library_search -- says: `exact mul_tsub n m k` example (n m k : ℕ) : n * m - n * k = n * (m - k) := by library_search -- says: `exact eq.symm (mul_tsub n m k)` example {α : Type} (x y : α) : x = y ↔ y = x := by library_search -- says: `exact eq_comm` example (a b : ℕ) (ha : 0 < a) (hb : 0 < b) : 0 < a + b := by library_search -- says: `exact add_pos ha hb` section synonym -- Synonym `>` for `<` in another part of the goal example (a b : ℕ) (ha : a > 0) (hb : 0 < b) : 0 < a + b := by library_search -- says: `exact add_pos ha hb` example (a b : ℕ) (h : a ∣ b) (w : b > 0) : a ≤ b := by library_search -- says: `exact nat.le_of_dvd w h` example (a b : ℕ) (h : a ∣ b) (w : b > 0) : b ≥ a := by library_search -- says: `exact nat.le_of_dvd w h` -- A lemma with head symbol `¬` can be used to prove `¬ p` or `⊥` example (a : ℕ) : ¬ (a < 0) := by library_search -- says `exact not_lt_bot` example (a : ℕ) (h : a < 0) : false := by library_search -- says `exact not_lt_bot h` -- An inductive type hides the constructor's arguments enough -- so that `library_search` doesn't accidentally close the goal. inductive P : ℕ → Prop | gt_in_head {n : ℕ} : n < 0 → P n -- This lemma with `>` as its head symbol should also be found for goals with head symbol `<`. lemma lemma_with_gt_in_head (a : ℕ) (h : P a) : 0 > a := by { cases h, assumption } -- This lemma with `false` as its head symbols should also be found for goals with head symbol `¬`. lemma lemma_with_false_in_head (a b : ℕ) (h1 : a < b) (h2 : P a) : false := by { apply nat.not_lt_zero, cases h2, assumption } example (a : ℕ) (h : P a) : 0 > a := by library_search -- says `exact lemma_with_gt_in_head a h` example (a : ℕ) (h : P a) : a < 0 := by library_search -- says `exact lemma_with_gt_in_head a h` example (a b : ℕ) (h1 : a < b) (h2 : P a) : false := by library_search -- says `exact lemma_with_false_in_head a b h1 h2` example (a b : ℕ) (h1 : a < b) : ¬ (P a) := by library_search! -- says `exact lemma_with_false_in_head a b h1` end synonym -- We even find `iff` results: example : ∀ P : Prop, ¬(P ↔ ¬P) := by library_search! -- says: `λ (a : Prop), (iff_not_self a).mp` example {a b c : ℕ} (h₁ : a ∣ c) (h₂ : a ∣ b + c) : a ∣ b := by library_search -- says `exact (nat.dvd_add_left h₁).mp h₂` -- Checking examples from issue #2220 example {α : Sort*} (h : empty) : α := by library_search example {α : Type*} (h : empty) : α := by library_search def map_from_sum {A B C : Type} (f : A → C) (g : B → C) : (A ⊕ B) → C := by library_search -- Test that we can set the transparency level in `apply` -- to change how aggressively we unfold definitions while trying to apply lemmas. lemma bind_singleton {α β} (x : α) (f : α → list β) : list.bind [x] f = f x := begin success_if_fail { library_search { md := tactic.transparency.reducible }, }, library_search!, end constant f : ℕ → ℕ axiom F (a b : ℕ) : f a ≤ f b ↔ a ≤ b example (a b : ℕ) (h : a ≤ b) : f a ≤ f b := by library_search -- Test #3432 theorem nonzero_gt_one (n : ℕ) : ¬ n = 0 → n ≥ 1 := by library_search! -- `exact nat.pos_of_ne_zero` example (L : list (list ℕ)) : list ℕ := by library_search using L example (n m : ℕ) : ℕ := by library_search using n m example (P Q : list ℕ) (h : ℕ) : list ℕ := by library_search using h Q example (P Q : list ℕ) (h : ℕ) : list ℕ := by library_search using P Q -- Make sure `library_search` finds nothing when we list too many hypotheses after `using`. example (P Q R S T : list ℕ) : list ℕ := begin success_if_fail { library_search using P Q R S T, }, exact [] end -- Tests for #3428 constants (x y w z : ℕ) axiom not_axiom : ¬ x = y axiom ne_axiom : w ≠ z example : x ≠ y := by library_search example : ¬ w = z := by library_search end test.library_search
7996c1be85427df1ff014d086af742d860f0cfd5
367134ba5a65885e863bdc4507601606690974c1
/src/topology/algebra/group_completion.lean
0beb68d02376ec9afcf3f38ebc6e5b6384a81ea2
[ "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
4,737
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 Completion of topological groups: -/ import topology.uniform_space.completion import topology.algebra.uniform_group noncomputable theory universes u v section group open uniform_space Cauchy filter set variables {α : Type u} [uniform_space α] instance [has_zero α] : has_zero (completion α) := ⟨(0 : α)⟩ instance [has_neg α] : has_neg (completion α) := ⟨completion.map (λa, -a : α → α)⟩ instance [has_add α] : has_add (completion α) := ⟨completion.map₂ (+)⟩ instance [has_sub α] : has_sub (completion α) := ⟨completion.map₂ has_sub.sub⟩ -- TODO: switch sides once #1103 is fixed @[norm_cast] lemma uniform_space.completion.coe_zero [has_zero α] : ((0 : α) : completion α) = 0 := rfl end group namespace uniform_space.completion section uniform_add_group open uniform_space uniform_space.completion variables {α : Type*} [uniform_space α] [add_group α] [uniform_add_group α] @[norm_cast] lemma coe_neg (a : α) : ((- a : α) : completion α) = - a := (map_coe uniform_continuous_neg a).symm @[norm_cast] lemma coe_sub (a b : α) : ((a - b : α) : completion α) = a - b := (map₂_coe_coe a b has_sub.sub uniform_continuous_sub).symm @[norm_cast] lemma coe_add (a b : α) : ((a + b : α) : completion α) = a + b := (map₂_coe_coe a b (+) uniform_continuous_add).symm instance : sub_neg_monoid (completion α) := { zero_add := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ continuous_const continuous_id) continuous_id) (assume a, show 0 + (a : completion α) = a, by rw_mod_cast zero_add), add_zero := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ continuous_id continuous_const) continuous_id) (assume a, show (a : completion α) + 0 = a, by rw_mod_cast add_zero), add_assoc := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous_map₂ (continuous_map₂ continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) (continuous_map₂ continuous_fst (continuous_map₂ (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (assume a b c, show (a : completion α) + b + c = a + (b + c), by repeat { rw_mod_cast add_assoc }), sub_eq_add_neg := λ a b, completion.induction_on₂ a b (is_closed_eq (continuous_map₂ continuous_fst continuous_snd) (continuous_map₂ continuous_fst (continuous_map.comp continuous_snd))) (λ a b, by exact_mod_cast congr_arg coe (sub_eq_add_neg a b)), .. completion.has_zero, .. completion.has_neg, ..completion.has_add, .. completion.has_sub } instance : add_group (completion α) := { add_left_neg := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ completion.continuous_map continuous_id) continuous_const) (assume a, show - (a : completion α) + a = 0, by { rw_mod_cast add_left_neg, refl }), .. completion.sub_neg_monoid } instance : uniform_add_group (completion α) := ⟨uniform_continuous_map₂ has_sub.sub⟩ instance is_add_group_hom_coe : is_add_group_hom (coe : α → completion α) := { map_add := coe_add } variables {β : Type v} [uniform_space β] [add_group β] [uniform_add_group β] lemma is_add_group_hom_extension [complete_space β] [separated_space β] {f : α → β} [is_add_group_hom f] (hf : continuous f) : is_add_group_hom (completion.extension f) := have hf : uniform_continuous f, from uniform_continuous_of_continuous hf, { map_add := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_extension.comp continuous_add) ((continuous_extension.comp continuous_fst).add (continuous_extension.comp continuous_snd))) (λ a b, by rw_mod_cast [extension_coe hf, extension_coe hf, extension_coe hf, is_add_hom.map_add f]) } lemma is_add_group_hom_map {f : α → β} [is_add_group_hom f] (hf : continuous f) : is_add_group_hom (completion.map f) := @is_add_group_hom_extension _ _ _ _ _ _ _ _ _ _ _ (is_add_group_hom.comp _ _) ((continuous_coe _).comp hf) instance {α : Type u} [uniform_space α] [add_comm_group α] [uniform_add_group α] : add_comm_group (completion α) := { add_comm := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_map₂ continuous_fst continuous_snd) (continuous_map₂ continuous_snd continuous_fst)) (assume x y, by { change ↑x + ↑y = ↑y + ↑x, rw [← coe_add, ← coe_add, add_comm]}), .. completion.add_group } end uniform_add_group end uniform_space.completion
a6a31ecad0316f708246bbbad80a6122e7f7ee09
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/pnat/factors.lean
08d7e03b465e6033a636fd1bd9f2d67967a1ec46
[ "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
13,960
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Neil Strickland -/ import data.pnat.basic import data.multiset.sort import data.int.gcd import algebra.group /-- The type of multisets of prime numbers. Unique factorization gives an equivalence between this set and ℕ+, as we will formalize below. -/ def prime_multiset := multiset nat.primes namespace prime_multiset instance : inhabited prime_multiset := by unfold prime_multiset; apply_instance instance : has_repr prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : canonically_ordered_add_monoid prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : distrib_lattice prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : semilattice_sup_bot prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : has_sub prime_multiset := by { dsimp [prime_multiset], apply_instance } theorem add_sub_of_le {u v : prime_multiset} : u ≤ v → u + (v - u) = v := multiset.add_sub_of_le /-- The multiset consisting of a single prime -/ def of_prime (p : nat.primes) : prime_multiset := (p :: 0) theorem card_of_prime (p : nat.primes) : multiset.card (of_prime p) = 1 := rfl /-- We can forget the primality property and regard a multiset of primes as just a multiset of positive integers, or a multiset of natural numbers. In the opposite direction, if we have a multiset of positive integers or natural numbers, together with a proof that all the elements are prime, then we can regard it as a multiset of primes. The next block of results records obvious properties of these coercions. -/ def to_nat_multiset : prime_multiset → multiset ℕ := λ v, v.map (λ p, (p : ℕ)) instance coe_nat : has_coe prime_multiset (multiset ℕ) := ⟨to_nat_multiset⟩ instance coe_nat_hom : is_add_monoid_hom (coe : prime_multiset → multiset ℕ) := by { unfold_coes, dsimp [to_nat_multiset], apply_instance } theorem coe_nat_injective : function.injective (coe : prime_multiset → multiset ℕ) := multiset.map_injective nat.primes.coe_nat_inj theorem coe_nat_of_prime (p : nat.primes) : ((of_prime p) : multiset ℕ) = (p : ℕ) :: 0 := rfl theorem coe_nat_prime (v : prime_multiset) (p : ℕ) (h : p ∈ (v : multiset ℕ)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp' } def to_pnat_multiset : prime_multiset → multiset ℕ+ := λ v, v.map (λ p, (p : ℕ+)) instance coe_pnat : has_coe prime_multiset (multiset ℕ+) := ⟨to_pnat_multiset⟩ instance coe_pnat_hom : is_add_monoid_hom (coe : prime_multiset → multiset ℕ+) := by { unfold_coes, dsimp [to_pnat_multiset], apply_instance } theorem coe_pnat_injective : function.injective (coe : prime_multiset → multiset ℕ+) := multiset.map_injective nat.primes.coe_pnat_inj theorem coe_pnat_of_prime (p : nat.primes) : ((of_prime p) : multiset ℕ+) = (p : ℕ+) :: 0 := rfl theorem coe_pnat_prime (v : prime_multiset) (p : ℕ+) (h : p ∈ (v : multiset ℕ+)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp' } instance coe_multiset_pnat_nat : has_coe (multiset ℕ+) (multiset ℕ) := ⟨λ v, v.map (λ n, (n : ℕ))⟩ theorem coe_pnat_nat (v : prime_multiset) : ((v : (multiset ℕ+)) : (multiset ℕ)) = (v : multiset ℕ) := by { change (v.map (coe : nat.primes → ℕ+)).map subtype.val = v.map subtype.val, rw [multiset.map_map], congr } def prod (v : prime_multiset) : ℕ+ := (v : multiset pnat).prod theorem coe_prod (v : prime_multiset) : (v.prod : ℕ) = (v : multiset ℕ).prod := begin let h : (v.prod : ℕ) = ((v.map coe).map coe).prod := ((monoid_hom.of coe).map_multiset_prod v.to_pnat_multiset), rw [multiset.map_map] at h, have : (coe : ℕ+ → ℕ) ∘ (coe : nat.primes → ℕ+) = coe := funext (λ p, rfl), rw[this] at h, exact h, end theorem prod_of_prime (p : nat.primes) : (of_prime p).prod = (p : ℕ+) := by { change multiset.prod ((p : ℕ+) :: 0) = (p : ℕ+), rw [multiset.prod_cons, multiset.prod_zero, mul_one] } def of_nat_multiset (v : multiset ℕ) (h : ∀ (p : ℕ), p ∈ v → p.prime) : prime_multiset := @multiset.pmap ℕ nat.primes nat.prime (λ p hp, ⟨p, hp⟩) v h theorem to_of_nat_multiset (v : multiset ℕ) (h) : ((of_nat_multiset v h) : multiset ℕ) = v := begin unfold_coes, dsimp [of_nat_multiset, to_nat_multiset], have : (λ (p : ℕ) (h : p.prime), ((⟨p, h⟩ : nat.primes) : ℕ)) = (λ p h, id p) := by {funext p h, refl}, rw [multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_nat_multiset (v : multiset ℕ) (h) : ((of_nat_multiset v h).prod : ℕ) = (v.prod : ℕ) := by rw[coe_prod, to_of_nat_multiset] def of_pnat_multiset (v : multiset ℕ+) (h : ∀ (p : ℕ+), p ∈ v → p.prime) : prime_multiset := @multiset.pmap ℕ+ nat.primes pnat.prime (λ p hp, ⟨(p : ℕ), hp⟩) v h theorem to_of_pnat_multiset (v : multiset ℕ+) (h) : ((of_pnat_multiset v h) : multiset ℕ+) = v := begin unfold_coes, dsimp[of_pnat_multiset, to_pnat_multiset], have : (λ (p : ℕ+) (h : p.prime), ((coe : nat.primes → ℕ+) ⟨p, h⟩)) = (λ p h, id p) := by {funext p h, apply subtype.eq, refl}, rw[multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_pnat_multiset (v : multiset ℕ+) (h) : ((of_pnat_multiset v h).prod : ℕ+) = v.prod := by { dsimp [prod], rw [to_of_pnat_multiset] } /-- Lists can be coerced to multisets; here we have some results about how this interacts with our constructions on multisets. -/ def of_nat_list (l : list ℕ) (h : ∀ (p : ℕ), p ∈ l → p.prime) : prime_multiset := of_nat_multiset (l : multiset ℕ) h theorem prod_of_nat_list (l : list ℕ) (h) : ((of_nat_list l h).prod : ℕ) = l.prod := by { have := prod_of_nat_multiset (l : multiset ℕ) h, rw [multiset.coe_prod] at this, exact this } def of_pnat_list (l : list ℕ+) (h : ∀ (p : ℕ+), p ∈ l → p.prime) : prime_multiset := of_pnat_multiset (l : multiset ℕ+) h theorem prod_of_pnat_list (l : list ℕ+) (h) : (of_pnat_list l h).prod = l.prod := by { have := prod_of_pnat_multiset (l : multiset ℕ+) h, rw [multiset.coe_prod] at this, exact this } /-- The product map gives a homomorphism from the additive monoid of multisets to the multiplicative monoid ℕ+. -/ theorem prod_zero : (0 : prime_multiset).prod = 1 := by { dsimp [prod], exact multiset.prod_zero } theorem prod_add (u v : prime_multiset) : (u + v).prod = u.prod * v.prod := by { dsimp [prod], rw [is_add_monoid_hom.map_add (coe : prime_multiset → multiset ℕ+)], rw [multiset.prod_add] } theorem prod_smul (d : ℕ) (u : prime_multiset) : (d •ℕ u).prod = u.prod ^ d := by { induction d with d ih, refl, rw [succ_nsmul, prod_add, ih, nat.succ_eq_add_one, pow_succ, mul_comm] } end prime_multiset namespace pnat /-- The prime factors of n, regarded as a multiset -/ def factor_multiset (n : ℕ+) : prime_multiset := prime_multiset.of_nat_list (nat.factors n) (@nat.mem_factors n) /-- The product of the factors is the original number -/ theorem prod_factor_multiset (n : ℕ+) : (factor_multiset n).prod = n := eq $ by { dsimp [factor_multiset], rw [prime_multiset.prod_of_nat_list], exact nat.prod_factors n.pos } theorem coe_nat_factor_multiset (n : ℕ+) : ((factor_multiset n) : (multiset ℕ)) = ((nat.factors n) : multiset ℕ) := prime_multiset.to_of_nat_multiset (nat.factors n) (@nat.mem_factors n) end pnat namespace prime_multiset /-- If we start with a multiset of primes, take the product and then factor it, we get back the original multiset. -/ theorem factor_multiset_prod (v : prime_multiset) : v.prod.factor_multiset = v := begin apply prime_multiset.coe_nat_injective, rw [v.prod.coe_nat_factor_multiset, prime_multiset.coe_prod], rcases v with l, unfold_coes, dsimp [prime_multiset.to_nat_multiset], rw [multiset.coe_prod], let l' := l.map (coe : nat.primes → ℕ), have : ∀ (p : ℕ), p ∈ l' → p.prime := λ p hp, by {rcases list.mem_map.mp hp with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp'}, exact multiset.coe_eq_coe.mpr (@nat.factors_unique _ l' rfl this).symm, end end prime_multiset namespace pnat /-- Positive integers biject with multisets of primes. -/ def factor_multiset_equiv : ℕ+ ≃ prime_multiset := { to_fun := factor_multiset, inv_fun := prime_multiset.prod, left_inv := prod_factor_multiset, right_inv := prime_multiset.factor_multiset_prod } /-- Factoring gives a homomorphism from the multiplicative monoid ℕ+ to the additive monoid of multisets. -/ theorem factor_multiset_one : factor_multiset 1 = 0 := rfl theorem factor_multiset_mul (n m : ℕ+) : factor_multiset (n * m) = (factor_multiset n) + (factor_multiset m) := begin let u := factor_multiset n, let v := factor_multiset m, have : n = u.prod := (prod_factor_multiset n).symm, rw[this], have : m = v.prod := (prod_factor_multiset m).symm, rw[this], rw[← prime_multiset.prod_add], repeat {rw[prime_multiset.factor_multiset_prod]}, end theorem factor_multiset_pow (n : ℕ+) (m : ℕ) : factor_multiset (n ^ m) = m •ℕ (factor_multiset n) := begin let u := factor_multiset n, have : n = u.prod := (prod_factor_multiset n).symm, rw[this, ← prime_multiset.prod_smul], repeat {rw[prime_multiset.factor_multiset_prod]}, end /-- Factoring a prime gives the corresponding one-element multiset. -/ theorem factor_multiset_of_prime (p : nat.primes) : (p : ℕ+).factor_multiset = prime_multiset.of_prime p := begin apply factor_multiset_equiv.symm.injective, change (p : ℕ+).factor_multiset.prod = (prime_multiset.of_prime p).prod, rw[(p : ℕ+).prod_factor_multiset, prime_multiset.prod_of_prime], end /-- We now have four different results that all encode the idea that inequality of multisets corresponds to divisibility of positive integers. -/ theorem factor_multiset_le_iff {m n : ℕ+} : factor_multiset m ≤ factor_multiset n ↔ m ∣ n := begin split, { intro h, rw [← prod_factor_multiset m, ← prod_factor_multiset m], apply dvd_intro (n.factor_multiset - m.factor_multiset).prod, rw [← prime_multiset.prod_add, prime_multiset.factor_multiset_prod, prime_multiset.add_sub_of_le h, prod_factor_multiset] }, { intro h, rw [← mul_div_exact h, factor_multiset_mul], exact le_add_right (le_refl _) } end theorem factor_multiset_le_iff' {m : ℕ+} {v : prime_multiset}: factor_multiset m ≤ v ↔ m ∣ v.prod := by { let h := @factor_multiset_le_iff m v.prod, rw [v.factor_multiset_prod] at h, exact h } end pnat namespace prime_multiset theorem prod_dvd_iff {u v : prime_multiset} : u.prod ∣ v.prod ↔ u ≤ v := by { let h := @pnat.factor_multiset_le_iff' u.prod v, rw [u.factor_multiset_prod] at h, exact h.symm } theorem prod_dvd_iff' {u : prime_multiset} {n : ℕ+} : u.prod ∣ n ↔ u ≤ n.factor_multiset := by { let h := @prod_dvd_iff u n.factor_multiset, rw [n.prod_factor_multiset] at h, exact h } end prime_multiset namespace pnat /-- The gcd and lcm operations on positive integers correspond to the inf and sup operations on multisets. -/ theorem factor_multiset_gcd (m n : ℕ+) : factor_multiset (gcd m n) = (factor_multiset m) ⊓ (factor_multiset n) := begin apply le_antisymm, { apply le_inf_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact gcd_dvd_left m n, exact gcd_dvd_right m n}, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply dvd_gcd; rw[prime_multiset.prod_dvd_iff'], exact inf_le_left, exact inf_le_right} end theorem factor_multiset_lcm (m n : ℕ+) : factor_multiset (lcm m n) = (factor_multiset m) ⊔ (factor_multiset n) := begin apply le_antisymm, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply lcm_dvd; rw[← factor_multiset_le_iff'], exact le_sup_left, exact le_sup_right}, { apply sup_le_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact dvd_lcm_left m n, exact dvd_lcm_right m n }, end /-- The number of occurrences of p in the factor multiset of m is the same as the p-adic valuation of m. -/ theorem count_factor_multiset (m : ℕ+) (p : nat.primes) (k : ℕ) : (p : ℕ+) ^ k ∣ m ↔ k ≤ m.factor_multiset.count p := begin intros, rw [multiset.le_count_iff_repeat_le], rw [← factor_multiset_le_iff, factor_multiset_pow, factor_multiset_of_prime], congr' 2, apply multiset.eq_repeat.mpr, split, { rw [multiset.card_smul, prime_multiset.card_of_prime, mul_one] }, { have : ∀ (m : ℕ), m •ℕ (p::0) = multiset.repeat p m := λ m, by {induction m with m ih, { refl }, rw [succ_nsmul, multiset.repeat_succ, ih], rw[multiset.cons_add, zero_add] }, intros q h, rw [prime_multiset.of_prime, this k] at h, exact multiset.eq_of_mem_repeat h } end end pnat namespace prime_multiset theorem prod_inf (u v : prime_multiset) : (u ⊓ v).prod = pnat.gcd u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u ⊓ v).prod = pnat.gcd n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw [← pnat.factor_multiset_gcd n m, pnat.prod_factor_multiset] end theorem prod_sup (u v : prime_multiset) : (u ⊔ v).prod = pnat.lcm u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u ⊔ v).prod = pnat.lcm n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw[← pnat.factor_multiset_lcm n m, pnat.prod_factor_multiset] end end prime_multiset
858df2f8953b8950a6e09dbc9ab12ce39233ff34
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/group_theory/submonoid/basic.lean
a4bf838fff9e7ff7f943014a237cab4c258cf0e7
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,177
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, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov -/ import data.set.lattice import data.set_like.basic /-! # Submonoids: definition and `complete_lattice` structure This file defines bundled multiplicative and additive submonoids. We also define a `complete_lattice` structure on `submonoid`s, define the closure of a set as the minimal submonoid that includes this set, and prove a few results about extending properties from a dense set (i.e. a set with `closure s = ⊤`) to the whole monoid, see `submonoid.dense_induction` and `monoid_hom.of_mdense`. ## Main definitions * `submonoid M`: the type of bundled submonoids of a monoid `M`; the underlying set is given in the `carrier` field of the structure, and should be accessed through coercion as in `(S : set M)`. * `add_submonoid M` : the type of bundled submonoids of an additive monoid `M`. For each of the following definitions in the `submonoid` namespace, there is a corresponding definition in the `add_submonoid` namespace. * `submonoid.copy` : copy of a submonoid with `carrier` replaced by a set that is equal but possibly not definitionally equal to the carrier of the original `submonoid`. * `submonoid.closure` : monoid closure of a set, i.e., the least submonoid that includes the set. * `submonoid.gi` : `closure : set M → submonoid M` and coercion `coe : submonoid M → set M` form a `galois_insertion`; * `monoid_hom.eq_mlocus`: the submonoid of elements `x : M` such that `f x = g x`; * `monoid_hom.of_mdense`: if a map `f : M → N` between two monoids satisfies `f 1 = 1` and `f (x * y) = f x * f y` for `y` from some dense set `s`, then `f` is a monoid homomorphism. E.g., if `f : ℕ → M` satisfies `f 0 = 0` and `f (x + 1) = f x + f 1`, then `f` is an additive monoid homomorphism. ## Implementation notes Submonoid inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a submonoid's underlying set. Note that `submonoid M` does not actually require `monoid M`, instead requiring only the weaker `mul_one_class M`. This file is designed to have very few dependencies. In particular, it should not use natural numbers. ## Tags submonoid, submonoids -/ variables {M : Type*} {N : Type*} variables {A : Type*} section non_assoc variables [mul_one_class M] {s : set M} variables [add_zero_class A] {t : set A} /-- A submonoid of a monoid `M` is a subset containing 1 and closed under multiplication. -/ structure submonoid (M : Type*) [mul_one_class M] := (carrier : set M) (one_mem' : (1 : M) ∈ carrier) (mul_mem' {a b} : a ∈ carrier → b ∈ carrier → a * b ∈ carrier) /-- An additive submonoid of an additive monoid `M` is a subset containing 0 and closed under addition. -/ structure add_submonoid (M : Type*) [add_zero_class M] := (carrier : set M) (zero_mem' : (0 : M) ∈ carrier) (add_mem' {a b} : a ∈ carrier → b ∈ carrier → a + b ∈ carrier) attribute [to_additive] submonoid namespace submonoid @[to_additive] instance : set_like (submonoid M) M := ⟨submonoid.carrier, λ p q h, by cases p; cases q; congr'⟩ /-- See Note [custom simps projection] -/ @[to_additive " See Note [custom simps projection]"] def simps.coe (S : submonoid M) : set M := S initialize_simps_projections submonoid (carrier → coe) initialize_simps_projections add_submonoid (carrier → coe) @[simp, to_additive] lemma mem_carrier {s : submonoid M} {x : M} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[simp, to_additive] lemma mem_mk {s : set M} {x : M} (h_one) (h_mul) : x ∈ mk s h_one h_mul ↔ x ∈ s := iff.rfl @[simp, to_additive] lemma coe_set_mk {s : set M} (h_one) (h_mul) : (mk s h_one h_mul : set M) = s := rfl @[simp, to_additive] lemma mk_le_mk {s t : set M} (h_one) (h_mul) (h_one') (h_mul') : mk s h_one h_mul ≤ mk t h_one' h_mul' ↔ s ⊆ t := iff.rfl /-- Two submonoids are equal if they have the same elements. -/ @[ext, to_additive "Two `add_submonoid`s are equal if they have the same elements."] theorem ext {S T : submonoid M} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h attribute [ext] add_submonoid.ext /-- Copy a submonoid replacing `carrier` with a set that is equal to it. -/ @[to_additive "Copy an additive submonoid replacing `carrier` with a set that is equal to it."] protected def copy (S : submonoid M) (s : set M) (hs : s = S) : submonoid M := { carrier := s, one_mem' := hs.symm ▸ S.one_mem', mul_mem' := hs.symm ▸ S.mul_mem' } variable {S : submonoid M} @[simp, to_additive] lemma coe_copy {s : set M} (hs : s = S) : (S.copy s hs : set M) = s := rfl @[to_additive] lemma copy_eq {s : set M} (hs : s = S) : S.copy s hs = S := set_like.coe_injective hs variable (S) /-- A submonoid contains the monoid's 1. -/ @[to_additive "An `add_submonoid` contains the monoid's 0."] theorem one_mem : (1 : M) ∈ S := S.one_mem' /-- A submonoid is closed under multiplication. -/ @[to_additive "An `add_submonoid` is closed under addition."] theorem mul_mem {x y : M} : x ∈ S → y ∈ S → x * y ∈ S := submonoid.mul_mem' S /-- The submonoid `M` of the monoid `M`. -/ @[to_additive "The additive submonoid `M` of the `add_monoid M`."] instance : has_top (submonoid M) := ⟨{ carrier := set.univ, one_mem' := set.mem_univ 1, mul_mem' := λ _ _ _ _, set.mem_univ _ }⟩ /-- The trivial submonoid `{1}` of an monoid `M`. -/ @[to_additive "The trivial `add_submonoid` `{0}` of an `add_monoid` `M`."] instance : has_bot (submonoid M) := ⟨{ carrier := {1}, one_mem' := set.mem_singleton 1, mul_mem' := λ a b ha hb, by { simp only [set.mem_singleton_iff] at *, rw [ha, hb, mul_one] }}⟩ @[to_additive] instance : inhabited (submonoid M) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : M} : x ∈ (⊥ : submonoid M) ↔ x = 1 := set.mem_singleton_iff @[simp, to_additive] lemma mem_top (x : M) : x ∈ (⊤ : submonoid M) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : submonoid M) : set M) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : submonoid M) : set M) = {1} := rfl /-- The inf of two submonoids is their intersection. -/ @[to_additive "The inf of two `add_submonoid`s is their intersection."] instance : has_inf (submonoid M) := ⟨λ S₁ S₂, { carrier := S₁ ∩ S₂, one_mem' := ⟨S₁.one_mem, S₂.one_mem⟩, mul_mem' := λ _ _ ⟨hx, hx'⟩ ⟨hy, hy'⟩, ⟨S₁.mul_mem hx hy, S₂.mul_mem hx' hy'⟩ }⟩ @[simp, to_additive] lemma coe_inf (p p' : submonoid M) : ((p ⊓ p' : submonoid M) : set M) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : submonoid M} {x : M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (submonoid M) := ⟨λ s, { carrier := ⋂ t ∈ s, ↑t, one_mem' := set.mem_bInter $ λ i h, i.one_mem, mul_mem' := λ x y hx hy, set.mem_bInter $ λ i h, i.mul_mem (by apply set.mem_bInter_iff.1 hx i h) (by apply set.mem_bInter_iff.1 hy i h) }⟩ @[simp, to_additive] lemma coe_Inf (S : set (submonoid M)) : ((Inf S : submonoid M) : set M) = ⋂ s ∈ S, ↑s := rfl attribute [norm_cast] coe_Inf add_submonoid.coe_Inf @[to_additive] lemma mem_Inf {S : set (submonoid M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[to_additive] lemma mem_infi {ι : Sort*} {S : ι → submonoid M} {x : M} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, to_additive] lemma coe_infi {ι : Sort*} {S : ι → submonoid M} : (↑(⨅ i, S i) : set M) = ⋂ i, S i := by simp only [infi, coe_Inf, set.bInter_range] attribute [norm_cast] coe_infi add_submonoid.coe_infi /-- Submonoids of a monoid form a complete lattice. -/ @[to_additive "The `add_submonoid`s of an `add_monoid` form a complete lattice."] instance : complete_lattice (submonoid M) := { le := (≤), lt := (<), bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), Inf := has_Inf.Inf, le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (submonoid M) $ λ s, is_glb.of_image (λ S T, show (S : set M) ≤ T ↔ S ≤ T, from set_like.coe_subset_coe) is_glb_binfi } @[simp, to_additive] lemma subsingleton_iff : subsingleton (submonoid M) ↔ subsingleton M := ⟨ λ h, by exactI ⟨λ x y, have ∀ i : M, i = 1 := λ i, mem_bot.mp $ subsingleton.elim (⊤ : submonoid M) ⊥ ▸ mem_top i, (this x).trans (this y).symm⟩, λ h, by exactI ⟨λ x y, submonoid.ext $ λ i, subsingleton.elim 1 i ▸ by simp [submonoid.one_mem]⟩⟩ @[simp, to_additive] lemma nontrivial_iff : nontrivial (submonoid M) ↔ nontrivial M := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans subsingleton_iff).trans not_nontrivial_iff_subsingleton.symm) @[to_additive] instance [subsingleton M] : unique (submonoid M) := ⟨⟨⊥⟩, λ a, @subsingleton.elim _ (subsingleton_iff.mpr ‹_›) a _⟩ @[to_additive] instance [nontrivial M] : nontrivial (submonoid M) := nontrivial_iff.mpr ‹_› /-- The `submonoid` generated by a set. -/ @[to_additive "The `add_submonoid` generated by a set"] def closure (s : set M) : submonoid M := Inf {S | s ⊆ S} @[to_additive] lemma mem_closure {x : M} : x ∈ closure s ↔ ∀ S : submonoid M, s ⊆ S → x ∈ S := mem_Inf /-- The submonoid generated by a set includes the set. -/ @[simp, to_additive "The `add_submonoid` generated by a set includes the set."] lemma subset_closure : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx variable {S} open set /-- A submonoid `S` includes `closure s` if and only if it includes `s`. -/ @[simp, to_additive "An additive submonoid `S` includes `closure s` if and only if it includes `s`"] lemma closure_le : closure s ≤ S ↔ s ⊆ S := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ /-- Submonoid closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ @[to_additive "Additive submonoid closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`"] lemma closure_mono ⦃s t : set M⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ subset.trans h subset_closure @[to_additive] lemma closure_eq_of_le (h₁ : s ⊆ S) (h₂ : S ≤ closure s) : closure s = S := le_antisymm (closure_le.2 h₁) h₂ variable (S) /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `s`, and is preserved under multiplication, then `p` holds for all elements of the closure of `s`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `s`, and is preserved under addition, then `p` holds for all elements of the additive closure of `s`."] lemma closure_induction {p : M → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, H1, Hmul⟩).2 Hs h attribute [elab_as_eliminator] submonoid.closure_induction add_submonoid.closure_induction /-- If `s` is a dense set in a monoid `M`, `submonoid.closure s = ⊤`, then in order to prove that some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, verify `p 1`, and verify that `p x` and `p y` imply `p (x * y)`. -/ @[to_additive] lemma dense_induction {p : M → Prop} (x : M) {s : set M} (hs : closure s = ⊤) (Hs : ∀ x ∈ s, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := have ∀ x ∈ closure s, p x, from λ x hx, closure_induction hx Hs H1 Hmul, by simpa [hs] using this x /-- If `s` is a dense set in an additive monoid `M`, `add_submonoid.closure s = ⊤`, then in order to prove that some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, verify `p 0`, and verify that `p x` and `p y` imply `p (x + y)`. -/ add_decl_doc add_submonoid.dense_induction attribute [elab_as_eliminator] dense_induction add_submonoid.dense_induction variable (M) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure M _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {M} /-- Closure of a submonoid `S` equals `S`. -/ @[simp, to_additive "Additive closure of an additive submonoid `S` equals `S`"] lemma closure_eq : closure (S : set M) = S := (submonoid.gi M).l_u_eq S @[simp, to_additive] lemma closure_empty : closure (∅ : set M) = ⊥ := (submonoid.gi M).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set M) = ⊤ := @coe_top M _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set M) : closure (s ∪ t) = closure s ⊔ closure t := (submonoid.gi M).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set M) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (submonoid.gi M).gc.l_supr end submonoid namespace monoid_hom variables [mul_one_class N] open submonoid /-- The submonoid of elements `x : M` such that `f x = g x` -/ @[to_additive "The additive submonoid of elements `x : M` such that `f x = g x`"] def eq_mlocus (f g : M →* N) : submonoid M := { carrier := {x | f x = g x}, one_mem' := by rw [set.mem_set_of_eq, f.map_one, g.map_one], mul_mem' := λ x y (hx : _ = _) (hy : _ = _), by simp [*] } /-- If two monoid homomorphisms are equal on a set, then they are equal on its submonoid closure. -/ @[to_additive] lemma eq_on_mclosure {f g : M →* N} {s : set M} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_mlocus g, from closure_le.2 h @[to_additive] lemma eq_of_eq_on_mtop {f g : M →* N} (h : set.eq_on f g (⊤ : submonoid M)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_mdense {s : set M} (hs : closure s = ⊤) {f g : M →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_mtop $ hs ▸ eq_on_mclosure h end monoid_hom end non_assoc section assoc variables [monoid M] [monoid N] {s : set M} section is_unit /-- The submonoid consisting of the units of a monoid -/ def is_unit.submonoid (M : Type*) [monoid M] : submonoid M := { carrier := set_of is_unit, one_mem' := by simp only [is_unit_one, set.mem_set_of_eq], mul_mem' := by { intros a b ha hb, rw set.mem_set_of_eq at *, exact is_unit.mul ha hb } } lemma is_unit.mem_submonoid_iff {M : Type*} [monoid M] (a : M) : a ∈ is_unit.submonoid M ↔ is_unit a := begin change a ∈ set_of is_unit ↔ is_unit a, rw set.mem_set_of_eq end end is_unit namespace monoid_hom open submonoid /-- Let `s` be a subset of a monoid `M` such that the closure of `s` is the whole monoid. Then `monoid_hom.of_mdense` defines a monoid homomorphism from `M` asking for a proof of `f (x * y) = f x * f y` only for `y ∈ s`. -/ @[to_additive] def of_mdense {M N} [monoid M] [monoid N] {s : set M} (f : M → N) (hs : closure s = ⊤) (h1 : f 1 = 1) (hmul : ∀ x (y ∈ s), f (x * y) = f x * f y) : M →* N := { to_fun := f, map_one' := h1, map_mul' := λ x y, dense_induction y hs (λ y hy x, hmul x y hy) (by simp [h1]) (λ y₁ y₂ h₁ h₂ x, by simp only [← mul_assoc, h₁, h₂]) x } /-- Let `s` be a subset of an additive monoid `M` such that the closure of `s` is the whole monoid. Then `add_monoid_hom.of_mdense` defines an additive monoid homomorphism from `M` asking for a proof of `f (x + y) = f x + f y` only for `y ∈ s`. -/ add_decl_doc add_monoid_hom.of_mdense @[simp, to_additive] lemma coe_of_mdense (f : M → N) (hs : closure s = ⊤) (h1 hmul) : ⇑(of_mdense f hs h1 hmul) = f := rfl attribute [norm_cast] coe_of_mdense add_monoid_hom.coe_of_mdense end monoid_hom end assoc
13869c882973f249d94b723ea2e9f84da943a3b6
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/limits/shapes/multiequalizer.lean
4f9c59a9671de04b2a588bbf1d8276d21d37d9b3
[ "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,747
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.limits.has_limits /-! # Multi-(co)equalizers A *multiequalizer* is an equalizer of two morphisms between two products. Since both products and equalizers are limits, such an object is again a limit. This file provides the diagram whose limit is indeed such an object. In fact, it is well-known that any limit can be obtained as a multiequalizer. The dual construction (multicoequalizers) is also provided. ## Projects Prove that a multiequalizer can be identified with an equalizer between products (and analogously for multicoequalizers). Prove that the limit of any diagram is a multiequalizer (and similarly for colimits). -/ namespace category_theory.limits open category_theory universes v u /-- The type underlying the multiequalizer diagram. -/ @[nolint unused_arguments] inductive walking_multicospan {L R : Type v} (fst snd : R → L) : Type v | left : L → walking_multicospan | right : R → walking_multicospan /-- The type underlying the multiecoqualizer diagram. -/ @[nolint unused_arguments] inductive walking_multispan {L R : Type v} (fst snd : L → R) : Type v | left : L → walking_multispan | right : R → walking_multispan namespace walking_multicospan variables {L R : Type v} {fst snd : R → L} instance [inhabited L] : inhabited (walking_multicospan fst snd) := ⟨left (default _)⟩ /-- Morphisms for `walking_multicospan`. -/ inductive hom : Π (a b : walking_multicospan fst snd), Type v | id (A) : hom A A | fst (b) : hom (left (fst b)) (right b) | snd (b) : hom (left (snd b)) (right b) instance {a : walking_multicospan fst snd} : inhabited (hom a a) := ⟨hom.id _⟩ /-- Composition of morphisms for `walking_multicospan`. -/ def hom.comp : Π {A B C : walking_multicospan fst snd} (f : hom A B) (g : hom B C), hom A C | _ _ _ (hom.id X) f := f | _ _ _ (hom.fst b) (hom.id X) := hom.fst b | _ _ _ (hom.snd b) (hom.id X) := hom.snd b instance : small_category (walking_multicospan fst snd) := { hom := hom, id := hom.id, comp := λ X Y Z, hom.comp, id_comp' := by { rintro (_|_) (_|_) (_|_|_), tidy }, comp_id' := by { rintro (_|_) (_|_) (_|_|_), tidy }, assoc' := by { rintro (_|_) (_|_) (_|_) (_|_) (_|_|_) (_|_|_) (_|_|_), tidy } } end walking_multicospan namespace walking_multispan variables {L R : Type v} {fst snd : L → R} instance [inhabited L] : inhabited (walking_multispan fst snd) := ⟨left (default _)⟩ /-- Morphisms for `walking_multispan`. -/ inductive hom : Π (a b : walking_multispan fst snd), Type v | id (A) : hom A A | fst (a) : hom (left a) (right (fst a)) | snd (a) : hom (left a) (right (snd a)) instance {a : walking_multispan fst snd} : inhabited (hom a a) := ⟨hom.id _⟩ /-- Composition of morphisms for `walking_multispan`. -/ def hom.comp : Π {A B C : walking_multispan fst snd} (f : hom A B) (g : hom B C), hom A C | _ _ _ (hom.id X) f := f | _ _ _ (hom.fst a) (hom.id X) := hom.fst a | _ _ _ (hom.snd a) (hom.id X) := hom.snd a instance : small_category (walking_multispan fst snd) := { hom := hom, id := hom.id, comp := λ X Y Z, hom.comp, id_comp' := by { rintro (_|_) (_|_) (_|_|_), tidy }, comp_id' := by { rintro (_|_) (_|_) (_|_|_), tidy }, assoc' := by { rintro (_|_) (_|_) (_|_) (_|_) (_|_|_) (_|_|_) (_|_|_), tidy } } end walking_multispan /-- This is a structure encapsulating the data necessary to define a `multicospan`. -/ @[nolint has_inhabited_instance] structure multicospan_index (C : Type u) [category.{v} C] := (L R : Type v) (fst_to snd_to : R → L) (left : L → C) (right : R → C) (fst : Π b, left (fst_to b) ⟶ right b) (snd : Π b, left (snd_to b) ⟶ right b) /-- This is a structure encapsulating the data necessary to define a `multispan`. -/ @[nolint has_inhabited_instance] structure multispan_index (C : Type u) [category.{v} C] := (L R : Type v) (fst_from snd_from : L → R) (left : L → C) (right : R → C) (fst : Π a, left a ⟶ right (fst_from a)) (snd : Π a, left a ⟶ right (snd_from a)) namespace multicospan_index variables {C : Type u} [category.{v} C] (I : multicospan_index C) /-- The multicospan associated to `I : multicospan_index`. -/ def multicospan : walking_multicospan I.fst_to I.snd_to ⥤ C := { obj := λ x, match x with | walking_multicospan.left a := I.left a | walking_multicospan.right b := I.right b end, map := λ x y f, match x, y, f with | _, _, walking_multicospan.hom.id x := 𝟙 _ | _, _, walking_multicospan.hom.fst b := I.fst _ | _, _, walking_multicospan.hom.snd b := I.snd _ end, map_id' := by { rintros (_|_), tidy }, map_comp' := by { rintros (_|_) (_|_) (_|_) (_|_|_) (_|_|_), tidy } } @[simp] lemma multicospan_obj_left (a) : I.multicospan.obj (walking_multicospan.left a) = I.left a := rfl @[simp] lemma multicospan_obj_right (b) : I.multicospan.obj (walking_multicospan.right b) = I.right b := rfl @[simp] lemma multicospan_map_fst (b) : I.multicospan.map (walking_multicospan.hom.fst b) = I.fst b := rfl @[simp] lemma multicospan_map_snd (b) : I.multicospan.map (walking_multicospan.hom.snd b) = I.snd b := rfl end multicospan_index namespace multispan_index variables {C : Type u} [category.{v} C] (I : multispan_index C) /-- The multispan associated to `I : multispan_index`. -/ def multispan : walking_multispan I.fst_from I.snd_from ⥤ C := { obj := λ x, match x with | walking_multispan.left a := I.left a | walking_multispan.right b := I.right b end, map := λ x y f, match x, y, f with | _, _, walking_multispan.hom.id x := 𝟙 _ | _, _, walking_multispan.hom.fst b := I.fst _ | _, _, walking_multispan.hom.snd b := I.snd _ end, map_id' := by { rintros (_|_), tidy }, map_comp' := by { rintros (_|_) (_|_) (_|_) (_|_|_) (_|_|_), tidy } } @[simp] lemma multispan_obj_left (a) : I.multispan.obj (walking_multispan.left a) = I.left a := rfl @[simp] lemma multispan_obj_right (b) : I.multispan.obj (walking_multispan.right b) = I.right b := rfl @[simp] lemma multispan_map_fst (a) : I.multispan.map (walking_multispan.hom.fst a) = I.fst a := rfl @[simp] lemma multispan_map_snd (a) : I.multispan.map (walking_multispan.hom.snd a) = I.snd a := rfl end multispan_index variables {C : Type u} [category.{v} C] /-- A multifork is a cone over a multicospan. -/ @[nolint has_inhabited_instance] def multifork (I : multicospan_index C) := cone I.multicospan /-- A multicofork is a cocone over a multispan. -/ @[nolint has_inhabited_instance] def multicofork (I : multispan_index C) := cocone I.multispan namespace multifork variables {I : multicospan_index C} (K : multifork I) /-- The maps from the cone point of a multifork to the objects on the left. -/ def ι (a : I.L) : K.X ⟶ I.left a := K.π.app (walking_multicospan.left _) @[simp] lemma ι_eq_app_left (a) : K.ι a = K.π.app (walking_multicospan.left _) := rfl @[simp] lemma app_left_fst (b) : K.π.app (walking_multicospan.left (I.fst_to b)) ≫ I.fst b = K.π.app (walking_multicospan.right b) := by { rw ← K.w (walking_multicospan.hom.fst b), refl } @[simp] lemma app_left_snd (b) : K.π.app (walking_multicospan.left (I.snd_to b)) ≫ I.snd b = K.π.app (walking_multicospan.right b) := by { rw ← K.w (walking_multicospan.hom.snd b), refl } /-- Construct a multifork using a collection `ι` of morphisms. -/ @[simps] def of_ι (I : multicospan_index C) (P : C) (ι : Π a, P ⟶ I.left a) (w : ∀ b, ι (I.fst_to b) ≫ I.fst b = ι (I.snd_to b) ≫ I.snd b) : multifork I := { X := P, π := { app := λ x, match x with | walking_multicospan.left a := ι _ | walking_multicospan.right b := ι (I.fst_to b) ≫ I.fst b end, naturality' := begin rintros (_|_) (_|_) (_|_|_), any_goals { symmetry, dsimp, rw category.id_comp, apply category.comp_id }, { dsimp, rw category.id_comp, refl }, { dsimp, rw category.id_comp, apply w } end } } @[reassoc] lemma condition (b) : K.ι (I.fst_to b) ≫ I.fst b = K.ι (I.snd_to b) ≫ I.snd b := by simp end multifork namespace multicofork variables {I : multispan_index C} (K : multicofork I) /-- The maps to the cocone point of a multicofork from the objects on the right. -/ def π (b : I.R) : I.right b ⟶ K.X := K.ι.app (walking_multispan.right _) @[simp] lemma π_eq_app_right (b) : K.π b = K.ι.app (walking_multispan.right _) := rfl @[simp] lemma fst_app_right (a) : I.fst a ≫ K.ι.app (walking_multispan.right (I.fst_from a)) = K.ι.app (walking_multispan.left a) := by { rw ← K.w (walking_multispan.hom.fst a), refl } @[simp] lemma snd_app_right (a) : I.snd a ≫ K.ι.app (walking_multispan.right (I.snd_from a)) = K.ι.app (walking_multispan.left a) := by { rw ← K.w (walking_multispan.hom.snd a), refl } /-- Construct a multicofork using a collection `π` of morphisms. -/ @[simps] def of_π (I : multispan_index C) (P : C) (π : Π b, I.right b ⟶ P) (w : ∀ a, I.fst a ≫ π (I.fst_from a) = I.snd a ≫ π (I.snd_from a)) : multicofork I := { X := P, ι := { app := λ x, match x with | walking_multispan.left a := I.fst a ≫ π _ | walking_multispan.right b := π _ end, naturality' := begin rintros (_|_) (_|_) (_|_|_), any_goals { dsimp, rw category.comp_id, apply category.id_comp }, { dsimp, rw category.comp_id, refl }, { dsimp, rw category.comp_id, apply (w _).symm } end } } @[reassoc] lemma condition (a) : I.fst a ≫ K.π (I.fst_from a) = I.snd a ≫ K.π (I.snd_from a) := by simp end multicofork /-- For `I : multicospan_index C`, we say that it has a multiequalizer if the associated multicospan has a limit. -/ abbreviation has_multiequalizer (I : multicospan_index C) := has_limit I.multicospan noncomputable theory /-- The multiequalizer of `I : multicospan_index C`. -/ abbreviation multiequalizer (I : multicospan_index C) [has_multiequalizer I] : C := limit I.multicospan /-- For `I : multispan_index C`, we say that it has a multicoequalizer if the associated multicospan has a limit. -/ abbreviation has_multicoequalizer (I : multispan_index C) := has_colimit I.multispan /-- The multiecoqualizer of `I : multispan_index C`. -/ abbreviation multicoequalizer (I : multispan_index C) [has_multicoequalizer I] : C := colimit I.multispan namespace multiequalizer variables (I : multicospan_index C) [has_multiequalizer I] /-- The canonical map from the multiequalizer to the objects on the left. -/ abbreviation ι (a : I.L) : multiequalizer I ⟶ I.left a := limit.π _ (walking_multicospan.left a) /-- The multifork associated to the multiequalizer. -/ abbreviation multifork : multifork I := limit.cone _ @[simp] lemma multifork_ι (a) : (multiequalizer.multifork I).ι a = multiequalizer.ι I a := rfl @[simp] lemma multifork_π_app_left (a) : (multiequalizer.multifork I).π.app (walking_multicospan.left a) = multiequalizer.ι I a := rfl @[reassoc] lemma condition (b) : multiequalizer.ι I (I.fst_to b) ≫ I.fst b = multiequalizer.ι I (I.snd_to b) ≫ I.snd b := multifork.condition _ _ /-- Construct a morphism to the multiequalizer from its universal property. -/ abbreviation lift (W : C) (k : Π a, W ⟶ I.left a) (h : ∀ b, k (I.fst_to b) ≫ I.fst b = k (I.snd_to b) ≫ I.snd b) : W ⟶ multiequalizer I := limit.lift _ (multifork.of_ι I _ k h) @[simp, reassoc] lemma lift_ι (W : C) (k : Π a, W ⟶ I.left a) (h : ∀ b, k (I.fst_to b) ≫ I.fst b = k (I.snd_to b) ≫ I.snd b) (a) : multiequalizer.lift I _ k h ≫ multiequalizer.ι I a = k _ := limit.lift_π _ _ @[ext] lemma hom_ext {W : C} (i j : W ⟶ multiequalizer I) (h : ∀ a, i ≫ multiequalizer.ι I a = j ≫ multiequalizer.ι I a) : i = j := limit.hom_ext begin rintro (a|b), { apply h }, simp_rw [← limit.w I.multicospan (walking_multicospan.hom.fst b), ← category.assoc, h], end end multiequalizer namespace multicoequalizer variables (I : multispan_index C) [has_multicoequalizer I] /-- The canonical map from the multiequalizer to the objects on the left. -/ abbreviation π (b : I.R) : I.right b ⟶ multicoequalizer I := colimit.ι I.multispan (walking_multispan.right _) /-- The multicofork associated to the multicoequalizer. -/ abbreviation multicofork : multicofork I := colimit.cocone _ @[simp] lemma multicofork_π (b) : (multicoequalizer.multicofork I).π b = multicoequalizer.π I b := rfl @[simp] lemma multicofork_ι_app_right (b) : (multicoequalizer.multicofork I).ι.app (walking_multispan.right b) = multicoequalizer.π I b := rfl @[reassoc] lemma condition (a) : I.fst a ≫ multicoequalizer.π I (I.fst_from a) = I.snd a ≫ multicoequalizer.π I (I.snd_from a) := multicofork.condition _ _ /-- Construct a morphism from the multicoequalizer from its universal property. -/ abbreviation desc (W : C) (k : Π b, I.right b ⟶ W) (h : ∀ a, I.fst a ≫ k (I.fst_from a) = I.snd a ≫ k (I.snd_from a)) : multicoequalizer I ⟶ W := colimit.desc _ (multicofork.of_π I _ k h) @[simp, reassoc] lemma π_desc (W : C) (k : Π b, I.right b ⟶ W) (h : ∀ a, I.fst a ≫ k (I.fst_from a) = I.snd a ≫ k (I.snd_from a)) (b) : multicoequalizer.π I b ≫ multicoequalizer.desc I _ k h = k _ := colimit.ι_desc _ _ @[ext] lemma hom_ext {W : C} (i j : multicoequalizer I ⟶ W) (h : ∀ b, multicoequalizer.π I b ≫ i = multicoequalizer.π I b ≫ j) : i = j := colimit.hom_ext begin rintro (a|b), { simp_rw [← colimit.w I.multispan (walking_multispan.hom.fst a), category.assoc, h] }, { apply h }, end end multicoequalizer end category_theory.limits
3dafd75e888542cedee39410319e9031b7e6676f
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/topology/uniform_space/basic.lean
bb4e5293a6b43f7fc743b8e76858fc39b634c319
[ "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
70,747
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import order.filter.lift import topology.separation /-! # Uniform spaces Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * uniform continuity (in this file) * completeness (in `cauchy.lean`) * extension of uniform continuous functions to complete spaces (in `uniform_embedding.lean`) * totally bounded sets (in `cauchy.lean`) * totally bounded complete sets are compact (in `cauchy.lean`) A uniform structure on a type `X` is a filter `𝓤 X` on `X × X` satisfying some conditions which makes it reasonable to say that `∀ᶠ (p : X × X) in 𝓤 X, ...` means "for all p.1 and p.2 in X close enough, ...". Elements of this filter are called entourages of `X`. The two main examples are: * If `X` is a metric space, `V ∈ 𝓤 X ↔ ∃ ε > 0, { p | dist p.1 p.2 < ε } ⊆ V` * If `G` is an additive topological group, `V ∈ 𝓤 G ↔ ∃ U ∈ 𝓝 (0 : G), {p | p.2 - p.1 ∈ U} ⊆ V` Those examples are generalizations in two different directions of the elementary example where `X = ℝ` and `V ∈ 𝓤 ℝ ↔ ∃ ε > 0, { p | |p.2 - p.1| < ε } ⊆ V` which features both the topological group structure on `ℝ` and its metric space structure. Each uniform structure on `X` induces a topology on `X` characterized by > `nhds_eq_comap_uniformity : ∀ {x : X}, 𝓝 x = comap (prod.mk x) (𝓤 X)` where `prod.mk x : X → X × X := (λ y, (x, y))` is the partial evaluation of the product constructor. The dictionary with metric spaces includes: * an upper bound for `dist x y` translates into `(x, y) ∈ V` for some `V ∈ 𝓤 X` * a ball `ball x r` roughly corresponds to `uniform_space.ball x V := {y | (x, y) ∈ V}` for some `V ∈ 𝓤 X`, but the later is more general (it includes in particular both open and closed balls for suitable `V`). In particular we have: `is_open_iff_ball_subset {s : set X} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 X, ball x V ⊆ s` The triangle inequality is abstracted to a statement involving the composition of relations in `X`. First note that the triangle inequality in a metric space is equivalent to `∀ (x y z : X) (r r' : ℝ), dist x y ≤ r → dist y z ≤ r' → dist x z ≤ r + r'`. Then, for any `V` and `W` with type `set (X × X)`, the composition `V ○ W : set (X × X)` is defined as `{ p : X × X | ∃ z, (p.1, z) ∈ V ∧ (z, p.2) ∈ W }`. In the metric space case, if `V = { p | dist p.1 p.2 ≤ r }` and `W = { p | dist p.1 p.2 ≤ r' }` then the triangle inequality, as reformulated above, says `V ○ W` is contained in `{p | dist p.1 p.2 ≤ r + r'}` which is the entourage associated to the radius `r + r'`. In general we have `mem_ball_comp (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W)`. Note that this discussion does not depend on any axiom imposed on the uniformity filter, it is simply captured by the definition of composition. The uniform space axioms ask the filter `𝓤 X` to satisfy the following: * every `V ∈ 𝓤 X` contains the diagonal `id_rel = { p | p.1 = p.2 }`. This abstracts the fact that `dist x x ≤ r` for every non-negative radius `r` in the metric space case and also that `x - x` belongs to every neighborhood of zero in the topological group case. * `V ∈ 𝓤 X → prod.swap '' V ∈ 𝓤 X`. This is tightly related the fact that `dist x y = dist y x` in a metric space, and to continuity of negation in the topological group case. * `∀ V ∈ 𝓤 X, ∃ W ∈ 𝓤 X, W ○ W ⊆ V`. In the metric space case, it corresponds to cutting the radius of a ball in half and applying the triangle inequality. In the topological group case, it comes from continuity of addition at `(0, 0)`. These three axioms are stated more abstractly in the definition below, in terms of operations on filters, without directly manipulating entourages. ## Main definitions * `uniform_space X` is a uniform space structure on a type `X` * `uniform_continuous f` is a predicate saying a function `f : α → β` between uniform spaces is uniformly continuous : `∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r` In this file we also define a complete lattice structure on the type `uniform_space X` of uniform structures on `X`, as well as the pullback (`uniform_space.comap`) of uniform structures coming from the pullback of filters. Like distance functions, uniform structures cannot be pushed forward in general. ## Notations Localized in `uniformity`, we have the notation `𝓤 X` for the uniformity on a uniform space `X`, and `○` for composition of relations, seen as terms with type `set (X × X)`. ## Implementation notes There is already a theory of relations in `data/rel.lean` where the main definition is `def rel (α β : Type*) := α → β → Prop`. The relations used in the current file involve only one type, but this is not the reason why we don't reuse `data/rel.lean`. We use `set (α × α)` instead of `rel α α` because we really need sets to use the filter library, and elements of filters on `α × α` have type `set (α × α)`. The structure `uniform_space X` bundles a uniform structure on `X`, a topology on `X` and an assumption saying those are compatible. This may not seem mathematically reasonable at first, but is in fact an instance of the forgetful inheritance pattern. See Note [forgetful inheritance] below. ## References The formalization uses the books: * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] But it makes a more systematic use of the filter library. -/ open set filter classical open_locale classical topological_space filter set_option eqn_compiler.zeta true universes u /-! ### Relations, seen as `set (α × α)` -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp [subset_def]; exact forall_congr (λ a, by simp) /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} localized "infix ` ○ `:55 := comp_rel" in uniformity @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ r₁ ○ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ○ (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ @[mono] lemma comp_rel_mono {f g h k: set (α×α)} (h₁ : f ⊆ h) (h₂ : g ⊆ k) : f ○ g ⊆ h ○ k := λ ⟨x, y⟩ ⟨z, h, h'⟩, ⟨z, h₁ h, h₂ h'⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ s ○ t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : id_rel ○ r = r := set.ext $ assume ⟨a, b⟩, by simp lemma comp_rel_assoc {r s t : set (α×α)} : (r ○ s) ○ t = r ○ (s ○ t) := by ext p; cases p; simp only [mem_comp_rel]; tauto lemma subset_comp_self {α : Type*} {s : set (α × α)} (h : id_rel ⊆ s) : s ⊆ s ○ s := λ ⟨x, y⟩ xy_in, ⟨x, h (by rw mem_id_rel), xy_in⟩ /-- The relation is invariant under swapping factors. -/ def symmetric_rel (V : set (α × α)) : Prop := prod.swap ⁻¹' V = V /-- The maximal symmetric relation contained in a given relation. -/ def symmetrize_rel (V : set (α × α)) : set (α × α) := V ∩ prod.swap ⁻¹' V lemma symmetric_symmetrize_rel (V : set (α × α)) : symmetric_rel (symmetrize_rel V) := by simp [symmetric_rel, symmetrize_rel, preimage_inter, inter_comm, ← preimage_comp] lemma symmetrize_rel_subset_self (V : set (α × α)) : symmetrize_rel V ⊆ V := sep_subset _ _ @[mono] lemma symmetrize_mono {V W: set (α × α)} (h : V ⊆ W) : symmetrize_rel V ⊆ symmetrize_rel W := inter_subset_inter h $ preimage_mono h lemma symmetric_rel_inter {U V : set (α × α)} (hU : symmetric_rel U) (hV : symmetric_rel V) : symmetric_rel (U ∩ V) := begin unfold symmetric_rel at *, rw [preimage_inter, hU, hV], end /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : 𝓟 id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, s ○ s) ≤ uniformity) /-- An alternative constructor for `uniform_space.core`. This version unfolds various `filter`-related definitions. -/ def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U) x, (x, x) ∈ r) (symm : ∀ r ∈ U, prod.swap ⁻¹' r ∈ U) (comp : ∀ r ∈ U, ∃ t ∈ U, t ○ t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity, is_open_univ := by simp; intro; exact univ_mem, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt}, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := by { congr, exact h } -- the topological structure is embedded in the uniform structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity)) /-- Alternative constructor for `uniform_space α` when a topology is already given. -/ @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) : uniform_space α := ⟨c, is_open_uniformity⟩ /-- Construct a `uniform_space` from a `uniform_space.core`. -/ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.rfl } /-- Construct a `uniform_space` from a `u : uniform_space.core` and a `topological_space` structure that is equal to `u.to_topological_space`. -/ def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.rfl } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] @[ext] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity (α : Type u) [uniform_space α] : filter (α × α) := (@uniform_space.to_core α _).uniformity localized "notation `𝓤` := uniformity" in uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : 𝓟 id_rel ≤ 𝓤 α := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) : (x, x) ∈ s := refl_le_uniformity h rfl lemma mem_uniformity_of_eq {x y : α} {s : set (α × α)} (h : s ∈ 𝓤 α) (hx : x = y) : (x, y) ∈ s := hx ▸ refl_mem_uniformity h lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), s ○ s) ≤ 𝓤 α := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) := symm_le_uniformity lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, t ○ t ⊆ s := have s ∈ (𝓤 α).lift' (λt:set (α×α), t ○ t), from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is transitive. -/ lemma filter.tendsto.uniformity_trans {l : filter β} {f₁ f₂ f₃ : β → α} (h₁₂ : tendsto (λ x, (f₁ x, f₂ x)) l (𝓤 α)) (h₂₃ : tendsto (λ x, (f₂ x, f₃ x)) l (𝓤 α)) : tendsto (λ x, (f₁ x, f₃ x)) l (𝓤 α) := begin refine le_trans (le_lift' $ λ s hs, mem_map.2 _) comp_le_uniformity, filter_upwards [h₁₂ hs, h₂₃ hs], exact λ x hx₁₂ hx₂₃, ⟨_, hx₁₂, hx₂₃⟩ end /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is symmetric -/ lemma filter.tendsto.uniformity_symm {l : filter β} {f : β → α × α} (h : tendsto f l (𝓤 α)) : tendsto (λ x, ((f x).2, (f x).1)) l (𝓤 α) := tendsto_swap_uniformity.comp h /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is reflexive. -/ lemma tendsto_diag_uniformity (f : β → α) (l : filter β) : tendsto (λ x, (f x, f x)) l (𝓤 α) := assume s hs, mem_map.2 $ univ_mem' $ λ x, refl_mem_uniformity hs lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) := tendsto_diag_uniformity (λ _, a) f lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem hs this, λ a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ t ○ t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α := by rw [map_swap_eq_comap_swap]; from map_le_iff_le_comap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α := le_antisymm uniformity_le_symm symm_le_uniformity lemma symmetrize_mem_uniformity {V : set (α × α)} (h : V ∈ 𝓤 α) : symmetrize_rel V ∈ 𝓤 α := begin apply (𝓤 α).inter_sets h, rw [← image_swap_eq_preimage_swap, uniformity_eq_symm], exact image_mem_map h, end theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f := calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f) : (𝓤 α).lift (λs, f (s ○ s)) ≤ (𝓤 α).lift f := calc (𝓤 α).lift (λs, f (s ○ s)) = ((𝓤 α).lift' (λs:set (α×α), s ○ s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : (𝓤 α).lift' (λs:set (α×α), s ○ (s ○ s)) ≤ (𝓤 α) := calc (𝓤 α).lift' (λd, d ○ (d ○ d)) = (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ (t ○ t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), s ○ t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (𝓟 ∘ (○) s) $ monotone_principal.comp (monotone_comp_rel monotone_const monotone_id) ... = (𝓤 α).lift' (λs:set(α×α), s ○ s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ (𝓤 α) : comp_le_uniformity lemma comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ⊆ s := begin obtain ⟨w, w_in, w_sub⟩ : ∃ w ∈ 𝓤 α, w ○ w ⊆ s := comp_mem_uniformity_sets hs, use [symmetrize_rel w, symmetrize_mem_uniformity w_in, symmetric_symmetrize_rel w], have : symmetrize_rel w ⊆ w := symmetrize_rel_subset_self w, calc symmetrize_rel w ○ symmetrize_rel w ⊆ w ○ w : by mono ... ⊆ s : w_sub, end lemma subset_comp_self_of_mem_uniformity {s : set (α × α)} (h : s ∈ 𝓤 α) : s ⊆ s ○ s := subset_comp_self (refl_le_uniformity h) lemma comp_comp_symm_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, symmetric_rel t ∧ t ○ t ○ t ⊆ s := begin rcases comp_symm_mem_uniformity_sets hs with ⟨w, w_in, w_symm, w_sub⟩, rcases comp_symm_mem_uniformity_sets w_in with ⟨t, t_in, t_symm, t_sub⟩, use [t, t_in, t_symm], have : t ⊆ t ○ t := subset_comp_self_of_mem_uniformity t_in, calc t ○ t ○ t ⊆ w ○ t : by mono ... ⊆ w ○ (t ○ t) : by mono ... ⊆ w ○ w : by mono ... ⊆ s : w_sub, end /-! ### Balls in uniform spaces -/ /-- The ball around `(x : β)` with respect to `(V : set (β × β))`. Intended to be used for `V ∈ 𝓤 β`, but this is not needed for the definition. Recovers the notions of metric space ball when `V = {p | dist p.1 p.2 < r }`. -/ def uniform_space.ball (x : β) (V : set (β × β)) : set β := (prod.mk x) ⁻¹' V open uniform_space (ball) lemma uniform_space.mem_ball_self (x : α) {V : set (α × α)} (hV : V ∈ 𝓤 α) : x ∈ ball x V := refl_mem_uniformity hV /-- The triangle inequality for `uniform_space.ball` -/ lemma mem_ball_comp {V W : set (β × β)} {x y z} (h : y ∈ ball x V) (h' : z ∈ ball y W) : z ∈ ball x (V ○ W) := prod_mk_mem_comp_rel h h' lemma ball_subset_of_comp_subset {V W : set (β × β)} {x y} (h : x ∈ ball y W) (h' : W ○ W ⊆ V) : ball x W ⊆ ball y V := λ z z_in, h' (mem_ball_comp h z_in) lemma ball_mono {V W : set (β × β)} (h : V ⊆ W) (x : β) : ball x V ⊆ ball x W := by tauto lemma ball_inter_left (x : β) (V W : set (β × β)) : ball x (V ∩ W) ⊆ ball x V := ball_mono (inter_subset_left V W) x lemma ball_inter_right (x : β) (V W : set (β × β)) : ball x (V ∩ W) ⊆ ball x W := ball_mono (inter_subset_right V W) x lemma mem_ball_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x y} : x ∈ ball y V ↔ y ∈ ball x V := show (x, y) ∈ prod.swap ⁻¹' V ↔ (x, y) ∈ V, by { unfold symmetric_rel at hV, rw hV } lemma ball_eq_of_symmetry {V : set (β × β)} (hV : symmetric_rel V) {x} : ball x V = {y | (y, x) ∈ V} := by { ext y, rw mem_ball_symmetry hV, exact iff.rfl } lemma mem_comp_of_mem_ball {V W : set (β × β)} {x y z : β} (hV : symmetric_rel V) (hx : x ∈ ball z V) (hy : y ∈ ball z W) : (x, y) ∈ V ○ W := begin rw mem_ball_symmetry hV at hx, exact ⟨z, hx, hy⟩ end lemma uniform_space.is_open_ball (x : α) {V : set (α × α)} (hV : is_open V) : is_open (ball x V) := hV.preimage $ continuous_const.prod_mk continuous_id lemma mem_comp_comp {V W M : set (β × β)} (hW' : symmetric_rel W) {p : β × β} : p ∈ V ○ M ○ W ↔ ((ball p.1 V).prod (ball p.2 W) ∩ M).nonempty := begin cases p with x y, split, { rintros ⟨z, ⟨w, hpw, hwz⟩, hzy⟩, exact ⟨(w, z), ⟨hpw, by rwa mem_ball_symmetry hW'⟩, hwz⟩, }, { rintro ⟨⟨w, z⟩, ⟨w_in, z_in⟩, hwz⟩, rwa mem_ball_symmetry hW' at z_in, use [z, w] ; tauto }, end /-! ### Neighborhoods in uniform spaces -/ lemma mem_nhds_uniformity_iff_right {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α := ⟨ begin simp only [mem_nhds_iff, is_open_uniformity, and_imp, exists_imp_distrib], exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ t ○ t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma mem_nhds_uniformity_iff_left {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.2 = x → p.1 ∈ s} ∈ 𝓤 α := by { rw [uniformity_eq_symm, mem_nhds_uniformity_iff_right], refl } lemma nhds_eq_comap_uniformity_aux {α : Type u} {x : α} {s : set α} {F : filter (α × α)} : {p : α × α | p.fst = x → p.snd ∈ s} ∈ F ↔ s ∈ comap (prod.mk x) F := by rw mem_comap ; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, F.sets_of_superset h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma nhds_eq_comap_uniformity {x : α} : 𝓝 x = (𝓤 α).comap (prod.mk x) := by { ext s, rw [mem_nhds_uniformity_iff_right], exact nhds_eq_comap_uniformity_aux } /-- See also `is_open_iff_open_ball_subset`. -/ lemma is_open_iff_ball_subset {s : set α} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, ball x V ⊆ s := begin simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity], exact iff.rfl, end lemma nhds_basis_uniformity' {p : ι → Prop} {s : ι → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} : (𝓝 x).has_basis p (λ i, ball x (s i)) := by { rw [nhds_eq_comap_uniformity], exact h.comap (prod.mk x) } lemma nhds_basis_uniformity {p : ι → Prop} {s : ι → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} : (𝓝 x).has_basis p (λ i, {y | (y, x) ∈ s i}) := begin replace h := h.comap prod.swap, rw [← map_swap_eq_comap_swap, ← uniformity_eq_symm] at h, exact nhds_basis_uniformity' h end lemma uniform_space.mem_nhds_iff {x : α} {s : set α} : s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, ball x V ⊆ s := begin rw [nhds_eq_comap_uniformity, mem_comap], exact iff.rfl, end lemma uniform_space.ball_mem_nhds (x : α) ⦃V : set (α × α)⦄ (V_in : V ∈ 𝓤 α) : ball x V ∈ 𝓝 x := begin rw uniform_space.mem_nhds_iff, exact ⟨V, V_in, subset.refl _⟩ end lemma uniform_space.mem_nhds_iff_symm {x : α} {s : set α} : s ∈ 𝓝 x ↔ ∃ V ∈ 𝓤 α, symmetric_rel V ∧ ball x V ⊆ s := begin rw uniform_space.mem_nhds_iff, split, { rintros ⟨V, V_in, V_sub⟩, use [symmetrize_rel V, symmetrize_mem_uniformity V_in, symmetric_symmetrize_rel V], exact subset.trans (ball_mono (symmetrize_rel_subset_self V) x) V_sub }, { rintros ⟨V, V_in, V_symm, V_sub⟩, exact ⟨V, V_in, V_sub⟩ } end lemma uniform_space.has_basis_nhds (x : α) : has_basis (𝓝 x) (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) (λ s, ball x s) := ⟨λ t, by simp [uniform_space.mem_nhds_iff_symm, and_assoc]⟩ open uniform_space lemma uniform_space.mem_closure_iff_symm_ball {s : set α} {x} : x ∈ closure s ↔ ∀ {V}, V ∈ 𝓤 α → symmetric_rel V → (s ∩ ball x V).nonempty := by simp [mem_closure_iff_nhds_basis (has_basis_nhds x), set.nonempty] lemma uniform_space.mem_closure_iff_ball {s : set α} {x} : x ∈ closure s ↔ ∀ {V}, V ∈ 𝓤 α → (ball x V ∩ s).nonempty := by simp [mem_closure_iff_nhds_basis' (nhds_basis_uniformity' (𝓤 α).basis_sets)] lemma uniform_space.has_basis_nhds_prod (x y : α) : has_basis (𝓝 (x, y)) (λ s, s ∈ 𝓤 α ∧ symmetric_rel s) $ λ s, (ball x s).prod (ball y s) := begin rw nhds_prod_eq, apply (has_basis_nhds x).prod' (has_basis_nhds y), rintro U V ⟨U_in, U_symm⟩ ⟨V_in, V_symm⟩, exact ⟨U ∩ V, ⟨(𝓤 α).inter_sets U_in V_in, symmetric_rel_inter U_symm V_symm⟩, ball_inter_left x U V, ball_inter_right y U V⟩, end lemma nhds_eq_uniformity {x : α} : 𝓝 x = (𝓤 α).lift' (ball x) := (nhds_basis_uniformity' (𝓤 α).basis_sets).eq_binfi lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {y : α | (x, y) ∈ s} ∈ 𝓝 x := ball_mem_nhds x h lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {x : α | (x, y) ∈ s} ∈ 𝓝 y := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (𝓝 a) (𝓤 α) := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (𝓝 a) (𝓤 α) := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_principal.comp $ monotone_preimage.comp monotone_preimage ) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ hg.comp monotone_preimage ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : 𝓝 a ×ᶠ 𝓝 b = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (𝓝 a).lift (λs:set α, (𝓝 b).lift (λt:set α, 𝓟 (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_principal.comp (monotone_prod monotone_const monotone_id), exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : 𝓝 (a, b) = (𝓤 α).lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, _root_.mem_nhds_iff.mp $ show cl_d ∈ 𝓝 (x, y), begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end /-- Entourages are neighborhoods of the diagonal. -/ lemma nhds_le_uniformity (x : α) : 𝓝 (x, x) ≤ 𝓤 α := begin intros V V_in, rcases comp_symm_mem_uniformity_sets V_in with ⟨w, w_in, w_symm, w_sub⟩, have : (ball x w).prod (ball x w) ∈ 𝓝 (x, x), { rw nhds_prod_eq, exact prod_mem_prod (ball_mem_nhds x w_in) (ball_mem_nhds x w_in) }, apply mem_of_superset this, rintros ⟨u, v⟩ ⟨u_in, v_in⟩, exact w_sub (mem_comp_of_mem_ball w_symm u_in v_in) end /-- Entourages are neighborhoods of the diagonal. -/ lemma supr_nhds_le_uniformity : (⨆ x : α, 𝓝 (x, x)) ≤ 𝓤 α := supr_le nhds_le_uniformity /-! ### Closure and interior in uniform spaces -/ lemma closure_eq_uniformity (s : set $ α × α) : closure s = ⋂ V ∈ {V | V ∈ 𝓤 α ∧ symmetric_rel V}, V ○ s ○ V := begin ext ⟨x, y⟩, simp_rw [mem_closure_iff_nhds_basis (uniform_space.has_basis_nhds_prod x y), mem_Inter, mem_set_of_eq], apply forall_congr, intro V, apply forall_congr, rintros ⟨V_in, V_symm⟩, simp_rw [mem_comp_comp V_symm, inter_comm, exists_prop], exact iff.rfl, end lemma uniformity_has_basis_closed : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_closed V) id := begin refine filter.has_basis_self.2 (λ t h, _), rcases comp_comp_symm_mem_uniformity_sets h with ⟨w, w_in, w_symm, r⟩, refine ⟨closure w, mem_of_superset w_in subset_closure, is_closed_closure, _⟩, refine subset.trans _ r, rw closure_eq_uniformity, apply Inter_subset_of_subset, apply Inter_subset, exact ⟨w_in, w_symm⟩ end /-- Closed entourages form a basis of the uniformity filter. -/ lemma uniformity_has_basis_closure : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α) closure := ⟨begin intro t, rw uniformity_has_basis_closed.mem_iff, split, { rintros ⟨r, ⟨r_in, r_closed⟩, r_sub⟩, use [r, r_in], convert r_sub, rw r_closed.closure_eq, refl }, { rintros ⟨r, r_in, r_sub⟩, exact ⟨closure r, ⟨mem_of_superset r_in subset_closure, is_closed_closure⟩, r_sub⟩ } end⟩ lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d ∈ 𝓤 α, d ○ (t ○ d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (𝓝 (a, b) ⊓ 𝓟 t ≠ ⊥) : mem_closure_iff_nhds_ne_bot ... ↔ (((@prod.swap α α) <$> 𝓤 α).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) (𝓤 α)).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : by refl ... ↔ ((𝓤 α).lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ 𝓟 t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s ∈ 𝓤 α, (set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t).nonempty) : begin rw [lift'_inf_principal_eq, ← ne_bot_iff, lift'_ne_bot_iff], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀ s ∈ 𝓤 α, (a, b) ∈ s ○ (t ○ s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure) (calc (𝓤 α).lift' closure ≤ (𝓤 α).lift' (λd, d ○ (d ○ d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ (𝓤 α) : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ λ x (hx : x ∈ t), let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp hx in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ 𝓤 α, by filter_upwards [hs] this, by simp [this]) (assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : interior s ∈ 𝓤 α := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed {s : set (α×α)} (h : s ∈ 𝓤 α) : ∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s := let ⟨t, ⟨ht_mem, htc⟩, hts⟩ := uniformity_has_basis_closed.mem_iff.1 h in ⟨t, ht_mem, htc, hts⟩ lemma is_open_iff_open_ball_subset {s : set α} : is_open s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, is_open V ∧ ball x V ⊆ s := begin rw is_open_iff_ball_subset, split; intros h x hx, { obtain ⟨V, hV, hV'⟩ := h x hx, exact ⟨interior V, interior_mem_uniformity hV, is_open_interior, (ball_mono interior_subset x).trans hV'⟩, }, { obtain ⟨V, hV, -, hV'⟩ := h x hx, exact ⟨V, hV, hV'⟩, }, end /-- The uniform neighborhoods of all points of a dense set cover the whole space. -/ lemma dense.bUnion_uniformity_ball {s : set α} {U : set (α × α)} (hs : dense s) (hU : U ∈ 𝓤 α) : (⋃ x ∈ s, ball x U) = univ := begin refine bUnion_eq_univ_iff.2 (λ y, _), rcases hs.inter_nhds_nonempty (mem_nhds_right y hU) with ⟨x, hxs, hxy : (x, y) ∈ U⟩, exact ⟨x, hxs, hxy⟩ end /-! ### Uniformity bases -/ /-- Open elements of `𝓤 α` form a basis of `𝓤 α`. -/ lemma uniformity_has_basis_open : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_open V) id := has_basis_self.2 $ λ s hs, ⟨interior s, interior_mem_uniformity hs, is_open_interior, interior_subset⟩ lemma filter.has_basis.mem_uniformity_iff {p : β → Prop} {s : β → set (α×α)} (h : (𝓤 α).has_basis p s) {t : set (α × α)} : t ∈ 𝓤 α ↔ ∃ i (hi : p i), ∀ a b, (a, b) ∈ s i → (a, b) ∈ t := h.mem_iff.trans $ by simp only [prod.forall, subset_def] /-- Symmetric entourages form a basis of `𝓤 α` -/ lemma uniform_space.has_basis_symmetric : (𝓤 α).has_basis (λ s : set (α × α), s ∈ 𝓤 α ∧ symmetric_rel s) id := has_basis_self.2 $ λ t t_in, ⟨symmetrize_rel t, symmetrize_mem_uniformity t_in, symmetric_symmetrize_rel t, symmetrize_rel_subset_self t⟩ /-- Open elements `s : set (α × α)` of `𝓤 α` such that `(x, y) ∈ s ↔ (y, x) ∈ s` form a basis of `𝓤 α`. -/ lemma uniformity_has_basis_open_symmetric : has_basis (𝓤 α) (λ V : set (α × α), V ∈ 𝓤 α ∧ is_open V ∧ symmetric_rel V) id := begin simp only [← and_assoc], refine uniformity_has_basis_open.restrict (λ s hs, ⟨symmetrize_rel s, _⟩), exact ⟨⟨symmetrize_mem_uniformity hs.1, is_open.inter hs.2 (hs.2.preimage continuous_swap)⟩, symmetric_symmetrize_rel s, symmetrize_rel_subset_self s⟩ end lemma uniform_space.has_seq_basis (h : is_countably_generated $ 𝓤 α) : ∃ V : ℕ → set (α × α), has_antitone_basis (𝓤 α) (λ _, true) V ∧ ∀ n, symmetric_rel (V n) := let ⟨U, hsym, hbasis⟩ := h.exists_antitone_subbasis uniform_space.has_basis_symmetric in ⟨U, hbasis, λ n, (hsym n).2⟩ lemma filter.has_basis.bInter_bUnion_ball {p : ι → Prop} {U : ι → set (α × α)} (h : has_basis (𝓤 α) p U) (s : set α) : (⋂ i (hi : p i), ⋃ x ∈ s, ball x (U i)) = closure s := begin ext x, simp [mem_closure_iff_nhds_basis (nhds_basis_uniformity h), ball] end /-! ### Uniform continuity -/ /-- A function `f : α → β` is *uniformly continuous* if `(f x, f y)` tends to the diagonal as `(x, y)` tends to the diagonal. In other words, if `x` is sufficiently close to `y`, then `f x` is close to `f y` no matter where `x` and `y` are located in `α`. -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β) /-- A function `f : α → β` is *uniformly continuous* on `s : set α` if `(f x, f y)` tends to the diagonal as `(x, y)` tends to the diagonal while remaining in `s.prod s`. In other words, if `x` is sufficiently close to `y`, then `f x` is close to `f y` no matter where `x` and `y` are located in `s`.-/ def uniform_continuous_on [uniform_space β] (f : α → β) (s : set α) : Prop := tendsto (λ x : α × α, (f x.1, f x.2)) (𝓤 α ⊓ principal (s.prod s)) (𝓤 β) theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, { x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α := iff.rfl theorem uniform_continuous_iff_eventually [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, ∀ᶠ (x : α × α) in 𝓤 α, (f x.1, f x.2) ∈ r := iff.rfl theorem uniform_continuous_on_univ [uniform_space β] {f : α → β} : uniform_continuous_on f univ ↔ uniform_continuous f := by rw [uniform_continuous_on, uniform_continuous, univ_prod_univ, principal_univ, inf_top_eq] lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) : uniform_continuous c := have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b, le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem]) refl_le_uniformity lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := uniform_continuous_of_const $ λ _ _, rfl lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) := hg.comp hf lemma filter.has_basis.uniform_continuous_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t) {f : α → β} : uniform_continuous f ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y, (x, y) ∈ s j → (f x, f y) ∈ t i := (ha.tendsto_iff hb).trans $ by simp only [prod.forall] lemma filter.has_basis.uniform_continuous_on_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t) {f : α → β} {S : set α} : uniform_continuous_on f S ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y ∈ S, (x, y) ∈ s j → (f x, f y) ∈ t i := ((ha.inf_principal (S.prod S)).tendsto_iff hb).trans $ by finish [prod.forall] end uniform_space open_locale uniformity section constructions instance : partial_order (uniform_space α) := { le := λt s, t.uniformity ≤ s.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, le_trans h₁ h₂ } instance : has_Inf (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma Inf_le {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : Inf tt ≤ t := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma le_Inf {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t ≤ t') : t ≤ Inf tt := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_top (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_bot (uniform_space α) := ⟨{ to_topological_space := ⊥, uniformity := 𝓟 id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], {simp}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩ instance : complete_lattice (uniform_space α) := { sup := λa b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf (λ _ ⟨h, _⟩, h), le_sup_right := λ a b, le_Inf (λ _ ⟨_, h⟩, h), sup_le := λ a b c h₁ h₂, Inf_le ⟨h₁, h₂⟩, inf := λ a b, Inf {a, b}, le_inf := λ a b c h₁ h₂, le_Inf (λ u h, by { cases h, exact h.symm ▸ h₁, exact (mem_singleton_iff.1 h).symm ▸ h₂ }), inf_le_left := λ a b, Inf_le (by simp), inf_le_right := λ a b, Inf_le (by simp), top := ⊤, le_top := λ a, show a.uniformity ≤ ⊤, from le_top, bot := ⊥, bot_le := λ u, u.refl, Sup := λ tt, Inf {t | ∀ t' ∈ tt, t' ≤ t}, le_Sup := λ s u h, le_Inf (λ u' h', h' u h), Sup_le := λ s u h, Inf_le h, Inf := Inf, le_Inf := λ s a hs, le_Inf hs, Inf_le := λ s a ha, Inf_le ha, ..uniform_space.partial_order } lemma infi_uniformity {ι : Sort*} {u : ι → uniform_space α} : (infi u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _) lemma inf_uniformity {u v : uniform_space α} : (u ⊓ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊓ v) = (⨅i (h : i = u ∨ i = v), i), by simp [infi_or, infi_inf_eq], calc (u ⊓ v).uniformity = ((⨅i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [infi_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊥⟩ instance inhabited_uniform_space_core : inhabited (uniform_space.core α) := ⟨@uniform_space.to_core _ (default _)⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl), symm := by simp [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_swap_uniformity.comp tendsto_comap, comp := le_trans begin rw [comap_lift'_eq, comap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (comap_mono u.comp), is_open_uniformity := λ s, begin change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced, mem_nhds_uniformity_iff_right, filter.comap, and_comm], refine ball_congr (λ x hx, ⟨_, _⟩), { rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩, rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) }, { rintro ⟨t, ht, hts⟩, exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl, mem_nhds_uniformity_iff_right.1 $ mem_nhds_left _ ht⟩ } end } lemma uniformity_comap [uniform_space α] [uniform_space β] {f : α → β} (h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) : 𝓤 α = comap (prod.map f f) (𝓤 β) := by { rw h, refl } lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id := by ext u ; dsimp [uniform_space.comap] ; rw [prod.id_prod, filter.comap_id] lemma uniform_space.comap_comap {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} : uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) := by ext ; dsimp [uniform_space.comap] ; rw filter.comap_comap lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] {f : α → β} : uniform_continuous f ↔ uα ≤ uβ.comap f := filter.map_le_iff_le_comap lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.comap f u) u f := tendsto_comap theorem to_topological_space_comap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.comap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := rfl lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g := tendsto_comap_iff.2 h lemma to_nhds_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) (a : α) : @nhds _ (@uniform_space.to_topological_space _ u₁) a ≤ @nhds _ (@uniform_space.to_topological_space _ u₂) a := by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h le_rfl) lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ to_nhds_mono h lemma uniform_continuous.continuous [uniform_space α] [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_le_induced.mpr $ to_topological_space_mono $ uniform_continuous_iff.1 hf lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := rfl lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := top_unique $ assume s hs, s.eq_empty_or_nonempty.elim (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊤) (assume ⟨x, hx⟩, have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl, this.symm ▸ @is_open_univ _ ⊤) lemma to_topological_space_infi {ι : Sort*} {u : ι → uniform_space α} : (infi u).to_topological_space = ⨅i, (u i).to_topological_space := begin casesI is_empty_or_nonempty ι, { rw [infi_of_empty, infi_of_empty, to_topological_space_top] }, { refine (eq_of_nhds_eq_nhds $ assume a, _), rw [nhds_infi, nhds_eq_uniformity], change (infi u).uniformity.lift' (preimage $ prod.mk a) = _, rw [infi_uniformity, lift'_infi], { simp only [nhds_eq_uniformity], refl }, { exact assume a b, rfl } }, end lemma to_topological_space_Inf {s : set (uniform_space α)} : (Inf s).to_topological_space = (⨅i∈s, @uniform_space.to_topological_space α i) := begin rw [Inf_eq_infi], simp only [← to_topological_space_infi], end lemma to_topological_space_inf {u v : uniform_space α} : (u ⊓ v).to_topological_space = u.to_topological_space ⊓ v.to_topological_space := by rw [to_topological_space_Inf, infi_pair] instance : uniform_space empty := ⊥ instance : uniform_space punit := ⊥ instance : uniform_space bool := ⊥ instance : uniform_space ℕ := ⊥ instance : uniform_space ℤ := ⊥ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.comap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : 𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_comap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_comap' hf lemma uniform_continuous_on_iff_restrict [uniform_space α] [uniform_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ uniform_continuous (s.restrict f) := begin unfold uniform_continuous_on set.restrict uniform_continuous tendsto, rw [show (λ x : s × s, (f x.1, f x.2)) = prod.map f f ∘ coe, by ext x; cases x; refl, uniformity_comap rfl, show prod.map subtype.val subtype.val = (coe : s × s → α × α), by ext x; cases x; refl], conv in (map _ (comap _ _)) { rw ← filter.map_map }, rw subtype_coe_map_comap_prod, refl, end lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ 𝓝 a) : tendsto f (𝓝 a) (𝓝 (f a)) := by rw [(@map_nhds_subtype_coe_eq α _ s a (mem_of_mem_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _) lemma uniform_continuous_on.continuous_on [uniform_space α] [uniform_space β] {f : α → β} {s : set α} (h : uniform_continuous_on f s) : continuous_on f s := begin rw uniform_continuous_on_iff_restrict at h, rw continuous_on_iff_continuous_restrict, exact h.continuous end section prod /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_topological_space : by rw [to_topological_space_inf, to_topological_space_comap, to_topological_space_comap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : 𝓤 (α × β) = (𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ (𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := inf_uniformity lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : 𝓤 (α×β) = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (𝓤 α ×ᶠ 𝓤 β) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_comap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap, comap_comap] lemma mem_map_iff_exists_image' {α : Type*} {β : Type*} {f : filter α} {m : α → β} {t : set β} : t ∈ (map m f).sets ↔ (∃s∈f, m '' s ⊆ t) := mem_map_iff_exists_image lemma mem_uniformity_of_uniform_continuous_invariant [uniform_space α] {s:set (α×α)} {f : α → α → α} (hf : uniform_continuous (λp:α×α, f p.1 p.2)) (hs : s ∈ 𝓤 α) : ∃u∈𝓤 α, ∀a b c, (a, b) ∈ u → (f a c, f b c) ∈ s := begin rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf, rcases mem_map_iff_exists_image'.1 (hf hs) with ⟨t, ht, hts⟩, clear hf, rcases mem_prod_iff.1 ht with ⟨u, hu, v, hv, huvt⟩, clear ht, refine ⟨u, hu, assume a b c hab, hts $ (mem_image _ _ _).2 ⟨⟨⟨a, b⟩, ⟨c, c⟩⟩, huvt ⟨_, _⟩, _⟩⟩, exact hab, exact refl_mem_uniformity hv, refl end lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) := by rw [uniformity_prod]; exact inter_mem_inf (preimage_mem_comap ha) (preimage_mem_comap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) := le_trans (map_mono (@inf_le_left (uniform_space (α×β)) _ _ _)) map_comap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) := le_trans (map_mono (@inf_le_right (uniform_space (α×β)) _ _ _)) map_comap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd variables [uniform_space α] [uniform_space β] [uniform_space γ] lemma uniform_continuous.prod_mk {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) : uniform_continuous (λ a, f (a,b)) := h.comp (uniform_continuous_id.prod_mk uniform_continuous_const) lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) : uniform_continuous (λ b, f (a,b)) := h.comp (uniform_continuous_const.prod_mk uniform_continuous_id) lemma uniform_continuous.prod_map [uniform_space δ] {f : α → γ} {g : β → δ} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (prod.map f g) := (hf.comp uniform_continuous_fst).prod_mk (hg.comp uniform_continuous_snd) lemma to_topological_space_prod {α} {β} [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl end prod section open uniform_space function variables {δ' : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] [uniform_space δ'] local notation f `∘₂` g := function.bicompr f g /-- Uniform continuity for functions of two variables. -/ def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (uncurry f) lemma uniform_continuous₂_def (f : α → β → γ) : uniform_continuous₂ f ↔ uniform_continuous (uncurry f) := iff.rfl lemma uniform_continuous₂.uniform_continuous {f : α → β → γ} (h : uniform_continuous₂ f) : uniform_continuous (uncurry f) := h lemma uniform_continuous₂_curry (f : α × β → γ) : uniform_continuous₂ (function.curry f) ↔ uniform_continuous f := by rw [uniform_continuous₂, uncurry_curry] lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ} (hg : uniform_continuous g) (hf : uniform_continuous₂ f) : uniform_continuous₂ (g ∘₂ f) := hg.comp hf lemma uniform_continuous₂.bicompl {f : α → β → γ} {ga : δ → α} {gb : δ' → β} (hf : uniform_continuous₂ f) (hga : uniform_continuous ga) (hgb : uniform_continuous gb) : uniform_continuous₂ (bicompl f ga gb) := hf.uniform_continuous.comp (hga.prod_map hgb) end lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl section sum variables [uniform_space α] [uniform_space β] open sum /-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained by taking independently an entourage of the diagonal in the first part, and an entourage of the diagonal in the second part. -/ def uniform_space.core.sum : uniform_space.core (α ⊕ β) := uniform_space.core.mk' (map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β)) (λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂]) (λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩) (λ r ⟨Hrα, Hrβ⟩, begin rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩, rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩, refine ⟨_, ⟨mem_map_iff_exists_image.2 ⟨tα, htα, subset_union_left _ _⟩, mem_map_iff_exists_image.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩, rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩, ⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩, { have A : (a, c) ∈ tα ○ tα := ⟨b, hab, hbc⟩, exact Htα A }, { have A : (a, c) ∈ tβ ○ tβ := ⟨b, hab, hbc⟩, exact Htβ A } end) /-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage of the diagonal. -/ lemma union_mem_uniformity_sum {a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) : ((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈ (@uniform_space.core.sum α β _ _).uniformity := ⟨mem_map_iff_exists_image.2 ⟨_, ha, subset_union_left _ _⟩, mem_map_iff_exists_image.2 ⟨_, hb, subset_union_right _ _⟩⟩ /- To prove that the topology defined by the uniform structure on the disjoint union coincides with the disjoint union topology, we need two lemmas saying that open sets can be characterized by the uniform structure -/ lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) : { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity := begin cases x, { refine mem_of_superset (union_mem_uniformity_sum (mem_nhds_uniformity_iff_right.1 (is_open.mem_nhds hs.1 xs)) univ_mem) (union_subset _ _); rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, { refine mem_of_superset (union_mem_uniformity_sum univ_mem (mem_nhds_uniformity_iff_right.1 (is_open.mem_nhds hs.2 xs))) (union_subset _ _); rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, end lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)} (hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity) : is_open s := begin split, { refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff_right.2 _), rcases mem_map_iff_exists_image.1 (hs _ ha).1 with ⟨t, ht, st⟩, refine mem_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }, { refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff_right.2 _), rcases mem_map_iff_exists_image.1 (hs _ hb).2 with ⟨t, ht, st⟩, refine mem_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl } end /- We can now define the uniform structure on the disjoint union -/ instance sum.uniform_space : uniform_space (α ⊕ β) := { to_core := uniform_space.core.sum, is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ } lemma sum.uniformity : 𝓤 (α ⊕ β) = map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl end sum end constructions -- For a version of the Lebesgue number lemma assuming only a sequentially compact space, -- see topology/sequences.lean /-- Let `c : ι → set α` be an open cover of a compact set `s`. Then there exists an entourage `n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `c i`. -/ lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α} (hs : is_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i := begin let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ m ○ n} ⊆ c i}, have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n), { refine λ n hn, is_open_uniformity.2 _, rintro x ⟨i, m, hm, h⟩, rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩, apply (𝓤 α).sets_of_superset hm', rintros ⟨x, y⟩ hp rfl, refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩, dsimp at hz ⊢, rw comp_rel_assoc, exact ⟨y, hp, hz⟩ }, have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n, { intros x hx, rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩, rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩, exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ }, rcases hs.elim_finite_subcover_image hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩, refine ⟨_, (bInter_mem b_fin).2 bu, λ x hx, _⟩, rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩, refine ⟨i, λ y hy, h _⟩, exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy) end /-- Let `c : set (set α)` be an open cover of a compact set `s`. Then there exists an entourage `n` such that for each `x ∈ s` its `n`-neighborhood is contained in some `t ∈ c`. -/ lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : is_compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma hs (by simpa) hc₂ /-- A useful consequence of the Lebesgue number lemma: given any compact set `K` contained in an open set `U`, we can find an (open) entourage `V` such that the ball of size `V` about any point of `K` is contained in `U`. -/ lemma lebesgue_number_of_compact_open [uniform_space α] {K U : set α} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V ∈ 𝓤 α, is_open V ∧ ∀ x ∈ K, uniform_space.ball x V ⊆ U := begin let W : K → set (α × α) := λ k, classical.some $ is_open_iff_open_ball_subset.mp hU k.1 $ hKU k.2, have hW : ∀ k, W k ∈ 𝓤 α ∧ is_open (W k) ∧ uniform_space.ball k.1 (W k) ⊆ U, { intros k, obtain ⟨h₁, h₂, h₃⟩ := classical.some_spec (is_open_iff_open_ball_subset.mp hU k.1 (hKU k.2)), exact ⟨h₁, h₂, h₃⟩, }, let c : K → set α := λ k, uniform_space.ball k.1 (W k), have hc₁ : ∀ k, is_open (c k), { exact λ k, uniform_space.is_open_ball k.1 (hW k).2.1, }, have hc₂ : K ⊆ ⋃ i, c i, { intros k hk, simp only [mem_Union, set_coe.exists], exact ⟨k, hk, uniform_space.mem_ball_self k (hW ⟨k, hk⟩).1⟩, }, have hc₃ : ∀ k, c k ⊆ U, { exact λ k, (hW k).2.2, }, obtain ⟨V, hV, hV'⟩ := lebesgue_number_lemma hK hc₁ hc₂, refine ⟨interior V, interior_mem_uniformity hV, is_open_interior, _⟩, intros k hk, obtain ⟨k', hk'⟩ := hV' k hk, exact ((ball_mono interior_subset k).trans hk').trans (hc₃ k'), end /-! ### Expressing continuity properties in uniform spaces We reformulate the various continuity properties of functions taking values in a uniform space in terms of the uniformity in the target. Since the same lemmas (essentially with the same names) also exist for metric spaces and emetric spaces (reformulating things in terms of the distance or the edistance in the target), we put them in a namespace `uniform` here. In the metric and emetric space setting, there are also similar lemmas where one assumes that both the source and the target are metric spaces, reformulating things in terms of the distance on both sides. These lemmas are generally written without primes, and the versions where only the target is a metric space is primed. We follow the same convention here, thus giving lemmas with primes. -/ namespace uniform variables [uniform_space α] theorem tendsto_nhds_right {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ tendsto (λ x, (a, u x)) f (𝓤 α) := ⟨λ H, tendsto_left_nhds_uniformity.comp H, λ H s hs, by simpa [mem_of_mem_nhds hs] using H (mem_nhds_uniformity_iff_right.1 hs)⟩ theorem tendsto_nhds_left {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ tendsto (λ x, (u x, a)) f (𝓤 α) := ⟨λ H, tendsto_right_nhds_uniformity.comp H, λ H s hs, by simpa [mem_of_mem_nhds hs] using H (mem_nhds_uniformity_iff_left.1 hs)⟩ theorem continuous_at_iff'_right [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) := by rw [continuous_at, tendsto_nhds_right] theorem continuous_at_iff'_left [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) := by rw [continuous_at, tendsto_nhds_left] theorem continuous_at_iff_prod [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x : β × β, (f x.1, f x.2)) (𝓝 (b, b)) (𝓤 α) := ⟨λ H, le_trans (H.prod_map' H) (nhds_le_uniformity _), λ H, continuous_at_iff'_left.2 $ H.comp $ tendsto_id.prod_mk_nhds tendsto_const_nhds⟩ theorem continuous_within_at_iff'_right [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) := by rw [continuous_within_at, tendsto_nhds_right] theorem continuous_within_at_iff'_left [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) := by rw [continuous_within_at, tendsto_nhds_left] theorem continuous_on_iff'_right [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f b, f x)) (𝓝[s] b) (𝓤 α) := by simp [continuous_on, continuous_within_at_iff'_right] theorem continuous_on_iff'_left [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f x, f b)) (𝓝[s] b) (𝓤 α) := by simp [continuous_on, continuous_within_at_iff'_left] theorem continuous_iff'_right [topological_space β] {f : β → α} : continuous f ↔ ∀ b, tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_right theorem continuous_iff'_left [topological_space β] {f : β → α} : continuous f ↔ ∀ b, tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_left end uniform lemma filter.tendsto.congr_uniformity {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β} (hf : tendsto f l (𝓝 b)) (hg : tendsto (λ x, (f x, g x)) l (𝓤 β)) : tendsto g l (𝓝 b) := uniform.tendsto_nhds_right.2 $ (uniform.tendsto_nhds_right.1 hf).uniformity_trans hg lemma uniform.tendsto_congr {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β} (hfg : tendsto (λ x, (f x, g x)) l (𝓤 β)) : tendsto f l (𝓝 b) ↔ tendsto g l (𝓝 b) := ⟨λ h, h.congr_uniformity hfg, λ h, h.congr_uniformity hfg.uniformity_symm⟩
32fc7d2d4034b5fe5cf1c8ac6e0200bdad02fb5d
fe84e287c662151bb313504482b218a503b972f3
/src/combinatorics/square_grid.lean
66a69c4fe7a524a96541b6b9f25dc06c29671ddd
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
13,966
lean
import data.fintype.basic import algebra.power_mod import group_theory.group_action import algebra.group_power import algebra.big_operators import data.zmod.basic import tactic.ring tactic.abel import group_theory.self_map import group_theory.action_instances import group_theory.burnside_count import group_theory.dihedral import data.fin_extra import data.enumeration import order.lattice order.lattice_extra open group_theory namespace combinatorics variable (N : ℕ) def square_grid := (fin N.succ) × (fin N.succ) namespace square_grid instance : decidable_eq (square_grid N) := by { dsimp [square_grid], apply_instance } instance : fintype (square_grid N) := by { dsimp [square_grid], apply_instance } instance : has_repr (square_grid N) := ⟨λ ij, ij.1.val.repr ++ ij.2.val.repr⟩ instance : distrib_lattice (square_grid N) := by { dsimp [square_grid], apply_instance } instance : bounded_order (square_grid N) := by { dsimp [square_grid], apply_instance } variable {N} def s : self_map (square_grid N) := λ ij, ⟨ij.1, ij.2.reflect⟩ def r : self_map (square_grid N) := λ ij, ⟨ij.2.reflect, ij.1⟩ variable (N) def p : dihedral.prehom 4 (self_map (square_grid N)) := begin refine_struct { r := r, s := s }; funext ij; rcases ij with ⟨i,j⟩; simp [self_map.one_app, self_map.mul_app, r, s, pow_succ, fin.reflect_reflect]; refl end instance four_pos : fact (4 > 0) := by apply_instance instance : mul_action (dihedral 4) (square_grid N) := self_map.mul_action_of_hom (p N).to_hom lemma smul_r₀ (ij : square_grid N) : (dihedral.r (0 : zmod 4)) • ij = ij := rfl lemma smul_r₁ (ij : square_grid N) : (dihedral.r (1 : zmod 4)) • ij = ⟨ij.2.reflect, ij.1⟩ := rfl lemma smul_r₂ (ij : (square_grid N)) : (dihedral.r (2 : zmod 4)) • ij = ⟨ij.1.reflect, ij.2.reflect⟩ := begin change ((p N).to_hom) (dihedral.r (2 : zmod 4)) ij = _, rw [dihedral.prehom.to_hom.map_r (p N) 2], change r (r ij) = _, simp only [r, fin.reflect_reflect], end lemma smul_r₃ (ij : (square_grid N)) : (dihedral.r (3 : zmod 4)) • ij = ⟨ij.2, ij.1.reflect⟩ := begin change ((p N).to_hom) (dihedral.r (3 : zmod 4)) ij = _, rw [dihedral.prehom.to_hom.map_r (p N) 3], change r (r (r ij)) = _, simp only [r, fin.reflect_reflect], end lemma smul_s₀ (ij : (square_grid N)) : (dihedral.s (0 : zmod 4)) • ij = ⟨ij.1, ij.2.reflect⟩ := rfl lemma smul_s₁ (ij : (square_grid N)) : (dihedral.s (1 : zmod 4)) • ij = ⟨ij.2, ij.1⟩ := begin change ((p N).to_hom) (dihedral.s (1 : zmod 4)) ij = _, rw [dihedral.prehom.to_hom.map_s (p N) 1, self_map.mul_app], change r (s ij) = _, simp only [s, r, fin.reflect_reflect], end lemma smul_s₂ (ij : (square_grid N)) : (dihedral.s (2 : zmod 4)) • ij = ⟨ij.1.reflect, ij.2⟩ := begin change ((p N).to_hom) (dihedral.s (2 : zmod 4)) ij = _, rw [dihedral.prehom.to_hom.map_s (p N) 2], change r (r (s ij)) = _, simp only [s, r, fin.reflect_reflect], end lemma smul_s₃ (ij : (square_grid N)) : (dihedral.s (3 : zmod 4)) • ij = ⟨ij.2.reflect, ij.1.reflect⟩ := begin change ((p N).to_hom) (dihedral.s (3 : zmod 4)) ij = _, rw [dihedral.prehom.to_hom.map_s (p N) 3], change r (r (r (s ij))) = _, simp only [s, r, fin.reflect_reflect], end def subsets := finset (square_grid N) namespace subsets instance : decidable_eq (subsets N) := by { dsimp [subsets], apply_instance } instance : has_repr (subsets N) := by { dsimp [subsets], apply_instance } instance : mul_action (dihedral 4) (subsets N) := by { dsimp [subsets], apply_instance } end subsets @[derive decidable_eq] structure dim := (w h : ℕ) namespace dim def flip : dim → dim := λ d, ⟨d.h, d.w⟩ lemma flip_h (d : dim) : d.flip.h = d.w := rfl lemma flip_w (d : dim) : d.flip.w = d.h := rfl lemma flip_flip (d : dim) : d.flip.flip = d := by { cases d, refl } def smul₀ : (dihedral 4) → dim → dim | (dihedral.r i) d := cond i.val.bodd d.flip d | (dihedral.s i) d := cond i.val.bodd d d.flip lemma bodd_mod4 (i : ℕ) : (i % 4).bodd = i.bodd := begin have : nat.bodd 4 = ff := rfl, rw[← congr_arg nat.bodd (nat.mod_add_div i 4), nat.bodd_add, nat.bodd_mul, this, ff_band, bxor_ff ] end lemma bodd_add (i j : zmod 4) : (i + j).val.bodd = bxor i.val.bodd j.val.bodd := by { rw [← nat.bodd_add,zmod.val_add], exact bodd_mod4 (i.val + j.val) } lemma bodd_sub (i j : zmod 4) : (i - j).val.bodd = bxor i.val.bodd j.val.bodd := begin have := bodd_add (i - j) j, rw [sub_add_cancel] at this, have := congr_fun (congr_arg bxor this) j.val.bodd, rw [bool.bxor_assoc, bxor_self, bxor_ff] at this, exact this.symm end instance : mul_action (dihedral 4) dim := { smul := smul₀, one_smul := λ ⟨_,_⟩, rfl, mul_smul := λ g h d, begin cases d with a b, cases g with i i; cases h with j j; simp only [smul₀, bodd_add, bodd_sub, dihedral.rr_mul, dihedral.rs_mul, dihedral.sr_mul, dihedral.ss_mul]; cases i.val.bodd; cases j.val.bodd; simp only [bxor, cond, flip_flip]; split; refl end } end dim @[derive decidable_eq] structure box := (i j k l : fin N.succ) (hik : i ≤ k) (hjl : j ≤ l) namespace box variable {N} @[ext] lemma ext (x y : box N) : x.i = y.i → x.j = y.j → x.k = y.k → x.l = y.l → x = y := by { cases x, cases y, simp only [], rintro ⟨_⟩ ⟨_⟩ ⟨_⟩ ⟨_⟩, cc } def bottom_left : (box N) → (square_grid N) | ⟨i,j,k,l,_,_⟩ := ⟨i,j⟩ def bottom_right : (box N) → (square_grid N) | ⟨i,j,k,l,_,_⟩ := ⟨k,j⟩ def top_left : (box N) → (square_grid N) | ⟨i,j,k,l,_,_⟩ := ⟨i,l⟩ def top_right : (box N) → (square_grid N) | ⟨i,j,k,l,_,_⟩ := ⟨k,l⟩ def size : (box N) → dim | ⟨i,j,k,l,_,_⟩ := ⟨k - i, l - j⟩ def r : self_map (box N) | ⟨i,j,k,l,hik,hjl⟩ := ⟨l.reflect, i, j.reflect, k, fin.reflect_le hjl, hik⟩ def s : self_map (box N) | ⟨i,j,k,l,hik,hjl⟩ := ⟨i,l.reflect,k,j.reflect,hik, fin.reflect_le hjl⟩ variable (N) def p : dihedral.prehom 4 (self_map (box N)) := begin have hc : ((4 : ℕ+) : ℕ) = 4 := rfl, have hp : (r ^ 4 : self_map (box N)) = r * r * r * r := by simp only [pow_succ, pow_zero, mul_assoc, mul_one], refine_struct { r := r, s := s }; ext x; cases x with i j k l h₀ h₁; simp only [hc, hp, self_map.mul_app, self_map.one_app, r, s, fin.reflect_reflect], end instance : mul_action (dihedral 4) (box N) := self_map.mul_action_of_hom (p N).to_hom lemma smul_r₀ (x : box N) : (dihedral.r (0 : zmod 4)) • x = x := rfl lemma smul_r₁ (x : box N) : (dihedral.r (1 : zmod 4)) • x = box.mk x.l.reflect x.i x.j.reflect x.k (fin.reflect_le x.hjl) x.hik := by { cases x, refl } lemma smul_r₂ (x : box N) : (dihedral.r (2 : zmod 4)) • x = box.mk x.k.reflect x.l.reflect x.i.reflect x.j.reflect (fin.reflect_le x.hik) (fin.reflect_le x.hjl) := by { cases x, refl } lemma smul_r₃ (x : box N) : (dihedral.r (3 : zmod 4)) • x = box.mk x.j x.k.reflect x.l x.i.reflect x.hjl (fin.reflect_le x.hik) := by { change (r * (r * r)) _ = _, cases x, simp only [self_map.mul_app, r, fin.reflect_reflect], cc } lemma smul_s₀ (x : box N) : (dihedral.s (0 : zmod 4)) • x = box.mk x.i x.l.reflect x.k x.j.reflect x.hik (fin.reflect_le x.hjl) := by { cases x, refl } lemma smul_s₁ (x : box N) : (dihedral.s (1 : zmod 4)) • x = box.mk x.j x.i x.l x.k x.hjl x.hik := by { change (r * s) _ = _, cases x, simp only [self_map.mul_app, r, s, fin.reflect_reflect], cc } lemma smul_s₂ (x : box N) : (dihedral.s (2 : zmod 4)) • x = box.mk x.k.reflect x.j x.i.reflect x.l (fin.reflect_le x.hik) x.hjl := by { change (r * r * s) _ = _, cases x, simp only [self_map.mul_app, r, s, fin.reflect_reflect], cc } lemma smul_s₃ (x : box N) : (dihedral.s (3 : zmod 4)) • x = box.mk x.l.reflect x.k.reflect x.j.reflect x.i.reflect (fin.reflect_le x.hjl) (fin.reflect_le x.hik) := by { change (r * r * r * s) _ = _, cases x, simp only [self_map.mul_app, r, s, fin.reflect_reflect], cc } def to_subset : ∀ (x : box N), subsets N | ⟨i,j,k,l,hik,hjl⟩ := finset.product (finset.Icc i k) (finset.Icc j l) end box variable {N} namespace subsets def bounding_box : (subsets N) → (square_grid N) × (square_grid N) := λ (xs : finset (square_grid N)), ⟨xs.inf id,xs.sup id⟩ def size (y : subsets N) : ℕ × ℕ := let b := y.bounding_box in prod.mk (b.2.1 - b.1.1) (b.2.2 - b.1.2) def is_horizontal (y : subsets N) : bool := y.size.2 = 0 def is_vertical (y : subsets N) : bool := y.size.1 = 0 end subsets @[derive decidable_eq] inductive Z_single (N : ℕ) | H : (fin N) → (fin N.succ) → Z_single | V : (fin N.succ) → (fin N) → Z_single namespace Z_single def to_string : (Z_single N) → string | (H i j) := "H" ++ i.val.repr ++ j.val.repr | (V i j) := "V" ++ i.val.repr ++ j.val.repr instance : has_repr (Z_single N) := ⟨to_string⟩ def bounding_box : (Z_single N) → (square_grid N) × (square_grid N) | (H i j) := ⟨⟨i.inc,j⟩,⟨i.succ,j⟩⟩ | (V i j) := ⟨⟨i,j.inc⟩,⟨i,j.succ⟩⟩ def size : (Z_single N) → ℕ × ℕ | (H _ _) := ⟨1,0⟩ | (V _ _) := ⟨0,1⟩ instance : enumeration (Z_single N) := { elems := ((enumeration.elems : list (fin N)).bind (λ i, (enumeration.elems : list (fin N.succ)).map (Z_single.H i))) ++ ((enumeration.elems : list (fin N.succ)).bind (λ i, (enumeration.elems : list (fin N)).map (Z_single.V i))), nodup := sorry, complete := λ z, begin cases z with i j i j; rw [list.mem_append], { left, exact @list.mem_bind_of_mem (fin N) (Z_single N) (H i j) (enumeration.elems : list (fin N)) (λ i, (enumeration.elems : list (fin N.succ)).map (Z_single.H i)) i (enumeration.complete i) (list.mem_map_of_mem (H i) (enumeration.complete j)) }, { right, exact @list.mem_bind_of_mem (fin N.succ) (Z_single N) (V i j) (enumeration.elems : list (fin N.succ)) (λ i, (enumeration.elems : list (fin N)).map (Z_single.V i)) i (enumeration.complete i) (list.mem_map_of_mem (V i) (enumeration.complete j)) }, end } def to_Y₀ : ∀ (z : Z_single N), list (square_grid N) | (H i j) := [prod.mk i.inc j, prod.mk i.succ j] | (V i j) := [prod.mk i j.inc, prod.mk i j.succ] lemma to_Y₀_nodup (z : Z_single N) : z.to_Y₀.nodup := begin have : ∀ {n : ℕ} (k : fin n), k.inc ≠ k.succ := λ n k, ne_of_lt k.inc_lt_succ, cases z with i j i j; dsimp[to_Y₀]; simp [fin.eq_iff_veq,(nat.succ_ne_self i.val).symm, this] end def to_Y (z : Z_single N) : (subsets N) := @finset.mk (square_grid N) z.to_Y₀ z.to_Y₀_nodup lemma to_Y_card (z : Z_single N) : z.to_Y.card = 2 := by { cases z with i j i j; refl } lemma to_Y_bounding_box (z : Z_single N) : z.to_Y.bounding_box = z.bounding_box := begin cases z with i j i j, focus { let u : square_grid N := ⟨i.inc,j⟩, let v : square_grid N := ⟨i.succ,j⟩, have huv : u ≤ v := ⟨le_of_lt i.inc_lt_succ,le_refl j⟩, }, swap, focus { let u : square_grid N := ⟨i,j.inc⟩, let v : square_grid N := ⟨i,j.succ⟩, have huv : u ≤ v := ⟨le_refl i,le_of_lt j.inc_lt_succ⟩ }, all_goals { change prod.mk (u ⊓ (v ⊓ ⊤)) (u ⊔ (v ⊔ ⊥)) = ⟨u,v⟩, rw [inf_top_eq, sup_bot_eq], rw [inf_of_le_left huv, sup_of_le_right huv] } end lemma to_Y_size (z : Z_single N) : z.to_Y.size = z.size := begin dsimp [subsets.size], rw [to_Y_bounding_box], rcases z with ⟨⟨i,hi⟩,⟨j,hj⟩⟩ | ⟨⟨i,hi⟩,⟨j,hj⟩⟩, { change prod.mk ((i + 1) - i) (j - j) = ⟨1,0⟩, rw [nat.sub_self, nat.add_sub_cancel_left] }, { change prod.mk (i - i) ((j + 1) - j) = ⟨0,1⟩, rw [nat.sub_self, nat.add_sub_cancel_left] } end lemma to_Y_inj : function.injective (@to_Y N) := begin intros z₀ z₁ he, have hb := congr_arg subsets.bounding_box he, rw [to_Y_bounding_box, to_Y_bounding_box] at hb, clear he, cases z₀ with i₀ j₀ i₀ j₀; cases z₁ with i₁ j₁ i₁ j₁, all_goals { simp only [bounding_box] at hb, injection hb with hb₀ hb₁, injection hb₀ with hb₂ hb₃, injection hb₁ with hb₄ hb₅ }, { replace hb₄ := fin.succ_inj.mp hb₄, cc }, { exfalso, exact ne_of_lt (fin.inc_lt_succ i₀) (hb₂.trans hb₄.symm) }, { exfalso, exact ne_of_lt (fin.inc_lt_succ j₀) (hb₃.trans hb₅.symm) }, { replace hb₅ := fin.succ_inj.mp hb₅, cc } end def s : (Z_single N) → (Z_single N) | (H i j) := H i j.reflect | (V i j) := V i j.reflect def r : (Z_single N) → (Z_single N) | (H i j) := V j.reflect i | (V i j) := H j.reflect i lemma to_Y_s (z : Z_single N) : (s z).to_Y = (dihedral.s (0 : zmod 4)) • z.to_Y := begin cases z with i j i j; dsimp[s, to_Y, to_Y₀]; change finset.mk _ _ = _; ext x; cases x with i' j'; simp only [ mul_action.mem_smul_finset', dihedral.s_inv, finset.mem_mk, multiset.mem_coe, list.mem_cons_iff, list.mem_singleton, mul_action.smul_eq_iff_eq_smul_inv]; simp only [smul_s₀, fin.reflect_inc, fin.reflect_succ, or_comm], end lemma to_Y_r (z : Z_single N) : (r z).to_Y = (dihedral.r (1 : zmod 4)) • z.to_Y := begin cases z with i j i j; dsimp[r, to_Y, to_Y₀]; change finset.mk _ _ = _; ext x; cases x with i' j'; simp only [ mul_action.mem_smul_finset', dihedral.r_inv, neg_neg, finset.mem_mk, multiset.mem_coe, list.mem_cons_iff, list.mem_singleton, mul_action.smul_eq_iff_eq_smul_inv]; simp only [smul_r₁, fin.reflect_inc, fin.reflect_succ, or.comm], end end Z_single end square_grid end combinatorics
a69dc37087ad98945d4cb8b98e271a4d0ac1e939
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Meta/WHNF.lean
71914d5ad6c30a31d2decae5490871a423472aa5
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,346
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.ToExpr import Lean.AuxRecursor import Lean.ProjFns import Lean.Meta.Basic import Lean.Meta.LevelDefEq import Lean.Meta.GetConst import Lean.Meta.Match.MatcherInfo namespace Lean.Meta /- =========================== Smart unfolding support =========================== -/ def smartUnfoldingSuffix := "_sunfold" @[inline] def mkSmartUnfoldingNameFor (declName : Name) : Name := Name.mkStr declName smartUnfoldingSuffix register_builtin_option smartUnfolding : Bool := { defValue := true descr := "when computing weak head normal form, use auxiliary definition created for functions defined by structural recursion" } /- =========================== Helper methods =========================== -/ def isAuxDef (constName : Name) : MetaM Bool := do let env ← getEnv return isAuxRecursor env constName || isNoConfusion env constName @[inline] private def matchConstAux {α} (e : Expr) (failK : Unit → MetaM α) (k : ConstantInfo → List Level → MetaM α) : MetaM α := match e with | Expr.const name lvls _ => do let (some cinfo) ← getConst? name | failK () k cinfo lvls | _ => failK () /- =========================== Helper functions for reducing recursors =========================== -/ private def getFirstCtor (d : Name) : MetaM (Option Name) := do let some (ConstantInfo.inductInfo { ctors := ctor::_, ..}) ← getConstNoEx? d | pure none return some ctor private def mkNullaryCtor (type : Expr) (nparams : Nat) : MetaM (Option Expr) := match type.getAppFn with | Expr.const d lvls _ => do let (some ctor) ← getFirstCtor d | pure none return mkAppN (mkConst ctor lvls) (type.getAppArgs.shrink nparams) | _ => return none def toCtorIfLit : Expr → Expr | Expr.lit (Literal.natVal v) _ => if v == 0 then mkConst `Nat.zero else mkApp (mkConst `Nat.succ) (mkNatLit (v-1)) | Expr.lit (Literal.strVal v) _ => mkApp (mkConst `String.mk) (toExpr v.toList) | e => e private def getRecRuleFor (recVal : RecursorVal) (major : Expr) : Option RecursorRule := match major.getAppFn with | Expr.const fn _ _ => recVal.rules.find? fun r => r.ctor == fn | _ => none private def toCtorWhenK (recVal : RecursorVal) (major : Expr) : MetaM (Option Expr) := do let majorType ← inferType major let majorType ← whnf majorType let majorTypeI := majorType.getAppFn if !majorTypeI.isConstOf recVal.getInduct then return none else if majorType.hasExprMVar && majorType.getAppArgs[recVal.numParams:].any Expr.hasExprMVar then return none else do let (some newCtorApp) ← mkNullaryCtor majorType recVal.numParams | pure none let newType ← inferType newCtorApp if (← isDefEq majorType newType) then return newCtorApp else return none /-- Auxiliary function for reducing recursor applications. -/ private def reduceRec {α} (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := let majorIdx := recVal.getMajorIdx if h : majorIdx < recArgs.size then do let major := recArgs.get ⟨majorIdx, h⟩ let mut major ← whnf major if recVal.k then let newMajor ← toCtorWhenK recVal major major := newMajor.getD major let major := toCtorIfLit major match getRecRuleFor recVal major with | some rule => let majorArgs := major.getAppArgs if recLvls.length != recVal.levelParams.length then failK () else let rhs := rule.rhs.instantiateLevelParams recVal.levelParams recLvls -- Apply parameters, motives and minor premises from recursor application. let rhs := mkAppRange rhs 0 (recVal.numParams+recVal.numMotives+recVal.numMinors) recArgs /- The number of parameters in the constructor is not necessarily equal to the number of parameters in the recursor when we have nested inductive types. -/ let nparams := majorArgs.size - rule.nfields let rhs := mkAppRange rhs nparams majorArgs.size majorArgs let rhs := mkAppRange rhs (majorIdx + 1) recArgs.size recArgs successK rhs | none => failK () else failK () /- =========================== Helper functions for reducing Quot.lift and Quot.ind =========================== -/ /-- Auxiliary function for reducing `Quot.lift` and `Quot.ind` applications. -/ private def reduceQuotRec {α} (recVal : QuotVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := let process (majorPos argPos : Nat) : MetaM α := if h : majorPos < recArgs.size then do let major := recArgs.get ⟨majorPos, h⟩ let major ← whnf major match major with | Expr.app (Expr.app (Expr.app (Expr.const majorFn _ _) _ _) _ _) majorArg _ => do let some (ConstantInfo.quotInfo { kind := QuotKind.ctor, .. }) ← getConstNoEx? majorFn | failK () let f := recArgs[argPos] let r := mkApp f majorArg let recArity := majorPos + 1 successK $ mkAppRange r recArity recArgs.size recArgs | _ => failK () else failK () match recVal.kind with | QuotKind.lift => process 5 3 | QuotKind.ind => process 4 3 | _ => failK () /- =========================== Helper function for extracting "stuck term" =========================== -/ mutual private partial def isRecStuck? (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) : MetaM (Option MVarId) := if recVal.k then -- TODO: improve this case return none else do let majorIdx := recVal.getMajorIdx if h : majorIdx < recArgs.size then do let major := recArgs.get ⟨majorIdx, h⟩ let major ← whnf major getStuckMVar? major else return none private partial def isQuotRecStuck? (recVal : QuotVal) (recLvls : List Level) (recArgs : Array Expr) : MetaM (Option MVarId) := let process? (majorPos : Nat) : MetaM (Option MVarId) := if h : majorPos < recArgs.size then do let major := recArgs.get ⟨majorPos, h⟩ let major ← whnf major getStuckMVar? major else return none match recVal.kind with | QuotKind.lift => process? 5 | QuotKind.ind => process? 4 | _ => return none /-- Return `some (Expr.mvar mvarId)` if metavariable `mvarId` is blocking reduction. -/ partial def getStuckMVar? : Expr → MetaM (Option MVarId) | Expr.mdata _ e _ => getStuckMVar? e | Expr.proj _ _ e _ => do getStuckMVar? (← whnf e) | e@(Expr.mvar ..) => do let e ← instantiateMVars e match e with | Expr.mvar mvarId _ => pure (some mvarId) | _ => getStuckMVar? e | e@(Expr.app f _ _) => let f := f.getAppFn match f with | Expr.mvar mvarId _ => return some mvarId | Expr.const fName fLvls _ => do let cinfo? ← getConstNoEx? fName match cinfo? with | some $ ConstantInfo.recInfo recVal => isRecStuck? recVal fLvls e.getAppArgs | some $ ConstantInfo.quotInfo recVal => isQuotRecStuck? recVal fLvls e.getAppArgs | _ => return none | _ => return none | _ => return none end /- =========================== Weak Head Normal Form auxiliary combinators =========================== -/ /-- Auxiliary combinator for handling easy WHNF cases. It takes a function for handling the "hard" cases as an argument -/ @[specialize] private partial def whnfEasyCases (e : Expr) (k : Expr → MetaM Expr) : MetaM Expr := do match e with | Expr.forallE .. => return e | Expr.lam .. => return e | Expr.sort .. => return e | Expr.lit .. => return e | Expr.bvar .. => unreachable! | Expr.letE .. => k e | Expr.const .. => k e | Expr.app .. => k e | Expr.proj .. => k e | Expr.mdata _ e _ => whnfEasyCases e k | Expr.fvar fvarId _ => let decl ← getLocalDecl fvarId match decl with | LocalDecl.cdecl .. => return e | LocalDecl.ldecl (value := v) (nonDep := nonDep) .. => let cfg ← getConfig if nonDep && !cfg.zetaNonDep then return e else when cfg.trackZeta do modify fun s => { s with zetaFVarIds := s.zetaFVarIds.insert fvarId } whnfEasyCases v k | Expr.mvar mvarId _ => match (← getExprMVarAssignment? mvarId) with | some v => whnfEasyCases v k | none => return e /-- Return true iff term is of the form `idRhs ...` -/ private def isIdRhsApp (e : Expr) : Bool := e.isAppOf `idRhs /-- (@idRhs T f a_1 ... a_n) ==> (f a_1 ... a_n) -/ private def extractIdRhs (e : Expr) : Expr := if !isIdRhsApp e then e else let args := e.getAppArgs if args.size < 2 then e else mkAppRange args[1] 2 args.size args @[specialize] private def deltaDefinition {α} (c : ConstantInfo) (lvls : List Level) (failK : Unit → α) (successK : Expr → α) : α := if c.levelParams.length != lvls.length then failK () else let val := c.instantiateValueLevelParams lvls successK (extractIdRhs val) @[specialize] private def deltaBetaDefinition {α} (c : ConstantInfo) (lvls : List Level) (revArgs : Array Expr) (failK : Unit → α) (successK : Expr → α) : α := if c.levelParams.length != lvls.length then failK () else let val := c.instantiateValueLevelParams lvls let val := val.betaRev revArgs successK (extractIdRhs val) inductive ReduceMatcherResult where | reduced (val : Expr) | stuck (val : Expr) | notMatcher | partialApp def reduceMatcher? (e : Expr) : MetaM ReduceMatcherResult := do match e.getAppFn with | Expr.const declName declLevels _ => let some info ← getMatcherInfo? declName | return ReduceMatcherResult.notMatcher let args := e.getAppArgs let prefixSz := info.numParams + 1 + info.numDiscrs if args.size < prefixSz + info.numAlts then return ReduceMatcherResult.partialApp else let constInfo ← getConstInfo declName let f := constInfo.instantiateValueLevelParams declLevels let auxApp := mkAppN f args[0:prefixSz] let auxAppType ← inferType auxApp forallBoundedTelescope auxAppType info.numAlts fun hs _ => do let auxApp := mkAppN auxApp hs let auxApp ← whnf auxApp let auxAppFn := auxApp.getAppFn let mut i := prefixSz for h in hs do if auxAppFn == h then let result := mkAppN args[i] auxApp.getAppArgs let result := mkAppN result args[prefixSz + info.numAlts:args.size] return ReduceMatcherResult.reduced result.headBeta i := i + 1 return ReduceMatcherResult.stuck auxApp | _ => pure ReduceMatcherResult.notMatcher /- Given an expression `e`, compute its WHNF and if the result is a constructor, return field #i. -/ def project? (e : Expr) (i : Nat) : MetaM (Option Expr) := do let e ← whnf e matchConstCtor e.getAppFn (fun _ => pure none) fun ctorVal _ => let numArgs := e.getAppNumArgs let idx := ctorVal.numParams + i if idx < numArgs then return some (e.getArg! idx) else return none def reduceProj? (e : Expr) : MetaM (Option Expr) := do match e with | Expr.proj _ i c _ => project? c i | _ => return none /- Auxiliary method for reducing terms of the form `?m t_1 ... t_n` where `?m` is delayed assigned. Recall that we can only expand a delayed assignment when all holes/metavariables in the assigned value have been "filled". -/ private def whnfDelayedAssigned? (f' : Expr) (e : Expr) : MetaM (Option Expr) := do if f'.isMVar then match (← getDelayedAssignment? f'.mvarId!) with | none => return none | some { fvars := fvars, val := val, .. } => let args := e.getAppArgs if fvars.size > args.size then -- Insufficient number of argument to expand delayed assignment return none else let newVal ← instantiateMVars val if newVal.hasExprMVar then -- Delayed assignment still contains metavariables return none else let newVal := newVal.abstract fvars let result := newVal.instantiateRevRange 0 fvars.size args return mkAppRange result fvars.size args.size args else return none /-- Apply beta-reduction, zeta-reduction (i.e., unfold let local-decls), iota-reduction, expand let-expressions, expand assigned meta-variables. -/ partial def whnfCore (e : Expr) : MetaM Expr := whnfEasyCases e fun e => do trace[Meta.whnf]! e match e with | Expr.const .. => pure e | Expr.letE _ _ v b _ => whnfCore $ b.instantiate1 v | Expr.app f .. => let f := f.getAppFn let f' ← whnfCore f if f'.isLambda then let revArgs := e.getAppRevArgs whnfCore <| f'.betaRev revArgs else if let some eNew ← whnfDelayedAssigned? f' e then whnfCore eNew else let e := if f == f' then e else e.updateFn f' match (← reduceMatcher? e) with | ReduceMatcherResult.reduced eNew => whnfCore eNew | ReduceMatcherResult.partialApp => pure e | ReduceMatcherResult.stuck _ => pure e | ReduceMatcherResult.notMatcher => matchConstAux f' (fun _ => return e) fun cinfo lvls => match cinfo with | ConstantInfo.recInfo rec => reduceRec rec lvls e.getAppArgs (fun _ => return e) whnfCore | ConstantInfo.quotInfo rec => reduceQuotRec rec lvls e.getAppArgs (fun _ => return e) whnfCore | c@(ConstantInfo.defnInfo _) => do if (← isAuxDef c.name) then deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => return e) whnfCore else return e | _ => return e | Expr.proj .. => match (← reduceProj? e) with | some e => whnfCore e | none => return e | _ => unreachable! mutual /-- Reduce `e` until `idRhs` application is exposed or it gets stuck. This is a helper method for implementing smart unfolding. -/ private partial def whnfUntilIdRhs (e : Expr) : MetaM Expr := do let e ← whnfCore e match (← getStuckMVar? e) with | some mvarId => /- Try to "unstuck" by resolving pending TC problems -/ if (← Meta.synthPending mvarId) then whnfUntilIdRhs e else return e -- failed because metavariable is blocking reduction | _ => if isIdRhsApp e then return e -- done else match (← unfoldDefinition? e) with | some e => whnfUntilIdRhs e | none => pure e -- failed because of symbolic argument /-- Auxiliary method for unfolding a class projection when transparency is set to `TransparencyMode.instances`. Recall that that class instance projections are not marked with `[reducible]` because we want them to be in "reducible canonical form". -/ private partial def unfoldProjInst (e : Expr) : MetaM (Option Expr) := do if (← getTransparency) != TransparencyMode.instances then return none else match e.getAppFn with | Expr.const declName .. => match (← getProjectionFnInfo? declName) with | some { fromClass := true, .. } => match (← withDefault <| unfoldDefinition? e) with | none => return none | some e => match (← reduceProj? e.getAppFn) with | none => return none | some r => return mkAppN r e.getAppArgs |>.headBeta | _ => return none | _ => return none /-- Unfold definition using "smart unfolding" if possible. -/ partial def unfoldDefinition? (e : Expr) : MetaM (Option Expr) := match e with | Expr.app f _ _ => matchConstAux f.getAppFn (fun _ => unfoldProjInst e) fun fInfo fLvls => do if fInfo.levelParams.length != fLvls.length then return none else let unfoldDefault (_ : Unit) : MetaM (Option Expr) := if fInfo.hasValue then deltaBetaDefinition fInfo fLvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e)) else return none if smartUnfolding.get (← getOptions) then let fAuxInfo? ← getConstNoEx? (mkSmartUnfoldingNameFor fInfo.name) match fAuxInfo? with | some fAuxInfo@(ConstantInfo.defnInfo _) => deltaBetaDefinition fAuxInfo fLvls e.getAppRevArgs (fun _ => pure none) fun e₁ => do let e₂ ← whnfUntilIdRhs e₁ if isIdRhsApp e₂ then return some (extractIdRhs e₂) else return none | _ => unfoldDefault () else unfoldDefault () | Expr.const declName lvls _ => do if smartUnfolding.get (← getOptions) && (← getEnv).contains (mkSmartUnfoldingNameFor declName) then return none else let (some (cinfo@(ConstantInfo.defnInfo _))) ← getConstNoEx? declName | pure none deltaDefinition cinfo lvls (fun _ => pure none) (fun e => pure (some e)) | _ => return none end def unfoldDefinition (e : Expr) : MetaM Expr := do let some e ← unfoldDefinition? e | throwError! "failed to unfold definition{indentExpr e}" return e @[specialize] partial def whnfHeadPred (e : Expr) (pred : Expr → MetaM Bool) : MetaM Expr := whnfEasyCases e fun e => do let e ← whnfCore e if (← pred e) then match (← unfoldDefinition? e) with | some e => whnfHeadPred e pred | none => return e else return e def whnfUntil (e : Expr) (declName : Name) : MetaM (Option Expr) := do let e ← whnfHeadPred e (fun e => return !e.isAppOf declName) if e.isAppOf declName then return e else return none /-- Try to reduce matcher/recursor/quot applications. We say they are all "morally" recursor applications. -/ def reduceRecMatcher? (e : Expr) : MetaM (Option Expr) := do if !e.isApp then return none else match (← reduceMatcher? e) with | ReduceMatcherResult.reduced e => return e | _ => matchConstAux e.getAppFn (fun _ => pure none) fun cinfo lvls => do match cinfo with | ConstantInfo.recInfo «rec» => reduceRec «rec» lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e)) | ConstantInfo.quotInfo «rec» => reduceQuotRec «rec» lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e)) | c@(ConstantInfo.defnInfo _) => if (← isAuxDef c.name) then deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e)) else return none | _ => return none unsafe def reduceBoolNativeUnsafe (constName : Name) : MetaM Bool := evalConstCheck Bool `Bool constName unsafe def reduceNatNativeUnsafe (constName : Name) : MetaM Nat := evalConstCheck Nat `Nat constName @[implementedBy reduceBoolNativeUnsafe] constant reduceBoolNative (constName : Name) : MetaM Bool @[implementedBy reduceNatNativeUnsafe] constant reduceNatNative (constName : Name) : MetaM Nat def reduceNative? (e : Expr) : MetaM (Option Expr) := match e with | Expr.app (Expr.const fName _ _) (Expr.const argName _ _) _ => if fName == `Lean.reduceBool then do return toExpr (← reduceBoolNative argName) else if fName == `Lean.reduceNat then do return toExpr (← reduceNatNative argName) else return none | _ => return none @[inline] def withNatValue {α} (a : Expr) (k : Nat → MetaM (Option α)) : MetaM (Option α) := do let a ← whnf a match a with | Expr.const `Nat.zero _ _ => k 0 | Expr.lit (Literal.natVal v) _ => k v | _ => return none def reduceUnaryNatOp (f : Nat → Nat) (a : Expr) : MetaM (Option Expr) := withNatValue a fun a => return mkNatLit <| f a def reduceBinNatOp (f : Nat → Nat → Nat) (a b : Expr) : MetaM (Option Expr) := withNatValue a fun a => withNatValue b fun b => do trace[Meta.isDefEq.whnf.reduceBinOp]! "{a} op {b}" return mkNatLit <| f a b def reduceBinNatPred (f : Nat → Nat → Bool) (a b : Expr) : MetaM (Option Expr) := do withNatValue a fun a => withNatValue b fun b => return toExpr <| f a b def reduceNat? (e : Expr) : MetaM (Option Expr) := if e.hasFVar || e.hasMVar then return none else match e with | Expr.app (Expr.const fn _ _) a _ => if fn == `Nat.succ then reduceUnaryNatOp Nat.succ a else return none | Expr.app (Expr.app (Expr.const fn _ _) a1 _) a2 _ => if fn == `Nat.add then reduceBinNatOp Nat.add a1 a2 else if fn == `Nat.sub then reduceBinNatOp Nat.sub a1 a2 else if fn == `Nat.mul then reduceBinNatOp Nat.mul a1 a2 else if fn == `Nat.div then reduceBinNatOp Nat.div a1 a2 else if fn == `Nat.mod then reduceBinNatOp Nat.mod a1 a2 else if fn == `Nat.beq then reduceBinNatPred Nat.beq a1 a2 else if fn == `Nat.ble then reduceBinNatPred Nat.ble a1 a2 else return none | _ => return none @[inline] private def useWHNFCache (e : Expr) : MetaM Bool := do -- We cache only closed terms without expr metavars. -- Potential refinement: cache if `e` is not stuck at a metavariable if e.hasFVar || e.hasExprMVar then return false else match (← getConfig).transparency with | TransparencyMode.default => true | TransparencyMode.all => true | _ => false @[inline] private def cached? (useCache : Bool) (e : Expr) : MetaM (Option Expr) := do if useCache then match (← getConfig).transparency with | TransparencyMode.default => return (← get).cache.whnfDefault.find? e | TransparencyMode.all => return (← get).cache.whnfAll.find? e | _ => unreachable! else return none private def cache (useCache : Bool) (e r : Expr) : MetaM Expr := do if useCache then match (← getConfig).transparency with | TransparencyMode.default => modify fun s => { s with cache.whnfDefault := s.cache.whnfDefault.insert e r } | TransparencyMode.all => modify fun s => { s with cache.whnfAll := s.cache.whnfAll.insert e r } | _ => unreachable! return r partial def whnfImp (e : Expr) : MetaM Expr := whnfEasyCases e fun e => do checkMaxHeartbeats "whnf" let useCache ← useWHNFCache e match (← cached? useCache e) with | some e' => pure e' | none => let e' ← whnfCore e match (← reduceNat? e') with | some v => cache useCache e v | none => match (← reduceNative? e') with | some v => cache useCache e v | none => match (← unfoldDefinition? e') with | some e => whnfImp e | none => cache useCache e e' @[builtinInit] def setWHNFRef : IO Unit := whnfRef.set whnfImp builtin_initialize registerTraceClass `Meta.whnf end Lean.Meta
365f9654c9ce38f5d2b17a493459e199917c2a2b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1372.lean
634521784a66c9d385ea96342265b66ba1e518d4
[ "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
792
lean
example (x₁ x₂ y₁ y₂ : Nat) : (x₁ + x₂) + (y₁ + y₂) = (x₁ + y₁) + (x₂ + y₂) := by calc (x₁ + x₂) + (y₁ + y₂) = x₁ + (x₂ + (y₁ + y₂)) := by rw [Nat.add_assoc] _ = x₁ + (y₁ + (x₂ + y₂)) := by rw [Nat.add_left_comm x₂ y₁ y₂] _ = (x₁ + y₁) + (x₂ + y₂) := by rw [Nat.add_assoc] example (n x₁ x₂ y₁ y₂ : Nat) : n = 0 → (x₁ + x₂) + (y₁ + y₂) = (x₁ + y₁) + (x₂ + y₂) := by intro h induction n with | zero => calc (x₁ + x₂) + (y₁ + y₂) = x₁ + (x₂ + (y₁ + y₂)) := by rw [Nat.add_assoc] _ = x₁ + (y₁ + (x₂ + y₂)) := by rw [Nat.add_left_comm x₂ y₁ y₂] _ = (x₁ + y₁) + (x₂ + y₂) := by rw [Nat.add_assoc] | succ _ _ => contradiction
2a32b17e53f3e8f81ada0f87a57b63ee05ebb8f4
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/analysis/calculus/times_cont_diff.lean
b00849920adfa0dbe4c589e024308b86a544c08a
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
136,287
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.calculus.mean_value import analysis.calculus.formal_multilinear_series /-! # Higher differentiability A function is `C^1` on a domain if it is differentiable there, and its derivative is continuous. By induction, it is `C^n` if it is `C^{n-1}` and its (n-1)-th derivative is `C^1` there or, equivalently, if it is `C^1` and its derivative is `C^{n-1}`. Finally, it is `C^∞` if it is `C^n` for all n. We formalize these notions by defining iteratively the `n+1`-th derivative of a function as the derivative of the `n`-th derivative. It is called `iterated_fderiv 𝕜 n f x` where `𝕜` is the field, `n` is the number of iterations, `f` is the function and `x` is the point, and it is given as an `n`-multilinear map. We also define a version `iterated_fderiv_within` relative to a domain, as well as predicates `times_cont_diff_within_at`, `times_cont_diff_at`, `times_cont_diff_on` and `times_cont_diff` saying that the function is `C^n` within a set at a point, at a point, on a set and on the whole space respectively. To avoid the issue of choice when choosing a derivative in sets where the derivative is not necessarily unique, `times_cont_diff_on` is not defined directly in terms of the regularity of the specific choice `iterated_fderiv_within 𝕜 n f s` inside `s`, but in terms of the existence of a nice sequence of derivatives, expressed with a predicate `has_ftaylor_series_up_to_on`. We prove basic properties of these notions. ## Main definitions and results Let `f : E → F` be a map between normed vector spaces over a nondiscrete normed field `𝕜`. * `has_ftaylor_series_up_to n f p`: expresses that the formal multilinear series `p` is a sequence of iterated derivatives of `f`, up to the `n`-th term (where `n` is a natural number or `∞`). * `has_ftaylor_series_up_to_on n f p s`: same thing, but inside a set `s`. The notion of derivative is now taken inside `s`. In particular, derivatives don't have to be unique. * `times_cont_diff 𝕜 n f`: expresses that `f` is `C^n`, i.e., it admits a Taylor series up to rank `n`. * `times_cont_diff_on 𝕜 n f s`: expresses that `f` is `C^n` in `s`. * `times_cont_diff_at 𝕜 n f x`: expresses that `f` is `C^n` around `x`. * `times_cont_diff_within_at 𝕜 n f s x`: expresses that `f` is `C^n` around `x` within the set `s`. * `iterated_fderiv_within 𝕜 n f s x` is an `n`-th derivative of `f` over the field `𝕜` on the set `s` at the point `x`. It is a continuous multilinear map from `E^n` to `F`, defined as a derivative within `s` of `iterated_fderiv_within 𝕜 (n-1) f s` if one exists, and `0` otherwise. * `iterated_fderiv 𝕜 n f x` is the `n`-th derivative of `f` over the field `𝕜` at the point `x`. It is a continuous multilinear map from `E^n` to `F`, defined as a derivative of `iterated_fderiv 𝕜 (n-1) f` if one exists, and `0` otherwise. In sets of unique differentiability, `times_cont_diff_on 𝕜 n f s` can be expressed in terms of the properties of `iterated_fderiv_within 𝕜 m f s` for `m ≤ n`. In the whole space, `times_cont_diff 𝕜 n f` can be expressed in terms of the properties of `iterated_fderiv 𝕜 m f` for `m ≤ n`. We also prove that the usual operations (addition, multiplication, difference, composition, and so on) preserve `C^n` functions. ## Implementation notes The definitions in this file are designed to work on any field `𝕜`. They are sometimes slightly more complicated than the naive definitions one would guess from the intuition over the real or complex numbers, but they are designed to circumvent the lack of gluing properties and partitions of unity in general. In the usual situations, they coincide with the usual definitions. ### Definition of `C^n` functions in domains One could define `C^n` functions in a domain `s` by fixing an arbitrary choice of derivatives (this is what we do with `iterated_fderiv_within`) and requiring that all these derivatives up to `n` are continuous. If the derivative is not unique, this could lead to strange behavior like two `C^n` functions `f` and `g` on `s` whose sum is not `C^n`. A better definition is thus to say that a function is `C^n` inside `s` if it admits a sequence of derivatives up to `n` inside `s`. This definition still has the problem that a function which is locally `C^n` would not need to be `C^n`, as different choices of sequences of derivatives around different points might possibly not be glued together to give a globally defined sequence of derivatives. (Note that this issue can not happen over reals, thanks to partition of unity, but the behavior over a general field is not so clear, and we want a definition for general fields). Also, there are locality problems for the order parameter: one could image a function which, for each `n`, has a nice sequence of derivatives up to order `n`, but they do not coincide for varying `n` and can therefore not be glued to give rise to an infinite sequence of derivatives. This would give a function which is `C^n` for all `n`, but not `C^∞`. We solve this issue by putting locality conditions in space and order in our definition of `times_cont_diff_within_at` and `times_cont_diff_on`. The resulting definition is slightly more complicated to work with (in fact not so much), but it gives rise to completely satisfactory theorems. For instance, with this definition, a real function which is `C^m` (but not better) on `(-1/m, 1/m)` for each natural `m` is by definition `C^∞` at `0`. There is another issue with the definition of `times_cont_diff_within_at 𝕜 n f s x`. We can require the existence and good behavior of derivatives up to order `n` on a neighborhood of `x` within `s`. However, this does not imply continuity or differentiability within `s` of the function at `x` when `x` does not belong to `s`. Therefore, we require such existence and good behavior on a neighborhood of `x` within `s ∪ {x}` (which appears as `insert x s` in this file). ### Side of the composition, and universe issues With a naïve direct definition, the `n`-th derivative of a function belongs to the space `E →L[𝕜] (E →L[𝕜] (E ... F)...)))` where there are n iterations of `E →L[𝕜]`. This space may also be seen as the space of continuous multilinear functions on `n` copies of `E` with values in `F`, by uncurrying. This is the point of view that is usually adopted in textbooks, and that we also use. This means that the definition and the first proofs are slightly involved, as one has to keep track of the uncurrying operation. The uncurrying can be done from the left or from the right, amounting to defining the `n+1`-th derivative either as the derivative of the `n`-th derivative, or as the `n`-th derivative of the derivative. For proofs, it would be more convenient to use the latter approach (from the right), as it means to prove things at the `n+1`-th step we only need to understand well enough the derivative in `E →L[𝕜] F` (contrary to the approach from the left, where one would need to know enough on the `n`-th derivative to deduce things on the `n+1`-th derivative). However, the definition from the right leads to a universe polymorphism problem: if we define `iterated_fderiv 𝕜 (n + 1) f x = iterated_fderiv 𝕜 n (fderiv 𝕜 f) x` by induction, we need to generalize over all spaces (as `f` and `fderiv 𝕜 f` don't take values in the same space). It is only possible to generalize over all spaces in some fixed universe in an inductive definition. For `f : E → F`, then `fderiv 𝕜 f` is a map `E → (E →L[𝕜] F)`. Therefore, the definition will only work if `F` and `E →L[𝕜] F` are in the same universe. This issue does not appear with the definition from the left, where one does not need to generalize over all spaces. Therefore, we use the definition from the left. This means some proofs later on become a little bit more complicated: to prove that a function is `C^n`, the most efficient approach is to exhibit a formula for its `n`-th derivative and prove it is continuous (contrary to the inductive approach where one would prove smoothness statements without giving a formula for the derivative). In the end, this approach is still satisfactory as it is good to have formulas for the iterated derivatives in various constructions. One point where we depart from this explicit approach is in the proof of smoothness of a composition: there is a formula for the `n`-th derivative of a composition (Faà di Bruno's formula), but it is very complicated and barely usable, while the inductive proof is very simple. Thus, we give the inductive proof. As explained above, it works by generalizing over the target space, hence it only works well if all spaces belong to the same universe. To get the general version, we lift things to a common universe using a trick. ### Variables management The textbook definitions and proofs use various identifications and abuse of notations, for instance when saying that the natural space in which the derivative lives, i.e., `E →L[𝕜] (E →L[𝕜] ( ... →L[𝕜] F))`, is the same as a space of multilinear maps. When doing things formally, we need to provide explicit maps for these identifications, and chase some diagrams to see everything is compatible with the identifications. In particular, one needs to check that taking the derivative and then doing the identification, or first doing the identification and then taking the derivative, gives the same result. The key point for this is that taking the derivative commutes with continuous linear equivalences. Therefore, we need to implement all our identifications with continuous linear equivs. ## Notations We use the notation `E [×n]→L[𝕜] F` for the space of continuous multilinear maps on `E^n` with values in `F`. This is the space in which the `n`-th derivative of a function from `E` to `F` lives. In this file, we denote `⊤ : with_top ℕ` with `∞`. ## Tags derivative, differentiability, higher derivative, `C^n`, multilinear, Taylor series, formal series -/ noncomputable theory open_locale classical big_operators local notation `∞` := (⊤ : with_top ℕ) universes u v w local attribute [instance, priority 1001] normed_group.to_add_comm_group normed_space.to_semimodule add_comm_group.to_add_comm_monoid open set fin open_locale topological_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] {s s₁ t u : set E} {f f₁ : E → F} {g : F → G} {x : E} {c : F} {b : E × F → G} /-! ### Functions with a Taylor series on a domain -/ variable {p : E → formal_multilinear_series 𝕜 E F} /-- `has_ftaylor_series_up_to_on n f p s` registers the fact that `p 0 = f` and `p (m+1)` is a derivative of `p m` for `m < n`, and is continuous for `m ≤ n`. This is a predicate analogous to `has_fderiv_within_at` but for higher order derivatives. -/ structure has_ftaylor_series_up_to_on (n : with_top ℕ) (f : E → F) (p : E → formal_multilinear_series 𝕜 E F) (s : set E) : Prop := (zero_eq : ∀ x ∈ s, (p x 0).uncurry0 = f x) (fderiv_within : ∀ (m : ℕ) (hm : (m : with_top ℕ) < n), ∀ x ∈ s, has_fderiv_within_at (λ y, p y m) (p x m.succ).curry_left s x) (cont : ∀ (m : ℕ) (hm : (m : with_top ℕ) ≤ n), continuous_on (λ x, p x m) s) lemma has_ftaylor_series_up_to_on.zero_eq' {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) {x : E} (hx : x ∈ s) : p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x) := by { rw ← h.zero_eq x hx, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ } /-- If two functions coincide on a set `s`, then a Taylor series for the first one is as well a Taylor series for the second one. -/ lemma has_ftaylor_series_up_to_on.congr {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (h₁ : ∀ x ∈ s, f₁ x = f x) : has_ftaylor_series_up_to_on n f₁ p s := begin refine ⟨λ x hx, _, h.fderiv_within, h.cont⟩, rw h₁ x hx, exact h.zero_eq x hx end lemma has_ftaylor_series_up_to_on.mono {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) {t : set E} (hst : t ⊆ s) : has_ftaylor_series_up_to_on n f p t := ⟨λ x hx, h.zero_eq x (hst hx), λ m hm x hx, (h.fderiv_within m hm x (hst hx)).mono hst, λ m hm, (h.cont m hm).mono hst⟩ lemma has_ftaylor_series_up_to_on.of_le {m n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hmn : m ≤ n) : has_ftaylor_series_up_to_on m f p s := ⟨h.zero_eq, λ k hk x hx, h.fderiv_within k (lt_of_lt_of_le hk hmn) x hx, λ k hk, h.cont k (le_trans hk hmn)⟩ lemma has_ftaylor_series_up_to_on.continuous_on {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) : continuous_on f s := begin have := (h.cont 0 bot_le).congr (λ x hx, (h.zero_eq' hx).symm), rwa linear_isometry_equiv.comp_continuous_on_iff at this end lemma has_ftaylor_series_up_to_on_zero_iff : has_ftaylor_series_up_to_on 0 f p s ↔ continuous_on f s ∧ (∀ x ∈ s, (p x 0).uncurry0 = f x) := begin refine ⟨λ H, ⟨H.continuous_on, H.zero_eq⟩, λ H, ⟨H.2, λ m hm, false.elim (not_le.2 hm bot_le), _⟩⟩, assume m hm, have : (m : with_top ℕ) = ((0 : ℕ) : with_bot ℕ) := le_antisymm hm bot_le, rw with_top.coe_eq_coe at this, rw this, have : ∀ x ∈ s, p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x), by { assume x hx, rw ← H.2 x hx, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ }, rw [continuous_on_congr this, linear_isometry_equiv.comp_continuous_on_iff], exact H.1 end lemma has_ftaylor_series_up_to_on_top_iff : (has_ftaylor_series_up_to_on ∞ f p s) ↔ (∀ (n : ℕ), has_ftaylor_series_up_to_on n f p s) := begin split, { assume H n, exact H.of_le le_top }, { assume H, split, { exact (H 0).zero_eq }, { assume m hm, apply (H m.succ).fderiv_within m (with_top.coe_lt_coe.2 (lt_add_one m)) }, { assume m hm, apply (H m).cont m (le_refl _) } } end /-- If a function has a Taylor series at order at least `1`, then the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to_on.has_fderiv_within_at {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : x ∈ s) : has_fderiv_within_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) s x := begin have A : ∀ y ∈ s, f y = (continuous_multilinear_curry_fin0 𝕜 E F) (p y 0), { assume y hy, rw ← h.zero_eq y hy, refl }, suffices H : has_fderiv_within_at (λ y, continuous_multilinear_curry_fin0 𝕜 E F (p y 0)) (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) s x, by exact H.congr A (A x hx), rw linear_isometry_equiv.comp_has_fderiv_within_at_iff', have : ((0 : ℕ) : with_top ℕ) < n := lt_of_lt_of_le (with_top.coe_lt_coe.2 nat.zero_lt_one) hn, convert h.fderiv_within _ this x hx, ext y v, change (p x 1) (snoc 0 y) = (p x 1) (cons y v), unfold_coes, congr' with i, rw unique.eq_default i, refl end lemma has_ftaylor_series_up_to_on.differentiable_on {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s := λ x hx, (h.has_fderiv_within_at hn hx).differentiable_within_at /-- If a function has a Taylor series at order at least `1` on a neighborhood of `x`, then the term of order `1` of this series is a derivative of `f` at `x`. -/ lemma has_ftaylor_series_up_to_on.has_fderiv_at {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : s ∈ 𝓝 x) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) x := (h.has_fderiv_within_at hn (mem_of_nhds hx)).has_fderiv_at hx /-- If a function has a Taylor series at order at least `1` on a neighborhood of `x`, then in a neighborhood of `x`, the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to_on.eventually_has_fderiv_at {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : s ∈ 𝓝 x) : ∀ᶠ y in 𝓝 x, has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p y 1)) y := (eventually_eventually_nhds.2 hx).mono $ λ y hy, h.has_fderiv_at hn hy /-- If a function has a Taylor series at order at least `1` on a neighborhood of `x`, then it is differentiable at `x`. -/ lemma has_ftaylor_series_up_to_on.differentiable_at {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := (h.has_fderiv_at hn hx).differentiable_at /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p` is a Taylor series up to `n`, and `p (n + 1)` is a derivative of `p n`. -/ theorem has_ftaylor_series_up_to_on_succ_iff_left {n : ℕ} : has_ftaylor_series_up_to_on (n + 1) f p s ↔ has_ftaylor_series_up_to_on n f p s ∧ (∀ x ∈ s, has_fderiv_within_at (λ y, p y n) (p x n.succ).curry_left s x) ∧ continuous_on (λ x, p x (n + 1)) s := begin split, { assume h, exact ⟨h.of_le (with_top.coe_le_coe.2 (nat.le_succ n)), h.fderiv_within _ (with_top.coe_lt_coe.2 (lt_add_one n)), h.cont (n + 1) (le_refl _)⟩ }, { assume h, split, { exact h.1.zero_eq }, { assume m hm, by_cases h' : m < n, { exact h.1.fderiv_within m (with_top.coe_lt_coe.2 h') }, { have : m = n := nat.eq_of_lt_succ_of_not_lt (with_top.coe_lt_coe.1 hm) h', rw this, exact h.2.1 } }, { assume m hm, by_cases h' : m ≤ n, { apply h.1.cont m (with_top.coe_le_coe.2 h') }, { have : m = (n + 1) := le_antisymm (with_top.coe_le_coe.1 hm) (not_le.1 h'), rw this, exact h.2.2 } } } end /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p.shift` is a Taylor series up to `n` for `p 1`, which is a derivative of `f`. -/ theorem has_ftaylor_series_up_to_on_succ_iff_right {n : ℕ} : has_ftaylor_series_up_to_on ((n + 1) : ℕ) f p s ↔ (∀ x ∈ s, (p x 0).uncurry0 = f x) ∧ (∀ x ∈ s, has_fderiv_within_at (λ y, p y 0) (p x 1).curry_left s x) ∧ has_ftaylor_series_up_to_on n (λ x, continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) (λ x, (p x).shift) s := begin split, { assume H, refine ⟨H.zero_eq, H.fderiv_within 0 (with_top.coe_lt_coe.2 (nat.succ_pos n)), _⟩, split, { assume x hx, refl }, { assume m (hm : (m : with_top ℕ) < n) x (hx : x ∈ s), have A : (m.succ : with_top ℕ) < n.succ, by { rw with_top.coe_lt_coe at ⊢ hm, exact nat.lt_succ_iff.mpr hm }, change has_fderiv_within_at ((continuous_multilinear_curry_right_equiv' 𝕜 m E F).symm ∘ (λ (y : E), p y m.succ)) (p x m.succ.succ).curry_right.curry_left s x, rw linear_isometry_equiv.comp_has_fderiv_within_at_iff', convert H.fderiv_within _ A x hx, ext y v, change (p x m.succ.succ) (snoc (cons y (init v)) (v (last _))) = (p x (nat.succ (nat.succ m))) (cons y v), rw [← cons_snoc_eq_snoc_cons, snoc_init_self] }, { assume m (hm : (m : with_top ℕ) ≤ n), have A : (m.succ : with_top ℕ) ≤ n.succ, by { rw with_top.coe_le_coe at ⊢ hm, exact nat.pred_le_iff.mp hm }, change continuous_on ((continuous_multilinear_curry_right_equiv' 𝕜 m E F).symm ∘ (λ (y : E), p y m.succ)) s, rw linear_isometry_equiv.comp_continuous_on_iff, exact H.cont _ A } }, { rintros ⟨Hzero_eq, Hfderiv_zero, Htaylor⟩, split, { exact Hzero_eq }, { assume m (hm : (m : with_top ℕ) < n.succ) x (hx : x ∈ s), cases m, { exact Hfderiv_zero x hx }, { have A : (m : with_top ℕ) < n, by { rw with_top.coe_lt_coe at hm ⊢, exact nat.lt_of_succ_lt_succ hm }, have : has_fderiv_within_at ((continuous_multilinear_curry_right_equiv' 𝕜 m E F).symm ∘ (λ (y : E), p y m.succ)) ((p x).shift m.succ).curry_left s x := Htaylor.fderiv_within _ A x hx, rw linear_isometry_equiv.comp_has_fderiv_within_at_iff' at this, convert this, ext y v, change (p x (nat.succ (nat.succ m))) (cons y v) = (p x m.succ.succ) (snoc (cons y (init v)) (v (last _))), rw [← cons_snoc_eq_snoc_cons, snoc_init_self] } }, { assume m (hm : (m : with_top ℕ) ≤ n.succ), cases m, { have : differentiable_on 𝕜 (λ x, p x 0) s := λ x hx, (Hfderiv_zero x hx).differentiable_within_at, exact this.continuous_on }, { have A : (m : with_top ℕ) ≤ n, by { rw with_top.coe_le_coe at hm ⊢, exact nat.lt_succ_iff.mp hm }, have : continuous_on ((continuous_multilinear_curry_right_equiv' 𝕜 m E F).symm ∘ (λ (y : E), p y m.succ)) s := Htaylor.cont _ A, rwa linear_isometry_equiv.comp_continuous_on_iff at this } } } end /-! ### Smooth functions within a set around a point -/ variable (𝕜) /-- A function is continuously differentiable up to order `n` within a set `s` at a point `x` if it admits continuous derivatives up to order `n` in a neighborhood of `x` in `s ∪ {x}`. For `n = ∞`, we only require that this holds up to any finite order (where the neighborhood may depend on the finite order we consider). For instance, a real function which is `C^m` on `(-1/m, 1/m)` for each natural `m`, but not better, is `C^∞` at `0` within `univ`. -/ def times_cont_diff_within_at (n : with_top ℕ) (f : E → F) (s : set E) (x : E) := ∀ (m : ℕ), (m : with_top ℕ) ≤ n → ∃ u ∈ 𝓝[insert x s] x, ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to_on m f p u variable {𝕜} lemma times_cont_diff_within_at_nat {n : ℕ} : times_cont_diff_within_at 𝕜 n f s x ↔ ∃ u ∈ 𝓝[insert x s] x, ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to_on n f p u := ⟨λ H, H n (le_refl _), λ ⟨u, hu, p, hp⟩ m hm, ⟨u, hu, p, hp.of_le hm⟩⟩ lemma times_cont_diff_within_at.of_le {m n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (hmn : m ≤ n) : times_cont_diff_within_at 𝕜 m f s x := λ k hk, h k (le_trans hk hmn) lemma times_cont_diff_within_at_iff_forall_nat_le {n : with_top ℕ} : times_cont_diff_within_at 𝕜 n f s x ↔ ∀ m : ℕ, ↑m ≤ n → times_cont_diff_within_at 𝕜 m f s x := ⟨λ H m hm, H.of_le hm, λ H m hm, H m hm _ le_rfl⟩ lemma times_cont_diff_within_at_top : times_cont_diff_within_at 𝕜 ∞ f s x ↔ ∀ (n : ℕ), times_cont_diff_within_at 𝕜 n f s x := times_cont_diff_within_at_iff_forall_nat_le.trans $ by simp only [forall_prop_of_true, le_top] lemma times_cont_diff_within_at.continuous_within_at {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) : continuous_within_at f s x := begin rcases h 0 bot_le with ⟨u, hu, p, H⟩, rw [mem_nhds_within_insert] at hu, exact (H.continuous_on.continuous_within_at hu.1).mono_of_mem hu.2 end lemma times_cont_diff_within_at.congr_of_eventually_eq {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : times_cont_diff_within_at 𝕜 n f₁ s x := λ m hm, let ⟨u, hu, p, H⟩ := h m hm in ⟨{x ∈ u | f₁ x = f x}, filter.inter_mem_sets hu (mem_nhds_within_insert.2 ⟨hx, h₁⟩), p, (H.mono (sep_subset _ _)).congr (λ _, and.right)⟩ lemma times_cont_diff_within_at.congr_of_eventually_eq' {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : x ∈ s) : times_cont_diff_within_at 𝕜 n f₁ s x := h.congr_of_eventually_eq h₁ $ h₁.self_of_nhds_within hx lemma filter.eventually_eq.times_cont_diff_within_at_iff {n : with_top ℕ} (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : times_cont_diff_within_at 𝕜 n f₁ s x ↔ times_cont_diff_within_at 𝕜 n f s x := ⟨λ H, times_cont_diff_within_at.congr_of_eventually_eq H h₁.symm hx.symm, λ H, H.congr_of_eventually_eq h₁ hx⟩ lemma times_cont_diff_within_at.congr {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (h₁ : ∀ y ∈ s, f₁ y = f y) (hx : f₁ x = f x) : times_cont_diff_within_at 𝕜 n f₁ s x := h.congr_of_eventually_eq (filter.eventually_eq_of_mem self_mem_nhds_within h₁) hx lemma times_cont_diff_within_at.mono_of_mem {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) {t : set E} (hst : s ∈ 𝓝[t] x) : times_cont_diff_within_at 𝕜 n f t x := begin assume m hm, rcases h m hm with ⟨u, hu, p, H⟩, exact ⟨u, nhds_within_le_of_mem (insert_mem_nhds_within_insert hst) hu, p, H⟩ end lemma times_cont_diff_within_at.mono {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) {t : set E} (hst : t ⊆ s) : times_cont_diff_within_at 𝕜 n f t x := h.mono_of_mem $ filter.mem_sets_of_superset self_mem_nhds_within hst lemma times_cont_diff_within_at.congr_nhds {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) {t : set E} (hst : 𝓝[s] x = 𝓝[t] x) : times_cont_diff_within_at 𝕜 n f t x := h.mono_of_mem $ hst ▸ self_mem_nhds_within lemma times_cont_diff_within_at_congr_nhds {n : with_top ℕ} {t : set E} (hst : 𝓝[s] x = 𝓝[t] x) : times_cont_diff_within_at 𝕜 n f s x ↔ times_cont_diff_within_at 𝕜 n f t x := ⟨λ h, h.congr_nhds hst, λ h, h.congr_nhds hst.symm⟩ lemma times_cont_diff_within_at_inter' {n : with_top ℕ} (h : t ∈ 𝓝[s] x) : times_cont_diff_within_at 𝕜 n f (s ∩ t) x ↔ times_cont_diff_within_at 𝕜 n f s x := times_cont_diff_within_at_congr_nhds $ eq.symm $ nhds_within_restrict'' _ h lemma times_cont_diff_within_at_inter {n : with_top ℕ} (h : t ∈ 𝓝 x) : times_cont_diff_within_at 𝕜 n f (s ∩ t) x ↔ times_cont_diff_within_at 𝕜 n f s x := times_cont_diff_within_at_inter' (mem_nhds_within_of_mem_nhds h) /-- If a function is `C^n` within a set at a point, with `n ≥ 1`, then it is differentiable within this set at this point. -/ lemma times_cont_diff_within_at.differentiable_within_at' {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (hn : 1 ≤ n) : differentiable_within_at 𝕜 f (insert x s) x := begin rcases h 1 hn with ⟨u, hu, p, H⟩, rcases mem_nhds_within.1 hu with ⟨t, t_open, xt, tu⟩, rw inter_comm at tu, have := ((H.mono tu).differentiable_on (le_refl _)) x ⟨mem_insert x s, xt⟩, exact (differentiable_within_at_inter (mem_nhds_sets t_open xt)).1 this, end lemma times_cont_diff_within_at.differentiable_within_at {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (hn : 1 ≤ n) : differentiable_within_at 𝕜 f s x := (h.differentiable_within_at' hn).mono (subset_insert x s) /-- A function is `C^(n + 1)` on a domain iff locally, it has a derivative which is `C^n`. -/ theorem times_cont_diff_within_at_succ_iff_has_fderiv_within_at {n : ℕ} : times_cont_diff_within_at 𝕜 ((n + 1) : ℕ) f s x ↔ ∃ u ∈ 𝓝[insert x s] x, ∃ f' : E → (E →L[𝕜] F), (∀ x ∈ u, has_fderiv_within_at f (f' x) u x) ∧ (times_cont_diff_within_at 𝕜 n f' u x) := begin split, { assume h, rcases h n.succ (le_refl _) with ⟨u, hu, p, Hp⟩, refine ⟨u, hu, λ y, (continuous_multilinear_curry_fin1 𝕜 E F) (p y 1), λ y hy, Hp.has_fderiv_within_at (with_top.coe_le_coe.2 (nat.le_add_left 1 n)) hy, _⟩, assume m hm, refine ⟨u, _, λ (y : E), (p y).shift, _⟩, { convert self_mem_nhds_within, have : x ∈ insert x s, by simp, exact (insert_eq_of_mem (mem_of_mem_nhds_within this hu)) }, { rw has_ftaylor_series_up_to_on_succ_iff_right at Hp, exact Hp.2.2.of_le hm } }, { rintros ⟨u, hu, f', f'_eq_deriv, Hf'⟩, rw times_cont_diff_within_at_nat, rcases Hf' n (le_refl _) with ⟨v, hv, p', Hp'⟩, refine ⟨v ∩ u, _, λ x, (p' x).unshift (f x), _⟩, { apply filter.inter_mem_sets _ hu, apply nhds_within_le_of_mem hu, exact nhds_within_mono _ (subset_insert x u) hv }, { rw has_ftaylor_series_up_to_on_succ_iff_right, refine ⟨λ y hy, rfl, λ y hy, _, _⟩, { change has_fderiv_within_at (λ z, (continuous_multilinear_curry_fin0 𝕜 E F).symm (f z)) ((formal_multilinear_series.unshift (p' y) (f y) 1).curry_left) (v ∩ u) y, rw linear_isometry_equiv.comp_has_fderiv_within_at_iff', convert (f'_eq_deriv y hy.2).mono (inter_subset_right v u), rw ← Hp'.zero_eq y hy.1, ext z, change ((p' y 0) (init (@cons 0 (λ i, E) z 0))) (@cons 0 (λ i, E) z 0 (last 0)) = ((p' y 0) 0) z, unfold_coes, congr }, { convert (Hp'.mono (inter_subset_left v u)).congr (λ x hx, Hp'.zero_eq x hx.1), { ext x y, change p' x 0 (init (@snoc 0 (λ i : fin 1, E) 0 y)) y = p' x 0 0 y, rw init_snoc }, { ext x k v y, change p' x k (init (@snoc k (λ i : fin k.succ, E) v y)) (@snoc k (λ i : fin k.succ, E) v y (last k)) = p' x k v y, rw [snoc_last, init_snoc] } } } } end /-! ### Smooth functions within a set -/ variable (𝕜) /-- A function is continuously differentiable up to `n` on `s` if, for any point `x` in `s`, it admits continuous derivatives up to order `n` on a neighborhood of `x` in `s`. For `n = ∞`, we only require that this holds up to any finite order (where the neighborhood may depend on the finite order we consider). -/ definition times_cont_diff_on (n : with_top ℕ) (f : E → F) (s : set E) := ∀ x ∈ s, times_cont_diff_within_at 𝕜 n f s x variable {𝕜} lemma times_cont_diff_on.times_cont_diff_within_at {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hx : x ∈ s) : times_cont_diff_within_at 𝕜 n f s x := h x hx lemma times_cont_diff_within_at.times_cont_diff_on {n : with_top ℕ} {m : ℕ} (hm : (m : with_top ℕ) ≤ n) (h : times_cont_diff_within_at 𝕜 n f s x) : ∃ u ∈ 𝓝[insert x s] x, u ⊆ insert x s ∧ times_cont_diff_on 𝕜 m f u := begin rcases h m hm with ⟨u, u_nhd, p, hp⟩, refine ⟨u ∩ insert x s, filter.inter_mem_sets u_nhd self_mem_nhds_within, inter_subset_right _ _, _⟩, assume y hy m' hm', refine ⟨u ∩ insert x s, _, p, (hp.mono (inter_subset_left _ _)).of_le hm'⟩, convert self_mem_nhds_within, exact insert_eq_of_mem hy end lemma times_cont_diff_on.of_le {m n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : m ≤ n) : times_cont_diff_on 𝕜 m f s := λ x hx, (h x hx).of_le hmn lemma times_cont_diff_on_iff_forall_nat_le {n : with_top ℕ} : times_cont_diff_on 𝕜 n f s ↔ ∀ m : ℕ, ↑m ≤ n → times_cont_diff_on 𝕜 m f s := ⟨λ H m hm, H.of_le hm, λ H x hx m hm, H m hm x hx m le_rfl⟩ lemma times_cont_diff_on_top : times_cont_diff_on 𝕜 ∞ f s ↔ ∀ (n : ℕ), times_cont_diff_on 𝕜 n f s := times_cont_diff_on_iff_forall_nat_le.trans $ by simp only [le_top, forall_prop_of_true] lemma times_cont_diff_on_all_iff_nat : (∀ n, times_cont_diff_on 𝕜 n f s) ↔ (∀ n : ℕ, times_cont_diff_on 𝕜 n f s) := begin refine ⟨λ H n, H n, _⟩, rintro H (_|n), exacts [times_cont_diff_on_top.2 H, H n] end lemma times_cont_diff_on.continuous_on {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) : continuous_on f s := λ x hx, (h x hx).continuous_within_at lemma times_cont_diff_on.congr {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (h₁ : ∀ x ∈ s, f₁ x = f x) : times_cont_diff_on 𝕜 n f₁ s := λ x hx, (h x hx).congr h₁ (h₁ x hx) lemma times_cont_diff_on_congr {n : with_top ℕ} (h₁ : ∀ x ∈ s, f₁ x = f x) : times_cont_diff_on 𝕜 n f₁ s ↔ times_cont_diff_on 𝕜 n f s := ⟨λ H, H.congr (λ x hx, (h₁ x hx).symm), λ H, H.congr h₁⟩ lemma times_cont_diff_on.mono {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) {t : set E} (hst : t ⊆ s) : times_cont_diff_on 𝕜 n f t := λ x hx, (h x (hst hx)).mono hst lemma times_cont_diff_on.congr_mono {n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (h₁ : ∀ x ∈ s₁, f₁ x = f x) (hs : s₁ ⊆ s) : times_cont_diff_on 𝕜 n f₁ s₁ := (hf.mono hs).congr h₁ /-- If a function is `C^n` on a set with `n ≥ 1`, then it is differentiable there. -/ lemma times_cont_diff_on.differentiable_on {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s := λ x hx, (h x hx).differentiable_within_at hn /-- If a function is `C^n` around each point in a set, then it is `C^n` on the set. -/ lemma times_cont_diff_on_of_locally_times_cont_diff_on {n : with_top ℕ} (h : ∀ x ∈ s, ∃u, is_open u ∧ x ∈ u ∧ times_cont_diff_on 𝕜 n f (s ∩ u)) : times_cont_diff_on 𝕜 n f s := begin assume x xs, rcases h x xs with ⟨u, u_open, xu, hu⟩, apply (times_cont_diff_within_at_inter _).1 (hu x ⟨xs, xu⟩), exact mem_nhds_sets u_open xu end /-- A function is `C^(n + 1)` on a domain iff locally, it has a derivative which is `C^n`. -/ theorem times_cont_diff_on_succ_iff_has_fderiv_within_at {n : ℕ} : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ ∀ x ∈ s, ∃ u ∈ 𝓝[insert x s] x, ∃ f' : E → (E →L[𝕜] F), (∀ x ∈ u, has_fderiv_within_at f (f' x) u x) ∧ (times_cont_diff_on 𝕜 n f' u) := begin split, { assume h x hx, rcases (h x hx) n.succ (le_refl _) with ⟨u, hu, p, Hp⟩, refine ⟨u, hu, λ y, (continuous_multilinear_curry_fin1 𝕜 E F) (p y 1), λ y hy, Hp.has_fderiv_within_at (with_top.coe_le_coe.2 (nat.le_add_left 1 n)) hy, _⟩, rw has_ftaylor_series_up_to_on_succ_iff_right at Hp, assume z hz m hm, refine ⟨u, _, λ (x : E), (p x).shift, Hp.2.2.of_le hm⟩, convert self_mem_nhds_within, exact insert_eq_of_mem hz, }, { assume h x hx, rw times_cont_diff_within_at_succ_iff_has_fderiv_within_at, rcases h x hx with ⟨u, u_nhbd, f', hu, hf'⟩, have : x ∈ u := mem_of_mem_nhds_within (mem_insert _ _) u_nhbd, exact ⟨u, u_nhbd, f', hu, hf' x this⟩ } end /-! ### Iterated derivative within a set -/ variable (𝕜) /-- The `n`-th derivative of a function along a set, defined inductively by saying that the `n+1`-th derivative of `f` is the derivative of the `n`-th derivative of `f` along this set, together with an uncurrying step to see it as a multilinear map in `n+1` variables.. -/ noncomputable def iterated_fderiv_within (n : ℕ) (f : E → F) (s : set E) : E → (E [×n]→L[𝕜] F) := nat.rec_on n (λ x, continuous_multilinear_map.curry0 𝕜 E (f x)) (λ n rec x, continuous_linear_map.uncurry_left (fderiv_within 𝕜 rec s x)) /-- Formal Taylor series associated to a function within a set. -/ def ftaylor_series_within (f : E → F) (s : set E) (x : E) : formal_multilinear_series 𝕜 E F := λ n, iterated_fderiv_within 𝕜 n f s x variable {𝕜} @[simp] lemma iterated_fderiv_within_zero_apply (m : (fin 0) → E) : (iterated_fderiv_within 𝕜 0 f s x : ((fin 0) → E) → F) m = f x := rfl lemma iterated_fderiv_within_zero_eq_comp : iterated_fderiv_within 𝕜 0 f s = (continuous_multilinear_curry_fin0 𝕜 E F).symm ∘ f := rfl lemma iterated_fderiv_within_succ_apply_left {n : ℕ} (m : fin (n + 1) → E): (iterated_fderiv_within 𝕜 (n + 1) f s x : (fin (n + 1) → E) → F) m = (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n f s) s x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) := rfl /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the derivative of the `n`-th derivative. -/ lemma iterated_fderiv_within_succ_eq_comp_left {n : ℕ} : iterated_fderiv_within 𝕜 (n + 1) f s = (continuous_multilinear_curry_left_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n f s) s) := rfl theorem iterated_fderiv_within_succ_apply_right {n : ℕ} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) (m : fin (n + 1) → E) : (iterated_fderiv_within 𝕜 (n + 1) f s x : (fin (n + 1) → E) → F) m = iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s x (init m) (m (last n)) := begin induction n with n IH generalizing x, { rw [iterated_fderiv_within_succ_eq_comp_left, iterated_fderiv_within_zero_eq_comp, iterated_fderiv_within_zero_apply, function.comp_apply, linear_isometry_equiv.comp_fderiv_within _ (hs x hx)], refl }, { let I := continuous_multilinear_curry_right_equiv' 𝕜 n E F, have A : ∀ y ∈ s, iterated_fderiv_within 𝕜 n.succ f s y = (I ∘ (iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s)) y, by { assume y hy, ext m, rw @IH m y hy, refl }, calc (iterated_fderiv_within 𝕜 (n+2) f s x : (fin (n+2) → E) → F) m = (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n.succ f s) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : rfl ... = (fderiv_within 𝕜 (I ∘ (iterated_fderiv_within 𝕜 n (fderiv_within 𝕜 f s) s)) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : by rw fderiv_within_congr (hs x hx) A (A x hx) ... = (I ∘ fderiv_within 𝕜 ((iterated_fderiv_within 𝕜 n (fderiv_within 𝕜 f s) s)) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : by { rw linear_isometry_equiv.comp_fderiv_within _ (hs x hx), refl } ... = (fderiv_within 𝕜 ((iterated_fderiv_within 𝕜 n (λ y, fderiv_within 𝕜 f s y) s)) s x : E → (E [×n]→L[𝕜] (E →L[𝕜] F))) (m 0) (init (tail m)) ((tail m) (last n)) : rfl ... = iterated_fderiv_within 𝕜 (nat.succ n) (λ y, fderiv_within 𝕜 f s y) s x (init m) (m (last (n + 1))) : by { rw [iterated_fderiv_within_succ_apply_left, tail_init_eq_init_tail], refl } } end /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the `n`-th derivative of the derivative. -/ lemma iterated_fderiv_within_succ_eq_comp_right {n : ℕ} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_fderiv_within 𝕜 (n + 1) f s x = ((continuous_multilinear_curry_right_equiv' 𝕜 n E F) ∘ (iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s)) x := by { ext m, rw iterated_fderiv_within_succ_apply_right hs hx, refl } @[simp] lemma iterated_fderiv_within_one_apply (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) (m : (fin 1) → E) : (iterated_fderiv_within 𝕜 1 f s x : ((fin 1) → E) → F) m = (fderiv_within 𝕜 f s x : E → F) (m 0) := by { rw [iterated_fderiv_within_succ_apply_right hs hx, iterated_fderiv_within_zero_apply], refl } /-- If two functions coincide on a set `s` of unique differentiability, then their iterated differentials within this set coincide. -/ lemma iterated_fderiv_within_congr {n : ℕ} (hs : unique_diff_on 𝕜 s) (hL : ∀y∈s, f₁ y = f y) (hx : x ∈ s) : iterated_fderiv_within 𝕜 n f₁ s x = iterated_fderiv_within 𝕜 n f s x := begin induction n with n IH generalizing x, { ext m, simp [hL x hx] }, { have : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f₁ s y) s x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) s x := fderiv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx), ext m, rw [iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_succ_apply_left, this] } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with an open set containing `x`. -/ lemma iterated_fderiv_within_inter_open {n : ℕ} (hu : is_open u) (hs : unique_diff_on 𝕜 (s ∩ u)) (hx : x ∈ s ∩ u) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := begin induction n with n IH generalizing x, { ext m, simp }, { have A : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f (s ∩ u) y) (s ∩ u) x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) (s ∩ u) x := fderiv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx), have B : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) (s ∩ u) x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) s x := fderiv_within_inter (mem_nhds_sets hu hx.2) ((unique_diff_within_at_inter (mem_nhds_sets hu hx.2)).1 (hs x hx)), ext m, rw [iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_succ_apply_left, A, B] } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with a neighborhood of `x` within `s`. -/ lemma iterated_fderiv_within_inter' {n : ℕ} (hu : u ∈ 𝓝[s] x) (hs : unique_diff_on 𝕜 s) (xs : x ∈ s) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := begin obtain ⟨v, v_open, xv, vu⟩ : ∃ v, is_open v ∧ x ∈ v ∧ v ∩ s ⊆ u := mem_nhds_within.1 hu, have A : (s ∩ u) ∩ v = s ∩ v, { apply subset.antisymm (inter_subset_inter (inter_subset_left _ _) (subset.refl _)), exact λ y ⟨ys, yv⟩, ⟨⟨ys, vu ⟨yv, ys⟩⟩, yv⟩ }, have : iterated_fderiv_within 𝕜 n f (s ∩ v) x = iterated_fderiv_within 𝕜 n f s x := iterated_fderiv_within_inter_open v_open (hs.inter v_open) ⟨xs, xv⟩, rw ← this, have : iterated_fderiv_within 𝕜 n f ((s ∩ u) ∩ v) x = iterated_fderiv_within 𝕜 n f (s ∩ u) x, { refine iterated_fderiv_within_inter_open v_open _ ⟨⟨xs, vu ⟨xv, xs⟩⟩, xv⟩, rw A, exact hs.inter v_open }, rw A at this, rw ← this end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with a neighborhood of `x`. -/ lemma iterated_fderiv_within_inter {n : ℕ} (hu : u ∈ 𝓝 x) (hs : unique_diff_on 𝕜 s) (xs : x ∈ s) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := iterated_fderiv_within_inter' (mem_nhds_within_of_mem_nhds hu) hs xs @[simp] lemma times_cont_diff_on_zero : times_cont_diff_on 𝕜 0 f s ↔ continuous_on f s := begin refine ⟨λ H, H.continuous_on, λ H, _⟩, assume x hx m hm, have : (m : with_top ℕ) = 0 := le_antisymm hm bot_le, rw this, refine ⟨insert x s, self_mem_nhds_within, ftaylor_series_within 𝕜 f s, _⟩, rw has_ftaylor_series_up_to_on_zero_iff, exact ⟨by rwa insert_eq_of_mem hx, λ x hx, by simp [ftaylor_series_within]⟩ end lemma times_cont_diff_within_at_zero (hx : x ∈ s) : times_cont_diff_within_at 𝕜 0 f s x ↔ ∃ u ∈ 𝓝[s] x, continuous_on f (s ∩ u) := begin split, { intros h, obtain ⟨u, H, p, hp⟩ := h 0 (by norm_num), refine ⟨u, _, _⟩, { simpa [hx] using H }, { simp only [with_top.coe_zero, has_ftaylor_series_up_to_on_zero_iff] at hp, exact hp.1.mono (inter_subset_right s u) } }, { rintros ⟨u, H, hu⟩, rw ← times_cont_diff_within_at_inter' H, have h' : x ∈ s ∩ u := ⟨hx, mem_of_mem_nhds_within hx H⟩, exact (times_cont_diff_on_zero.mpr hu).times_cont_diff_within_at h' } end /-- On a set with unique differentiability, any choice of iterated differential has to coincide with the one we have chosen in `iterated_fderiv_within 𝕜 m f s`. -/ theorem has_ftaylor_series_up_to_on.eq_ftaylor_series_of_unique_diff_on {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) {m : ℕ} (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : p x m = iterated_fderiv_within 𝕜 m f s x := begin induction m with m IH generalizing x, { rw [h.zero_eq' hx, iterated_fderiv_within_zero_eq_comp] }, { have A : (m : with_top ℕ) < n := lt_of_lt_of_le (with_top.coe_lt_coe.2 (lt_add_one m)) hmn, have : has_fderiv_within_at (λ (y : E), iterated_fderiv_within 𝕜 m f s y) (continuous_multilinear_map.curry_left (p x (nat.succ m))) s x := (h.fderiv_within m A x hx).congr (λ y hy, (IH (le_of_lt A) hy).symm) (IH (le_of_lt A) hx).symm, rw [iterated_fderiv_within_succ_eq_comp_left, function.comp_apply, this.fderiv_within (hs x hx)], exact (continuous_multilinear_map.uncurry_curry_left _).symm } end /-- When a function is `C^n` in a set `s` of unique differentiability, it admits `ftaylor_series_within 𝕜 f s` as a Taylor series up to order `n` in `s`. -/ theorem times_cont_diff_on.ftaylor_series_within {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) : has_ftaylor_series_up_to_on n f (ftaylor_series_within 𝕜 f s) s := begin split, { assume x hx, simp only [ftaylor_series_within, continuous_multilinear_map.uncurry0_apply, iterated_fderiv_within_zero_apply] }, { assume m hm x hx, rcases (h x hx) m.succ (with_top.add_one_le_of_lt hm) with ⟨u, hu, p, Hp⟩, rw insert_eq_of_mem hx at hu, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw inter_comm at ho, have : p x m.succ = ftaylor_series_within 𝕜 f s x m.succ, { change p x m.succ = iterated_fderiv_within 𝕜 m.succ f s x, rw ← iterated_fderiv_within_inter (mem_nhds_sets o_open xo) hs hx, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (le_refl _) (hs.inter o_open) ⟨hx, xo⟩ }, rw [← this, ← has_fderiv_within_at_inter (mem_nhds_sets o_open xo)], have A : ∀ y ∈ s ∩ o, p y m = ftaylor_series_within 𝕜 f s y m, { rintros y ⟨hy, yo⟩, change p y m = iterated_fderiv_within 𝕜 m f s y, rw ← iterated_fderiv_within_inter (mem_nhds_sets o_open yo) hs hy, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (with_top.coe_le_coe.2 (nat.le_succ m)) (hs.inter o_open) ⟨hy, yo⟩ }, exact ((Hp.mono ho).fderiv_within m (with_top.coe_lt_coe.2 (lt_add_one m)) x ⟨hx, xo⟩).congr (λ y hy, (A y hy).symm) (A x ⟨hx, xo⟩).symm }, { assume m hm, apply continuous_on_of_locally_continuous_on, assume x hx, rcases h x hx m hm with ⟨u, hu, p, Hp⟩, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw insert_eq_of_mem hx at ho, rw inter_comm at ho, refine ⟨o, o_open, xo, _⟩, have A : ∀ y ∈ s ∩ o, p y m = ftaylor_series_within 𝕜 f s y m, { rintros y ⟨hy, yo⟩, change p y m = iterated_fderiv_within 𝕜 m f s y, rw ← iterated_fderiv_within_inter (mem_nhds_sets o_open yo) hs hy, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (le_refl _) (hs.inter o_open) ⟨hy, yo⟩ }, exact ((Hp.mono ho).cont m (le_refl _)).congr (λ y hy, (A y hy).symm) } end lemma times_cont_diff_on_of_continuous_on_differentiable_on {n : with_top ℕ} (Hcont : ∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_fderiv_within 𝕜 m f s x) s) (Hdiff : ∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_fderiv_within 𝕜 m f s x) s) : times_cont_diff_on 𝕜 n f s := begin assume x hx m hm, rw insert_eq_of_mem hx, refine ⟨s, self_mem_nhds_within, ftaylor_series_within 𝕜 f s, _⟩, split, { assume y hy, simp only [ftaylor_series_within, continuous_multilinear_map.uncurry0_apply, iterated_fderiv_within_zero_apply] }, { assume k hk y hy, convert (Hdiff k (lt_of_lt_of_le hk hm) y hy).has_fderiv_within_at, simp only [ftaylor_series_within, iterated_fderiv_within_succ_eq_comp_left, continuous_linear_equiv.coe_apply, function.comp_app, coe_fn_coe_base], exact continuous_linear_map.curry_uncurry_left _ }, { assume k hk, exact Hcont k (le_trans hk hm) } end lemma times_cont_diff_on_of_differentiable_on {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s) : times_cont_diff_on 𝕜 n f s := times_cont_diff_on_of_continuous_on_differentiable_on (λ m hm, (h m hm).continuous_on) (λ m hm, (h m (le_of_lt hm))) lemma times_cont_diff_on.continuous_on_iterated_fderiv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) : continuous_on (iterated_fderiv_within 𝕜 m f s) s := (h.ftaylor_series_within hs).cont m hmn lemma times_cont_diff_on.differentiable_on_iterated_fderiv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) < n) (hs : unique_diff_on 𝕜 s) : differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s := λ x hx, ((h.ftaylor_series_within hs).fderiv_within m hmn x hx).differentiable_within_at lemma times_cont_diff_on_iff_continuous_on_differentiable_on {n : with_top ℕ} (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n f s ↔ (∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_fderiv_within 𝕜 m f s x) s) ∧ (∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_fderiv_within 𝕜 m f s x) s) := begin split, { assume h, split, { assume m hm, exact h.continuous_on_iterated_fderiv_within hm hs }, { assume m hm, exact h.differentiable_on_iterated_fderiv_within hm hs } }, { assume h, exact times_cont_diff_on_of_continuous_on_differentiable_on h.1 h.2 } end /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (expressed with `fderiv_within`) is `C^n`. -/ theorem times_cont_diff_on_succ_iff_fderiv_within {n : ℕ} (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 n (λ y, fderiv_within 𝕜 f s y) s := begin split, { assume H, refine ⟨H.differentiable_on (with_top.coe_le_coe.2 (nat.le_add_left 1 n)), λ x hx, _⟩, rcases times_cont_diff_within_at_succ_iff_has_fderiv_within_at.1 (H x hx) with ⟨u, hu, f', hff', hf'⟩, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw [inter_comm, insert_eq_of_mem hx] at ho, have := hf'.mono ho, rw times_cont_diff_within_at_inter' (mem_nhds_within_of_mem_nhds (mem_nhds_sets o_open xo)) at this, apply this.congr_of_eventually_eq' _ hx, have : o ∩ s ∈ 𝓝[s] x := mem_nhds_within.2 ⟨o, o_open, xo, subset.refl _⟩, rw inter_comm at this, apply filter.eventually_eq_of_mem this (λ y hy, _), have A : fderiv_within 𝕜 f (s ∩ o) y = f' y := ((hff' y (ho hy)).mono ho).fderiv_within (hs.inter o_open y hy), rwa fderiv_within_inter (mem_nhds_sets o_open hy.2) (hs y hy.1) at A, }, { rintros ⟨hdiff, h⟩ x hx, rw [times_cont_diff_within_at_succ_iff_has_fderiv_within_at, insert_eq_of_mem hx], exact ⟨s, self_mem_nhds_within, fderiv_within 𝕜 f s, λ y hy, (hdiff y hy).has_fderiv_within_at, h x hx⟩ } end /-- A function is `C^(n + 1)` on an open domain if and only if it is differentiable there, and its derivative (expressed with `fderiv`) is `C^n`. -/ theorem times_cont_diff_on_succ_iff_fderiv_of_open {n : ℕ} (hs : is_open s) : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 n (λ y, fderiv 𝕜 f y) s := begin rw times_cont_diff_on_succ_iff_fderiv_within hs.unique_diff_on, congr' 2, rw ← iff_iff_eq, apply times_cont_diff_on_congr, assume x hx, exact fderiv_within_of_open hs hx end /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (expressed with `fderiv_within`) is `C^∞`. -/ theorem times_cont_diff_on_top_iff_fderiv_within (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 ∞ f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 ∞ (λ y, fderiv_within 𝕜 f s y) s := begin split, { assume h, refine ⟨h.differentiable_on le_top, _⟩, apply times_cont_diff_on_top.2 (λ n, ((times_cont_diff_on_succ_iff_fderiv_within hs).1 _).2), exact h.of_le le_top }, { assume h, refine times_cont_diff_on_top.2 (λ n, _), have A : (n : with_top ℕ) ≤ ∞ := le_top, apply ((times_cont_diff_on_succ_iff_fderiv_within hs).2 ⟨h.1, h.2.of_le A⟩).of_le, exact with_top.coe_le_coe.2 (nat.le_succ n) } end /-- A function is `C^∞` on an open domain if and only if it is differentiable there, and its derivative (expressed with `fderiv`) is `C^∞`. -/ theorem times_cont_diff_on_top_iff_fderiv_of_open (hs : is_open s) : times_cont_diff_on 𝕜 ∞ f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 ∞ (λ y, fderiv 𝕜 f y) s := begin rw times_cont_diff_on_top_iff_fderiv_within hs.unique_diff_on, congr' 2, rw ← iff_iff_eq, apply times_cont_diff_on_congr, assume x hx, exact fderiv_within_of_open hs hx end lemma times_cont_diff_on.fderiv_within {m n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (λ y, fderiv_within 𝕜 f s y) s := begin cases m, { change ∞ + 1 ≤ n at hmn, have : n = ∞, by simpa using hmn, rw this at hf, exact ((times_cont_diff_on_top_iff_fderiv_within hs).1 hf).2 }, { change (m.succ : with_top ℕ) ≤ n at hmn, exact ((times_cont_diff_on_succ_iff_fderiv_within hs).1 (hf.of_le hmn)).2 } end lemma times_cont_diff_on.fderiv_of_open {m n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (hs : is_open s) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (λ y, fderiv 𝕜 f y) s := (hf.fderiv_within hs.unique_diff_on hmn).congr (λ x hx, (fderiv_within_of_open hs hx).symm) lemma times_cont_diff_on.continuous_on_fderiv_within {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hn : 1 ≤ n) : continuous_on (λ x, fderiv_within 𝕜 f s x) s := ((times_cont_diff_on_succ_iff_fderiv_within hs).1 (h.of_le hn)).2.continuous_on lemma times_cont_diff_on.continuous_on_fderiv_of_open {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : is_open s) (hn : 1 ≤ n) : continuous_on (λ x, fderiv 𝕜 f x) s := ((times_cont_diff_on_succ_iff_fderiv_of_open hs).1 (h.of_le hn)).2.continuous_on /-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is continuous. -/ lemma times_cont_diff_on.continuous_on_fderiv_within_apply {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hn : 1 ≤ n) : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1 : E → F) p.2) (set.prod s univ) := begin have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1, p.2)) (set.prod s univ), { apply continuous_on.prod _ continuous_snd.continuous_on, exact continuous_on.comp (h.continuous_on_fderiv_within hs hn) continuous_fst.continuous_on (prod_subset_preimage_fst _ _) }, exact A.comp_continuous_on B end /-! ### Functions with a Taylor series on the whole space -/ /-- `has_ftaylor_series_up_to n f p` registers the fact that `p 0 = f` and `p (m+1)` is a derivative of `p m` for `m < n`, and is continuous for `m ≤ n`. This is a predicate analogous to `has_fderiv_at` but for higher order derivatives. -/ structure has_ftaylor_series_up_to (n : with_top ℕ) (f : E → F) (p : E → formal_multilinear_series 𝕜 E F) : Prop := (zero_eq : ∀ x, (p x 0).uncurry0 = f x) (fderiv : ∀ (m : ℕ) (hm : (m : with_top ℕ) < n), ∀ x, has_fderiv_at (λ y, p y m) (p x m.succ).curry_left x) (cont : ∀ (m : ℕ) (hm : (m : with_top ℕ) ≤ n), continuous (λ x, p x m)) lemma has_ftaylor_series_up_to.zero_eq' {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (x : E) : p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x) := by { rw ← h.zero_eq x, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ } lemma has_ftaylor_series_up_to_on_univ_iff {n : with_top ℕ} : has_ftaylor_series_up_to_on n f p univ ↔ has_ftaylor_series_up_to n f p := begin split, { assume H, split, { exact λ x, H.zero_eq x (mem_univ x) }, { assume m hm x, rw ← has_fderiv_within_at_univ, exact H.fderiv_within m hm x (mem_univ x) }, { assume m hm, rw continuous_iff_continuous_on_univ, exact H.cont m hm } }, { assume H, split, { exact λ x hx, H.zero_eq x }, { assume m hm x hx, rw has_fderiv_within_at_univ, exact H.fderiv m hm x }, { assume m hm, rw ← continuous_iff_continuous_on_univ, exact H.cont m hm } } end lemma has_ftaylor_series_up_to.has_ftaylor_series_up_to_on {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (s : set E) : has_ftaylor_series_up_to_on n f p s := (has_ftaylor_series_up_to_on_univ_iff.2 h).mono (subset_univ _) lemma has_ftaylor_series_up_to.of_le {m n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (hmn : m ≤ n) : has_ftaylor_series_up_to m f p := by { rw ← has_ftaylor_series_up_to_on_univ_iff at h ⊢, exact h.of_le hmn } lemma has_ftaylor_series_up_to.continuous {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) : continuous f := begin rw ← has_ftaylor_series_up_to_on_univ_iff at h, rw continuous_iff_continuous_on_univ, exact h.continuous_on end lemma has_ftaylor_series_up_to_zero_iff : has_ftaylor_series_up_to 0 f p ↔ continuous f ∧ (∀ x, (p x 0).uncurry0 = f x) := by simp [has_ftaylor_series_up_to_on_univ_iff.symm, continuous_iff_continuous_on_univ, has_ftaylor_series_up_to_on_zero_iff] /-- If a function has a Taylor series at order at least `1`, then the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to.has_fderiv_at {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (hn : 1 ≤ n) (x : E) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) x := begin rw [← has_fderiv_within_at_univ], exact (has_ftaylor_series_up_to_on_univ_iff.2 h).has_fderiv_within_at hn (mem_univ _) end lemma has_ftaylor_series_up_to.differentiable {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (hn : 1 ≤ n) : differentiable 𝕜 f := λ x, (h.has_fderiv_at hn x).differentiable_at /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p.shift` is a Taylor series up to `n` for `p 1`, which is a derivative of `f`. -/ theorem has_ftaylor_series_up_to_succ_iff_right {n : ℕ} : has_ftaylor_series_up_to ((n + 1) : ℕ) f p ↔ (∀ x, (p x 0).uncurry0 = f x) ∧ (∀ x, has_fderiv_at (λ y, p y 0) (p x 1).curry_left x) ∧ has_ftaylor_series_up_to n (λ x, continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) (λ x, (p x).shift) := by simp [has_ftaylor_series_up_to_on_succ_iff_right, has_ftaylor_series_up_to_on_univ_iff.symm, -add_comm, -with_zero.coe_add] /-! ### Smooth functions at a point -/ variable (𝕜) /-- A function is continuously differentiable up to `n` at a point `x` if, for any integer `k ≤ n`, there is a neighborhood of `x` where `f` admits derivatives up to order `n`, which are continuous. -/ def times_cont_diff_at (n : with_top ℕ) (f : E → F) (x : E) := times_cont_diff_within_at 𝕜 n f univ x variable {𝕜} theorem times_cont_diff_within_at_univ {n : with_top ℕ} : times_cont_diff_within_at 𝕜 n f univ x ↔ times_cont_diff_at 𝕜 n f x := iff.rfl lemma times_cont_diff_at_top : times_cont_diff_at 𝕜 ∞ f x ↔ ∀ (n : ℕ), times_cont_diff_at 𝕜 n f x := by simp [← times_cont_diff_within_at_univ, times_cont_diff_within_at_top] lemma times_cont_diff_at.times_cont_diff_within_at {n : with_top ℕ} (h : times_cont_diff_at 𝕜 n f x) : times_cont_diff_within_at 𝕜 n f s x := h.mono (subset_univ _) lemma times_cont_diff_within_at.times_cont_diff_at {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (hx : s ∈ 𝓝 x) : times_cont_diff_at 𝕜 n f x := by rwa [times_cont_diff_at, ← times_cont_diff_within_at_inter hx, univ_inter] lemma times_cont_diff_at.congr_of_eventually_eq {n : with_top ℕ} (h : times_cont_diff_at 𝕜 n f x) (hg : f₁ =ᶠ[𝓝 x] f) : times_cont_diff_at 𝕜 n f₁ x := h.congr_of_eventually_eq' (by rwa nhds_within_univ) (mem_univ x) lemma times_cont_diff_at.of_le {m n : with_top ℕ} (h : times_cont_diff_at 𝕜 n f x) (hmn : m ≤ n) : times_cont_diff_at 𝕜 m f x := h.of_le hmn lemma times_cont_diff_at.continuous_at {n : with_top ℕ} (h : times_cont_diff_at 𝕜 n f x) : continuous_at f x := by simpa [continuous_within_at_univ] using h.continuous_within_at /-- If a function is `C^n` with `n ≥ 1` at a point, then it is differentiable there. -/ lemma times_cont_diff_at.differentiable_at {n : with_top ℕ} (h : times_cont_diff_at 𝕜 n f x) (hn : 1 ≤ n) : differentiable_at 𝕜 f x := by simpa [hn, differentiable_within_at_univ] using h.differentiable_within_at /-- A function is `C^(n + 1)` at a point iff locally, it has a derivative which is `C^n`. -/ theorem times_cont_diff_at_succ_iff_has_fderiv_at {n : ℕ} : times_cont_diff_at 𝕜 ((n + 1) : ℕ) f x ↔ (∃ f' : E → (E →L[𝕜] F), (∃ u ∈ 𝓝 x, (∀ x ∈ u, has_fderiv_at f (f' x) x)) ∧ (times_cont_diff_at 𝕜 n f' x)) := begin rw [← times_cont_diff_within_at_univ, times_cont_diff_within_at_succ_iff_has_fderiv_within_at], simp only [nhds_within_univ, exists_prop, mem_univ, insert_eq_of_mem], split, { rintros ⟨u, H, f', h_fderiv, h_times_cont_diff⟩, rcases mem_nhds_sets_iff.mp H with ⟨t, htu, ht, hxt⟩, refine ⟨f', ⟨t, _⟩, h_times_cont_diff.times_cont_diff_at H⟩, refine ⟨mem_nhds_sets_iff.mpr ⟨t, subset.rfl, ht, hxt⟩, _⟩, intros y hyt, refine (h_fderiv y (htu hyt)).has_fderiv_at _, exact mem_nhds_sets_iff.mpr ⟨t, htu, ht, hyt⟩ }, { rintros ⟨f', ⟨u, H, h_fderiv⟩, h_times_cont_diff⟩, refine ⟨u, H, f', _, h_times_cont_diff.times_cont_diff_within_at⟩, intros x hxu, exact (h_fderiv x hxu).has_fderiv_within_at } end /-! ### Smooth functions -/ variable (𝕜) /-- A function is continuously differentiable up to `n` if it admits derivatives up to order `n`, which are continuous. Contrary to the case of definitions in domains (where derivatives might not be unique) we do not need to localize the definition in space or time. -/ definition times_cont_diff (n : with_top ℕ) (f : E → F) := ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to n f p variable {𝕜} theorem times_cont_diff_on_univ {n : with_top ℕ} : times_cont_diff_on 𝕜 n f univ ↔ times_cont_diff 𝕜 n f := begin split, { assume H, use ftaylor_series_within 𝕜 f univ, rw ← has_ftaylor_series_up_to_on_univ_iff, exact H.ftaylor_series_within unique_diff_on_univ }, { rintros ⟨p, hp⟩ x hx m hm, exact ⟨univ, filter.univ_sets _, p, (hp.has_ftaylor_series_up_to_on univ).of_le hm⟩ } end lemma times_cont_diff_iff_times_cont_diff_at {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ ∀ x, times_cont_diff_at 𝕜 n f x := by simp [← times_cont_diff_on_univ, times_cont_diff_on, times_cont_diff_at] lemma times_cont_diff.times_cont_diff_at {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : times_cont_diff_at 𝕜 n f x := times_cont_diff_iff_times_cont_diff_at.1 h x lemma times_cont_diff.times_cont_diff_within_at {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : times_cont_diff_within_at 𝕜 n f s x := h.times_cont_diff_at.times_cont_diff_within_at lemma times_cont_diff_top : times_cont_diff 𝕜 ∞ f ↔ ∀ (n : ℕ), times_cont_diff 𝕜 n f := by simp [times_cont_diff_on_univ.symm, times_cont_diff_on_top] lemma times_cont_diff_all_iff_nat : (∀ n, times_cont_diff 𝕜 n f) ↔ (∀ n : ℕ, times_cont_diff 𝕜 n f) := by simp only [← times_cont_diff_on_univ, times_cont_diff_on_all_iff_nat] lemma times_cont_diff.times_cont_diff_on {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : times_cont_diff_on 𝕜 n f s := (times_cont_diff_on_univ.2 h).mono (subset_univ _) @[simp] lemma times_cont_diff_zero : times_cont_diff 𝕜 0 f ↔ continuous f := begin rw [← times_cont_diff_on_univ, continuous_iff_continuous_on_univ], exact times_cont_diff_on_zero end lemma times_cont_diff_at_zero : times_cont_diff_at 𝕜 0 f x ↔ ∃ u ∈ 𝓝 x, continuous_on f u := by { rw ← times_cont_diff_within_at_univ, simp [times_cont_diff_within_at_zero, nhds_within_univ] } lemma times_cont_diff.of_le {m n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hmn : m ≤ n) : times_cont_diff 𝕜 m f := times_cont_diff_on_univ.1 $ (times_cont_diff_on_univ.2 h).of_le hmn lemma times_cont_diff.continuous {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : continuous f := times_cont_diff_zero.1 (h.of_le bot_le) /-- If a function is `C^n` with `n ≥ 1`, then it is differentiable. -/ lemma times_cont_diff.differentiable {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : differentiable 𝕜 f := differentiable_on_univ.1 $ (times_cont_diff_on_univ.2 h).differentiable_on hn /-! ### Iterated derivative -/ variable (𝕜) /-- The `n`-th derivative of a function, as a multilinear map, defined inductively. -/ noncomputable def iterated_fderiv (n : ℕ) (f : E → F) : E → (E [×n]→L[𝕜] F) := nat.rec_on n (λ x, continuous_multilinear_map.curry0 𝕜 E (f x)) (λ n rec x, continuous_linear_map.uncurry_left (fderiv 𝕜 rec x)) /-- Formal Taylor series associated to a function within a set. -/ def ftaylor_series (f : E → F) (x : E) : formal_multilinear_series 𝕜 E F := λ n, iterated_fderiv 𝕜 n f x variable {𝕜} @[simp] lemma iterated_fderiv_zero_apply (m : (fin 0) → E) : (iterated_fderiv 𝕜 0 f x : ((fin 0) → E) → F) m = f x := rfl lemma iterated_fderiv_zero_eq_comp : iterated_fderiv 𝕜 0 f = (continuous_multilinear_curry_fin0 𝕜 E F).symm ∘ f := rfl lemma iterated_fderiv_succ_apply_left {n : ℕ} (m : fin (n + 1) → E): (iterated_fderiv 𝕜 (n + 1) f x : (fin (n + 1) → E) → F) m = (fderiv 𝕜 (iterated_fderiv 𝕜 n f) x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) := rfl /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the derivative of the `n`-th derivative. -/ lemma iterated_fderiv_succ_eq_comp_left {n : ℕ} : iterated_fderiv 𝕜 (n + 1) f = (continuous_multilinear_curry_left_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (fderiv 𝕜 (iterated_fderiv 𝕜 n f)) := rfl lemma iterated_fderiv_within_univ {n : ℕ} : iterated_fderiv_within 𝕜 n f univ = iterated_fderiv 𝕜 n f := begin induction n with n IH, { ext x, simp }, { ext x m, rw [iterated_fderiv_succ_apply_left, iterated_fderiv_within_succ_apply_left, IH, fderiv_within_univ] } end lemma ftaylor_series_within_univ : ftaylor_series_within 𝕜 f univ = ftaylor_series 𝕜 f := begin ext1 x, ext1 n, change iterated_fderiv_within 𝕜 n f univ x = iterated_fderiv 𝕜 n f x, rw iterated_fderiv_within_univ end theorem iterated_fderiv_succ_apply_right {n : ℕ} (m : fin (n + 1) → E) : (iterated_fderiv 𝕜 (n + 1) f x : (fin (n + 1) → E) → F) m = iterated_fderiv 𝕜 n (λy, fderiv 𝕜 f y) x (init m) (m (last n)) := begin rw [← iterated_fderiv_within_univ, ← iterated_fderiv_within_univ, ← fderiv_within_univ], exact iterated_fderiv_within_succ_apply_right unique_diff_on_univ (mem_univ _) _ end /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the `n`-th derivative of the derivative. -/ lemma iterated_fderiv_succ_eq_comp_right {n : ℕ} : iterated_fderiv 𝕜 (n + 1) f x = ((continuous_multilinear_curry_right_equiv' 𝕜 n E F) ∘ (iterated_fderiv 𝕜 n (λy, fderiv 𝕜 f y))) x := by { ext m, rw iterated_fderiv_succ_apply_right, refl } @[simp] lemma iterated_fderiv_one_apply (m : (fin 1) → E) : (iterated_fderiv 𝕜 1 f x : ((fin 1) → E) → F) m = (fderiv 𝕜 f x : E → F) (m 0) := by { rw [iterated_fderiv_succ_apply_right, iterated_fderiv_zero_apply], refl } /-- When a function is `C^n` in a set `s` of unique differentiability, it admits `ftaylor_series_within 𝕜 f s` as a Taylor series up to order `n` in `s`. -/ theorem times_cont_diff_on_iff_ftaylor_series {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ has_ftaylor_series_up_to n f (ftaylor_series 𝕜 f) := begin split, { rw [← times_cont_diff_on_univ, ← has_ftaylor_series_up_to_on_univ_iff, ← ftaylor_series_within_univ], exact λ h, times_cont_diff_on.ftaylor_series_within h unique_diff_on_univ }, { assume h, exact ⟨ftaylor_series 𝕜 f, h⟩ } end lemma times_cont_diff_iff_continuous_differentiable {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ (∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous (λ x, iterated_fderiv 𝕜 m f x)) ∧ (∀ (m : ℕ), (m : with_top ℕ) < n → differentiable 𝕜 (λ x, iterated_fderiv 𝕜 m f x)) := by simp [times_cont_diff_on_univ.symm, continuous_iff_continuous_on_univ, differentiable_on_univ.symm, iterated_fderiv_within_univ, times_cont_diff_on_iff_continuous_on_differentiable_on unique_diff_on_univ] lemma times_cont_diff_of_differentiable_iterated_fderiv {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable 𝕜 (iterated_fderiv 𝕜 m f)) : times_cont_diff 𝕜 n f := times_cont_diff_iff_continuous_differentiable.2 ⟨λ m hm, (h m hm).continuous, λ m hm, (h m (le_of_lt hm))⟩ /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative is `C^n`. -/ theorem times_cont_diff_succ_iff_fderiv {n : ℕ} : times_cont_diff 𝕜 ((n + 1) : ℕ) f ↔ differentiable 𝕜 f ∧ times_cont_diff 𝕜 n (λ y, fderiv 𝕜 f y) := by simp [times_cont_diff_on_univ.symm, differentiable_on_univ.symm, fderiv_within_univ.symm, - fderiv_within_univ, times_cont_diff_on_succ_iff_fderiv_within unique_diff_on_univ, -with_zero.coe_add, -add_comm] /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative is `C^∞`. -/ theorem times_cont_diff_top_iff_fderiv : times_cont_diff 𝕜 ∞ f ↔ differentiable 𝕜 f ∧ times_cont_diff 𝕜 ∞ (λ y, fderiv 𝕜 f y) := begin simp [times_cont_diff_on_univ.symm, differentiable_on_univ.symm, fderiv_within_univ.symm, - fderiv_within_univ], rw times_cont_diff_on_top_iff_fderiv_within unique_diff_on_univ, end lemma times_cont_diff.continuous_fderiv {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : continuous (λ x, fderiv 𝕜 f x) := ((times_cont_diff_succ_iff_fderiv).1 (h.of_le hn)).2.continuous /-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is continuous. -/ lemma times_cont_diff.continuous_fderiv_apply {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : continuous (λp : E × E, (fderiv 𝕜 f p.1 : E → F) p.2) := begin have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous (λp : E × E, (fderiv 𝕜 f p.1, p.2)), { apply continuous.prod_mk _ continuous_snd, exact continuous.comp (h.continuous_fderiv hn) continuous_fst }, exact A.comp B end /-! ### Constants -/ lemma iterated_fderiv_within_zero_fun {n : ℕ} : iterated_fderiv 𝕜 n (λ x : E, (0 : F)) = 0 := begin induction n with n IH, { ext m, simp }, { ext x m, rw [iterated_fderiv_succ_apply_left, IH], change (fderiv 𝕜 (λ (x : E), (0 : (E [×n]→L[𝕜] F))) x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) = _, rw fderiv_const, refl } end lemma times_cont_diff_zero_fun {n : with_top ℕ} : times_cont_diff 𝕜 n (λ x : E, (0 : F)) := begin apply times_cont_diff_of_differentiable_iterated_fderiv (λm hm, _), rw iterated_fderiv_within_zero_fun, apply differentiable_const (0 : (E [×m]→L[𝕜] F)) end /-- Constants are `C^∞`. -/ lemma times_cont_diff_const {n : with_top ℕ} {c : F} : times_cont_diff 𝕜 n (λx : E, c) := begin suffices h : times_cont_diff 𝕜 ∞ (λx : E, c), by exact h.of_le le_top, rw times_cont_diff_top_iff_fderiv, refine ⟨differentiable_const c, _⟩, rw fderiv_const, exact times_cont_diff_zero_fun end lemma times_cont_diff_on_const {n : with_top ℕ} {c : F} {s : set E} : times_cont_diff_on 𝕜 n (λx : E, c) s := times_cont_diff_const.times_cont_diff_on lemma times_cont_diff_at_const {n : with_top ℕ} {c : F} : times_cont_diff_at 𝕜 n (λx : E, c) x := times_cont_diff_const.times_cont_diff_at lemma times_cont_diff_within_at_const {n : with_top ℕ} {c : F} : times_cont_diff_within_at 𝕜 n (λx : E, c) s x := times_cont_diff_at_const.times_cont_diff_within_at @[nontriviality] lemma times_cont_diff_of_subsingleton [subsingleton F] {n : with_top ℕ} : times_cont_diff 𝕜 n f := by { rw [subsingleton.elim f (λ _, 0)], exact times_cont_diff_const } @[nontriviality] lemma times_cont_diff_at_of_subsingleton [subsingleton F] {n : with_top ℕ} : times_cont_diff_at 𝕜 n f x := by { rw [subsingleton.elim f (λ _, 0)], exact times_cont_diff_at_const } @[nontriviality] lemma times_cont_diff_within_at_of_subsingleton [subsingleton F] {n : with_top ℕ} : times_cont_diff_within_at 𝕜 n f s x := by { rw [subsingleton.elim f (λ _, 0)], exact times_cont_diff_within_at_const } @[nontriviality] lemma times_cont_diff_on_of_subsingleton [subsingleton F] {n : with_top ℕ} : times_cont_diff_on 𝕜 n f s := by { rw [subsingleton.elim f (λ _, 0)], exact times_cont_diff_on_const } /-! ### Linear functions -/ /-- Unbundled bounded linear functions are `C^∞`. -/ lemma is_bounded_linear_map.times_cont_diff {n : with_top ℕ} (hf : is_bounded_linear_map 𝕜 f) : times_cont_diff 𝕜 n f := begin suffices h : times_cont_diff 𝕜 ∞ f, by exact h.of_le le_top, rw times_cont_diff_top_iff_fderiv, refine ⟨hf.differentiable, _⟩, simp [hf.fderiv], exact times_cont_diff_const end lemma continuous_linear_map.times_cont_diff {n : with_top ℕ} (f : E →L[𝕜] F) : times_cont_diff 𝕜 n f := f.is_bounded_linear_map.times_cont_diff lemma continuous_linear_equiv.times_cont_diff {n : with_top ℕ} (f : E ≃L[𝕜] F) : times_cont_diff 𝕜 n f := (f : E →L[𝕜] F).times_cont_diff lemma linear_isometry_map.times_cont_diff {n : with_top ℕ} (f : E →ₗᵢ[𝕜] F) : times_cont_diff 𝕜 n f := f.to_continuous_linear_map.times_cont_diff lemma linear_isometry_equiv.times_cont_diff {n : with_top ℕ} (f : E ≃ₗᵢ[𝕜] F) : times_cont_diff 𝕜 n f := (f : E →L[𝕜] F).times_cont_diff /-- The first projection in a product is `C^∞`. -/ lemma times_cont_diff_fst {n : with_top ℕ} : times_cont_diff 𝕜 n (prod.fst : E × F → E) := is_bounded_linear_map.times_cont_diff is_bounded_linear_map.fst /-- The first projection on a domain in a product is `C^∞`. -/ lemma times_cont_diff_on_fst {s : set (E×F)} {n : with_top ℕ} : times_cont_diff_on 𝕜 n (prod.fst : E × F → E) s := times_cont_diff.times_cont_diff_on times_cont_diff_fst /-- The first projection at a point in a product is `C^∞`. -/ lemma times_cont_diff_at_fst {p : E × F} {n : with_top ℕ} : times_cont_diff_at 𝕜 n (prod.fst : E × F → E) p := times_cont_diff_fst.times_cont_diff_at /-- The first projection within a domain at a point in a product is `C^∞`. -/ lemma times_cont_diff_within_at_fst {s : set (E × F)} {p : E × F} {n : with_top ℕ} : times_cont_diff_within_at 𝕜 n (prod.fst : E × F → E) s p := times_cont_diff_fst.times_cont_diff_within_at /-- The second projection in a product is `C^∞`. -/ lemma times_cont_diff_snd {n : with_top ℕ} : times_cont_diff 𝕜 n (prod.snd : E × F → F) := is_bounded_linear_map.times_cont_diff is_bounded_linear_map.snd /-- The second projection on a domain in a product is `C^∞`. -/ lemma times_cont_diff_on_snd {s : set (E×F)} {n : with_top ℕ} : times_cont_diff_on 𝕜 n (prod.snd : E × F → F) s := times_cont_diff.times_cont_diff_on times_cont_diff_snd /-- The second projection at a point in a product is `C^∞`. -/ lemma times_cont_diff_at_snd {p : E × F} {n : with_top ℕ} : times_cont_diff_at 𝕜 n (prod.snd : E × F → F) p := times_cont_diff_snd.times_cont_diff_at /-- The second projection within a domain at a point in a product is `C^∞`. -/ lemma times_cont_diff_within_at_snd {s : set (E × F)} {p : E × F} {n : with_top ℕ} : times_cont_diff_within_at 𝕜 n (prod.snd : E × F → F) s p := times_cont_diff_snd.times_cont_diff_within_at /-- The identity is `C^∞`. -/ lemma times_cont_diff_id {n : with_top ℕ} : times_cont_diff 𝕜 n (id : E → E) := is_bounded_linear_map.id.times_cont_diff lemma times_cont_diff_within_at_id {n : with_top ℕ} {s x} : times_cont_diff_within_at 𝕜 n (id : E → E) s x := times_cont_diff_id.times_cont_diff_within_at lemma times_cont_diff_at_id {n : with_top ℕ} {x} : times_cont_diff_at 𝕜 n (id : E → E) x := times_cont_diff_id.times_cont_diff_at lemma times_cont_diff_on_id {n : with_top ℕ} {s} : times_cont_diff_on 𝕜 n (id : E → E) s := times_cont_diff_id.times_cont_diff_on /-- Bilinear functions are `C^∞`. -/ lemma is_bounded_bilinear_map.times_cont_diff {n : with_top ℕ} (hb : is_bounded_bilinear_map 𝕜 b) : times_cont_diff 𝕜 n b := begin suffices h : times_cont_diff 𝕜 ∞ b, by exact h.of_le le_top, rw times_cont_diff_top_iff_fderiv, refine ⟨hb.differentiable, _⟩, simp [hb.fderiv], exact hb.is_bounded_linear_map_deriv.times_cont_diff end /-- If `f` admits a Taylor series `p` in a set `s`, and `g` is linear, then `g ∘ f` admits a Taylor series whose `k`-th term is given by `g ∘ (p k)`. -/ lemma has_ftaylor_series_up_to_on.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G) (hf : has_ftaylor_series_up_to_on n f p s) : has_ftaylor_series_up_to_on n (g ∘ f) (λ x k, g.comp_continuous_multilinear_map (p x k)) s := begin split, { assume x hx, simp [(hf.zero_eq x hx).symm] }, { assume m hm x hx, let A : (E [×m]→L[𝕜] F) → (E [×m]→L[𝕜] G) := λ f, g.comp_continuous_multilinear_map f, have hA : is_bounded_linear_map 𝕜 A := is_bounded_bilinear_map_comp_multilinear.is_bounded_linear_map_right _, have := hf.fderiv_within m hm x hx, convert has_fderiv_at.comp_has_fderiv_within_at x (hA.has_fderiv_at) this }, { assume m hm, let A : (E [×m]→L[𝕜] F) → (E [×m]→L[𝕜] G) := λ f, g.comp_continuous_multilinear_map f, have hA : is_bounded_linear_map 𝕜 A := is_bounded_bilinear_map_comp_multilinear.is_bounded_linear_map_right _, exact hA.continuous.comp_continuous_on (hf.cont m hm) } end /-- Composition by continuous linear maps on the left preserves `C^n` functions in a domain at a point. -/ lemma times_cont_diff_within_at.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G) (hf : times_cont_diff_within_at 𝕜 n f s x) : times_cont_diff_within_at 𝕜 n (g ∘ f) s x := begin assume m hm, rcases hf m hm with ⟨u, hu, p, hp⟩, exact ⟨u, hu, _, hp.continuous_linear_map_comp g⟩, end /-- Composition by continuous linear maps on the left preserves `C^n` functions in a domain at a point. -/ lemma times_cont_diff_at.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G) (hf : times_cont_diff_at 𝕜 n f x) : times_cont_diff_at 𝕜 n (g ∘ f) x := times_cont_diff_within_at.continuous_linear_map_comp g hf /-- Composition by continuous linear maps on the left preserves `C^n` functions on domains. -/ lemma times_cont_diff_on.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G) (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (g ∘ f) s := λ x hx, (hf x hx).continuous_linear_map_comp g /-- Composition by continuous linear maps on the left preserves `C^n` functions. -/ lemma times_cont_diff.continuous_linear_map_comp {n : with_top ℕ} {f : E → F} (g : F →L[𝕜] G) (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (λx, g (f x)) := times_cont_diff_on_univ.1 $ times_cont_diff_on.continuous_linear_map_comp _ (times_cont_diff_on_univ.2 hf) /-- Composition by continuous linear equivs on the left respects higher differentiability on domains. -/ lemma continuous_linear_equiv.comp_times_cont_diff_within_at_iff {n : with_top ℕ} (e : F ≃L[𝕜] G) : times_cont_diff_within_at 𝕜 n (e ∘ f) s x ↔ times_cont_diff_within_at 𝕜 n f s x := begin split, { assume H, have : f = e.symm ∘ (e ∘ f), by { ext y, simp only [function.comp_app], rw e.symm_apply_apply (f y) }, rw this, exact H.continuous_linear_map_comp _ }, { assume H, exact H.continuous_linear_map_comp _ } end /-- Composition by continuous linear equivs on the left respects higher differentiability on domains. -/ lemma continuous_linear_equiv.comp_times_cont_diff_on_iff {n : with_top ℕ} (e : F ≃L[𝕜] G) : times_cont_diff_on 𝕜 n (e ∘ f) s ↔ times_cont_diff_on 𝕜 n f s := by simp [times_cont_diff_on, e.comp_times_cont_diff_within_at_iff] /-- If `f` admits a Taylor series `p` in a set `s`, and `g` is linear, then `f ∘ g` admits a Taylor series in `g ⁻¹' s`, whose `k`-th term is given by `p k (g v₁, ..., g vₖ)` . -/ lemma has_ftaylor_series_up_to_on.comp_continuous_linear_map {n : with_top ℕ} (hf : has_ftaylor_series_up_to_on n f p s) (g : G →L[𝕜] E) : has_ftaylor_series_up_to_on n (f ∘ g) (λ x k, (p (g x) k).comp_continuous_linear_map (λ _, g)) (g ⁻¹' s) := begin let A : Π m : ℕ, (E [×m]→L[𝕜] F) → (G [×m]→L[𝕜] F) := λ m h, h.comp_continuous_linear_map (λ _, g), have hA : ∀ m, is_bounded_linear_map 𝕜 (A m) := λ m, is_bounded_linear_map_continuous_multilinear_map_comp_linear g, split, { assume x hx, simp only [(hf.zero_eq (g x) hx).symm, function.comp_app], change p (g x) 0 (λ (i : fin 0), g 0) = p (g x) 0 0, rw continuous_linear_map.map_zero, refl }, { assume m hm x hx, convert ((hA m).has_fderiv_at).comp_has_fderiv_within_at x ((hf.fderiv_within m hm (g x) hx).comp x (g.has_fderiv_within_at) (subset.refl _)), ext y v, change p (g x) (nat.succ m) (g ∘ (cons y v)) = p (g x) m.succ (cons (g y) (g ∘ v)), rw comp_cons }, { assume m hm, exact (hA m).continuous.comp_continuous_on ((hf.cont m hm).comp g.continuous.continuous_on (subset.refl _)) } end /-- Composition by continuous linear maps on the right preserves `C^n` functions at a point on a domain. -/ lemma times_cont_diff_within_at.comp_continuous_linear_map {n : with_top ℕ} {x : G} (g : G →L[𝕜] E) (hf : times_cont_diff_within_at 𝕜 n f s (g x)) : times_cont_diff_within_at 𝕜 n (f ∘ g) (g ⁻¹' s) x := begin assume m hm, rcases hf m hm with ⟨u, hu, p, hp⟩, refine ⟨g ⁻¹' u, _, _, hp.comp_continuous_linear_map g⟩, apply continuous_within_at.preimage_mem_nhds_within', { exact g.continuous.continuous_within_at }, { apply nhds_within_mono (g x) _ hu, rw image_insert_eq, exact insert_subset_insert (image_preimage_subset g s) } end /-- Composition by continuous linear maps on the right preserves `C^n` functions on domains. -/ lemma times_cont_diff_on.comp_continuous_linear_map {n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (g : G →L[𝕜] E) : times_cont_diff_on 𝕜 n (f ∘ g) (g ⁻¹' s) := λ x hx, (hf (g x) hx).comp_continuous_linear_map g /-- Composition by continuous linear maps on the right preserves `C^n` functions. -/ lemma times_cont_diff.comp_continuous_linear_map {n : with_top ℕ} {f : E → F} {g : G →L[𝕜] E} (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (f ∘ g) := times_cont_diff_on_univ.1 $ times_cont_diff_on.comp_continuous_linear_map (times_cont_diff_on_univ.2 hf) _ /-- Composition by continuous linear equivs on the right respects higher differentiability at a point in a domain. -/ lemma continuous_linear_equiv.times_cont_diff_within_at_comp_iff {n : with_top ℕ} (e : G ≃L[𝕜] E) : times_cont_diff_within_at 𝕜 n (f ∘ e) (e ⁻¹' s) (e.symm x) ↔ times_cont_diff_within_at 𝕜 n f s x := begin split, { assume H, have A : f = (f ∘ e) ∘ e.symm, by { ext y, simp only [function.comp_app], rw e.apply_symm_apply y }, have B : e.symm ⁻¹' (e ⁻¹' s) = s, by { rw [← preimage_comp, e.self_comp_symm], refl }, rw [A, ← B], exact H.comp_continuous_linear_map _}, { assume H, have : x = e (e.symm x), by simp, rw this at H, exact H.comp_continuous_linear_map _ }, end /-- Composition by continuous linear equivs on the right respects higher differentiability on domains. -/ lemma continuous_linear_equiv.times_cont_diff_on_comp_iff {n : with_top ℕ} (e : G ≃L[𝕜] E) : times_cont_diff_on 𝕜 n (f ∘ e) (e ⁻¹' s) ↔ times_cont_diff_on 𝕜 n f s := begin refine ⟨λ H, _, λ H, H.comp_continuous_linear_map _⟩, have A : f = (f ∘ e) ∘ e.symm, by { ext y, simp only [function.comp_app], rw e.apply_symm_apply y }, have B : e.symm ⁻¹' (e ⁻¹' s) = s, by { rw [← preimage_comp, e.self_comp_symm], refl }, rw [A, ← B], exact H.comp_continuous_linear_map _ end /-- If two functions `f` and `g` admit Taylor series `p` and `q` in a set `s`, then the cartesian product of `f` and `g` admits the cartesian product of `p` and `q` as a Taylor series. -/ lemma has_ftaylor_series_up_to_on.prod {n : with_top ℕ} (hf : has_ftaylor_series_up_to_on n f p s) {g : E → G} {q : E → formal_multilinear_series 𝕜 E G} (hg : has_ftaylor_series_up_to_on n g q s) : has_ftaylor_series_up_to_on n (λ y, (f y, g y)) (λ y k, (p y k).prod (q y k)) s := begin split, { assume x hx, rw [← hf.zero_eq x hx, ← hg.zero_eq x hx], refl }, { assume m hm x hx, let A : (E [×m]→L[𝕜] F) × (E [×m]→L[𝕜] G) → (E [×m]→L[𝕜] (F × G)) := λ p, p.1.prod p.2, have hA : is_bounded_linear_map 𝕜 A := is_bounded_linear_map_prod_multilinear, convert hA.has_fderiv_at.comp_has_fderiv_within_at x ((hf.fderiv_within m hm x hx).prod (hg.fderiv_within m hm x hx)) }, { assume m hm, let A : (E [×m]→L[𝕜] F) × (E [×m]→L[𝕜] G) → (E [×m]→L[𝕜] (F × G)) := λ p, p.1.prod p.2, have hA : is_bounded_linear_map 𝕜 A := is_bounded_linear_map_prod_multilinear, exact hA.continuous.comp_continuous_on ((hf.cont m hm).prod (hg.cont m hm)) } end /-- The cartesian product of `C^n` functions at a point in a domain is `C^n`. -/ lemma times_cont_diff_within_at.prod {n : with_top ℕ} {s : set E} {f : E → F} {g : E → G} (hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) : times_cont_diff_within_at 𝕜 n (λx:E, (f x, g x)) s x := begin assume m hm, rcases hf m hm with ⟨u, hu, p, hp⟩, rcases hg m hm with ⟨v, hv, q, hq⟩, exact ⟨u ∩ v, filter.inter_mem_sets hu hv, _, (hp.mono (inter_subset_left u v)).prod (hq.mono (inter_subset_right u v))⟩ end /-- The cartesian product of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.prod {n : with_top ℕ} {s : set E} {f : E → F} {g : E → G} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λx:E, (f x, g x)) s := λ x hx, (hf x hx).prod (hg x hx) /-- The cartesian product of `C^n` functions at a point is `C^n`. -/ lemma times_cont_diff_at.prod {n : with_top ℕ} {f : E → F} {g : E → G} (hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) : times_cont_diff_at 𝕜 n (λx:E, (f x, g x)) x := times_cont_diff_within_at_univ.1 $ times_cont_diff_within_at.prod (times_cont_diff_within_at_univ.2 hf) (times_cont_diff_within_at_univ.2 hg) /-- The cartesian product of `C^n` functions is `C^n`. -/ lemma times_cont_diff.prod {n : with_top ℕ} {f : E → F} {g : E → G} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx:E, (f x, g x)) := times_cont_diff_on_univ.1 $ times_cont_diff_on.prod (times_cont_diff_on_univ.2 hf) (times_cont_diff_on_univ.2 hg) /-! ### Composition of `C^n` functions We show that the composition of `C^n` functions is `C^n`. One way to prove it would be to write the `n`-th derivative of the composition (this is Faà di Bruno's formula) and check its continuity, but this is very painful. Instead, we go for a simple inductive proof. Assume it is done for `n`. Then, to check it for `n+1`, one needs to check that the derivative of `g ∘ f` is `C^n`, i.e., that `Dg(f x) ⬝ Df(x)` is `C^n`. The term `Dg (f x)` is the composition of two `C^n` functions, so it is `C^n` by the inductive assumption. The term `Df(x)` is also `C^n`. Then, the matrix multiplication is the application of a bilinear map (which is `C^∞`, and therefore `C^n`) to `x ↦ (Dg(f x), Df x)`. As the composition of two `C^n` maps, it is again `C^n`, and we are done. There is a subtlety in this argument: we apply the inductive assumption to functions on other Banach spaces. In maths, one would say: prove by induction over `n` that, for all `C^n` maps between all pairs of Banach spaces, their composition is `C^n`. In Lean, this is fine as long as the spaces stay in the same universe. This is not the case in the above argument: if `E` lives in universe `u` and `F` lives in universe `v`, then linear maps from `E` to `F` (to which the derivative of `f` belongs) is in universe `max u v`. If one could quantify over finitely many universes, the above proof would work fine, but this is not the case. One could still write the proof considering spaces in any universe in `u, v, w, max u v, max v w, max u v w`, but it would be extremely tedious and lead to a lot of duplication. Instead, we formulate the above proof when all spaces live in the same universe (where everything is fine), and then we deduce the general result by lifting all our spaces to a common universe. We use the trick that any space `H` is isomorphic through a continuous linear equiv to `continuous_multilinear_map (λ (i : fin 0), E × F × G) H` to change the universe level, and then argue that composing with such a linear equiv does not change the fact of being `C^n`, which we have already proved previously. -/ /-- Auxiliary lemma proving that the composition of `C^n` functions on domains is `C^n` when all spaces live in the same universe. Use instead `times_cont_diff_on.comp` which removes the universe assumption (but is deduced from this one). -/ private lemma times_cont_diff_on.comp_same_univ {Eu : Type u} [normed_group Eu] [normed_space 𝕜 Eu] {Fu : Type u} [normed_group Fu] [normed_space 𝕜 Fu] {Gu : Type u} [normed_group Gu] [normed_space 𝕜 Gu] {n : with_top ℕ} {s : set Eu} {t : set Fu} {g : Fu → Gu} {f : Eu → Fu} (hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) (st : s ⊆ f ⁻¹' t) : times_cont_diff_on 𝕜 n (g ∘ f) s := begin unfreezingI { induction n using with_top.nat_induction with n IH Itop generalizing Eu Fu Gu }, { rw times_cont_diff_on_zero at hf hg ⊢, exact continuous_on.comp hg hf st }, { rw times_cont_diff_on_succ_iff_has_fderiv_within_at at hg ⊢, assume x hx, rcases (times_cont_diff_on_succ_iff_has_fderiv_within_at.1 hf) x hx with ⟨u, hu, f', hf', f'_diff⟩, rcases hg (f x) (st hx) with ⟨v, hv, g', hg', g'_diff⟩, rw insert_eq_of_mem hx at hu ⊢, have xu : x ∈ u := mem_of_mem_nhds_within hx hu, let w := s ∩ (u ∩ f⁻¹' v), have wv : w ⊆ f ⁻¹' v := λ y hy, hy.2.2, have wu : w ⊆ u := λ y hy, hy.2.1, have ws : w ⊆ s := λ y hy, hy.1, refine ⟨w, _, λ y, (g' (f y)).comp (f' y), _, _⟩, show w ∈ 𝓝[s] x, { apply filter.inter_mem_sets self_mem_nhds_within, apply filter.inter_mem_sets hu, apply continuous_within_at.preimage_mem_nhds_within', { rw ← continuous_within_at_inter' hu, exact (hf' x xu).differentiable_within_at.continuous_within_at.mono (inter_subset_right _ _) }, { apply nhds_within_mono _ _ hv, exact subset.trans (image_subset_iff.mpr st) (subset_insert (f x) t) } }, show ∀ y ∈ w, has_fderiv_within_at (g ∘ f) ((g' (f y)).comp (f' y)) w y, { rintros y ⟨ys, yu, yv⟩, exact (hg' (f y) yv).comp y ((hf' y yu).mono wu) wv }, show times_cont_diff_on 𝕜 n (λ y, (g' (f y)).comp (f' y)) w, { have A : times_cont_diff_on 𝕜 n (λ y, g' (f y)) w := IH g'_diff ((hf.of_le (with_top.coe_le_coe.2 (nat.le_succ n))).mono ws) wv, have B : times_cont_diff_on 𝕜 n f' w := f'_diff.mono wu, have C : times_cont_diff_on 𝕜 n (λ y, (f' y, g' (f y))) w := times_cont_diff_on.prod B A, have D : times_cont_diff_on 𝕜 n (λ(p : (Eu →L[𝕜] Fu) × (Fu →L[𝕜] Gu)), p.2.comp p.1) univ := is_bounded_bilinear_map_comp.times_cont_diff.times_cont_diff_on, exact IH D C (subset_univ _) } }, { rw times_cont_diff_on_top at hf hg ⊢, assume n, apply Itop n (hg n) (hf n) st } end /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.comp {n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) (st : s ⊆ f ⁻¹' t) : times_cont_diff_on 𝕜 n (g ∘ f) s := begin /- we lift all the spaces to a common universe, as we have already proved the result in this situation. For the lift, we use the trick that `H` is isomorphic through a continuous linear equiv to `continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) H`, and continuous linear equivs respect smoothness classes. -/ let Eu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) E, letI : normed_group Eu := by apply_instance, letI : normed_space 𝕜 Eu := by apply_instance, let Fu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) F, letI : normed_group Fu := by apply_instance, letI : normed_space 𝕜 Fu := by apply_instance, let Gu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) G, letI : normed_group Gu := by apply_instance, letI : normed_space 𝕜 Gu := by apply_instance, -- declare the isomorphisms let isoE : Eu ≃L[𝕜] E := continuous_multilinear_curry_fin0 𝕜 (E × F × G) E, let isoF : Fu ≃L[𝕜] F := continuous_multilinear_curry_fin0 𝕜 (E × F × G) F, let isoG : Gu ≃L[𝕜] G := continuous_multilinear_curry_fin0 𝕜 (E × F × G) G, -- lift the functions to the new spaces, check smoothness there, and then go back. let fu : Eu → Fu := (isoF.symm ∘ f) ∘ isoE, have fu_diff : times_cont_diff_on 𝕜 n fu (isoE ⁻¹' s), by rwa [isoE.times_cont_diff_on_comp_iff, isoF.symm.comp_times_cont_diff_on_iff], let gu : Fu → Gu := (isoG.symm ∘ g) ∘ isoF, have gu_diff : times_cont_diff_on 𝕜 n gu (isoF ⁻¹' t), by rwa [isoF.times_cont_diff_on_comp_iff, isoG.symm.comp_times_cont_diff_on_iff], have main : times_cont_diff_on 𝕜 n (gu ∘ fu) (isoE ⁻¹' s), { apply times_cont_diff_on.comp_same_univ gu_diff fu_diff, assume y hy, simp only [fu, continuous_linear_equiv.coe_apply, function.comp_app, mem_preimage], rw isoF.apply_symm_apply (f (isoE y)), exact st hy }, have : gu ∘ fu = (isoG.symm ∘ (g ∘ f)) ∘ isoE, { ext y, simp only [function.comp_apply, gu, fu], rw isoF.apply_symm_apply (f (isoE y)) }, rwa [this, isoE.times_cont_diff_on_comp_iff, isoG.symm.comp_times_cont_diff_on_iff] at main end /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.comp' {n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (g ∘ f) (s ∩ f⁻¹' t) := hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) /-- The composition of a `C^n` function on a domain with a `C^n` function is `C^n`. -/ lemma times_cont_diff.comp_times_cont_diff_on {n : with_top ℕ} {s : set E} {g : F → G} {f : E → F} (hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (g ∘ f) s := (times_cont_diff_on_univ.2 hg).comp hf subset_preimage_univ /-- The composition of `C^n` functions is `C^n`. -/ lemma times_cont_diff.comp {n : with_top ℕ} {g : F → G} {f : E → F} (hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (g ∘ f) := times_cont_diff_on_univ.1 $ times_cont_diff_on.comp (times_cont_diff_on_univ.2 hg) (times_cont_diff_on_univ.2 hf) (subset_univ _) /-- The composition of `C^n` functions at points in domains is `C^n`. -/ lemma times_cont_diff_within_at.comp {n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (x : E) (hg : times_cont_diff_within_at 𝕜 n g t (f x)) (hf : times_cont_diff_within_at 𝕜 n f s x) (st : s ⊆ f ⁻¹' t) : times_cont_diff_within_at 𝕜 n (g ∘ f) s x := begin assume m hm, rcases hg.times_cont_diff_on hm with ⟨u, u_nhd, ut, hu⟩, rcases hf.times_cont_diff_on hm with ⟨v, v_nhd, vs, hv⟩, have xmem : x ∈ f ⁻¹' u ∩ v := ⟨(mem_of_mem_nhds_within (mem_insert (f x) _) u_nhd : _), mem_of_mem_nhds_within (mem_insert x s) v_nhd⟩, have : f ⁻¹' u ∈ 𝓝[insert x s] x, { apply hf.continuous_within_at.insert_self.preimage_mem_nhds_within', apply nhds_within_mono _ _ u_nhd, rw image_insert_eq, exact insert_subset_insert (image_subset_iff.mpr st) }, have Z := ((hu.comp (hv.mono (inter_subset_right (f ⁻¹' u) v)) (inter_subset_left _ _)) .times_cont_diff_within_at) xmem m (le_refl _), have : 𝓝[f ⁻¹' u ∩ v] x = 𝓝[insert x s] x, { have A : f ⁻¹' u ∩ v = (insert x s) ∩ (f ⁻¹' u ∩ v), { apply subset.antisymm _ (inter_subset_right _ _), rintros y ⟨hy1, hy2⟩, simp [hy1, hy2, vs hy2] }, rw [A, ← nhds_within_restrict''], exact filter.inter_mem_sets this v_nhd }, rwa [insert_eq_of_mem xmem, this] at Z, end /-- The composition of `C^n` functions at points in domains is `C^n`. -/ lemma times_cont_diff_within_at.comp' {n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (x : E) (hg : times_cont_diff_within_at 𝕜 n g t (f x)) (hf : times_cont_diff_within_at 𝕜 n f s x) : times_cont_diff_within_at 𝕜 n (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma times_cont_diff_at.comp_times_cont_diff_within_at {n} (x : E) (hg : times_cont_diff_at 𝕜 n g (f x)) (hf : times_cont_diff_within_at 𝕜 n f s x) : times_cont_diff_within_at 𝕜 n (g ∘ f) s x := hg.comp x hf (maps_to_univ _ _) /-- The composition of `C^n` functions at points is `C^n`. -/ lemma times_cont_diff_at.comp {n : with_top ℕ} (x : E) (hg : times_cont_diff_at 𝕜 n g (f x)) (hf : times_cont_diff_at 𝕜 n f x) : times_cont_diff_at 𝕜 n (g ∘ f) x := hg.comp x hf subset_preimage_univ lemma times_cont_diff.comp_times_cont_diff_within_at {n : with_top ℕ} {g : F → G} {f : E → F} (h : times_cont_diff 𝕜 n g) (hf : times_cont_diff_within_at 𝕜 n f t x) : times_cont_diff_within_at 𝕜 n (g ∘ f) t x := begin have : times_cont_diff_within_at 𝕜 n g univ (f x) := h.times_cont_diff_at.times_cont_diff_within_at, exact this.comp x hf (subset_univ _), end lemma times_cont_diff.comp_times_cont_diff_at {n : with_top ℕ} {g : F → G} {f : E → F} (x : E) (hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff_at 𝕜 n f x) : times_cont_diff_at 𝕜 n (g ∘ f) x := hg.comp_times_cont_diff_within_at hf /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma times_cont_diff_on_fderiv_within_apply {m n : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (λp : E × E, (fderiv_within 𝕜 f s p.1 : E →L[𝕜] F) p.2) (set.prod s (univ : set E)) := begin have A : times_cont_diff 𝕜 m (λp : (E →L[𝕜] F) × E, p.1 p.2), { apply is_bounded_bilinear_map.times_cont_diff, exact is_bounded_bilinear_map_apply }, have B : times_cont_diff_on 𝕜 m (λ (p : E × E), ((fderiv_within 𝕜 f s p.fst), p.snd)) (set.prod s univ), { apply times_cont_diff_on.prod _ _, { have I : times_cont_diff_on 𝕜 m (λ (x : E), fderiv_within 𝕜 f s x) s := hf.fderiv_within hs hmn, have J : times_cont_diff_on 𝕜 m (λ (x : E × E), x.1) (set.prod s univ) := times_cont_diff_fst.times_cont_diff_on, exact times_cont_diff_on.comp I J (prod_subset_preimage_fst _ _) }, { apply times_cont_diff.times_cont_diff_on _ , apply is_bounded_linear_map.snd.times_cont_diff } }, exact A.comp_times_cont_diff_on B end /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma times_cont_diff.times_cont_diff_fderiv_apply {n m : with_top ℕ} {f : E → F} (hf : times_cont_diff 𝕜 n f) (hmn : m + 1 ≤ n) : times_cont_diff 𝕜 m (λp : E × E, (fderiv 𝕜 f p.1 : E →L[𝕜] F) p.2) := begin rw ← times_cont_diff_on_univ at ⊢ hf, rw [← fderiv_within_univ, ← univ_prod_univ], exact times_cont_diff_on_fderiv_within_apply hf unique_diff_on_univ hmn end /-! ### Sum of two functions -/ /- The sum is smooth. -/ lemma times_cont_diff_add {n : with_top ℕ} : times_cont_diff 𝕜 n (λp : F × F, p.1 + p.2) := (is_bounded_linear_map.fst.add is_bounded_linear_map.snd).times_cont_diff /-- The sum of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma times_cont_diff_within_at.add {n : with_top ℕ} {s : set E} {f g : E → F} (hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) : times_cont_diff_within_at 𝕜 n (λx, f x + g x) s x := times_cont_diff_add.times_cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ /-- The sum of two `C^n` functions at a point is `C^n` at this point. -/ lemma times_cont_diff_at.add {n : with_top ℕ} {f g : E → F} (hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) : times_cont_diff_at 𝕜 n (λx, f x + g x) x := by rw [← times_cont_diff_within_at_univ] at *; exact hf.add hg /-- The sum of two `C^n`functions is `C^n`. -/ lemma times_cont_diff.add {n : with_top ℕ} {f g : E → F} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx, f x + g x) := times_cont_diff_add.comp (hf.prod hg) /-- The sum of two `C^n` functions on a domain is `C^n`. -/ lemma times_cont_diff_on.add {n : with_top ℕ} {s : set E} {f g : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λx, f x + g x) s := λ x hx, (hf x hx).add (hg x hx) /-! ### Negative -/ /- The negative is smooth. -/ lemma times_cont_diff_neg {n : with_top ℕ} : times_cont_diff 𝕜 n (λp : F, -p) := is_bounded_linear_map.id.neg.times_cont_diff /-- The negative of a `C^n` function within a domain at a point is `C^n` within this domain at this point. -/ lemma times_cont_diff_within_at.neg {n : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff_within_at 𝕜 n f s x) : times_cont_diff_within_at 𝕜 n (λx, -f x) s x := times_cont_diff_neg.times_cont_diff_within_at.comp x hf subset_preimage_univ /-- The negative of a `C^n` function at a point is `C^n` at this point. -/ lemma times_cont_diff_at.neg {n : with_top ℕ} {f : E → F} (hf : times_cont_diff_at 𝕜 n f x) : times_cont_diff_at 𝕜 n (λx, -f x) x := by rw ← times_cont_diff_within_at_univ at *; exact hf.neg /-- The negative of a `C^n`function is `C^n`. -/ lemma times_cont_diff.neg {n : with_top ℕ} {f : E → F} (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (λx, -f x) := times_cont_diff_neg.comp hf /-- The negative of a `C^n` function on a domain is `C^n`. -/ lemma times_cont_diff_on.neg {n : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (λx, -f x) s := λ x hx, (hf x hx).neg /-! ### Subtraction -/ /-- The difference of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma times_cont_diff_within_at.sub {n : with_top ℕ} {s : set E} {f g : E → F} (hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) : times_cont_diff_within_at 𝕜 n (λx, f x - g x) s x := by simpa only [sub_eq_add_neg] using hf.add hg.neg /-- The difference of two `C^n` functions at a point is `C^n` at this point. -/ lemma times_cont_diff_at.sub {n : with_top ℕ} {f g : E → F} (hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) : times_cont_diff_at 𝕜 n (λx, f x - g x) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg /-- The difference of two `C^n` functions on a domain is `C^n`. -/ lemma times_cont_diff_on.sub {n : with_top ℕ} {s : set E} {f g : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λx, f x - g x) s := by simpa only [sub_eq_add_neg] using hf.add hg.neg /-- The difference of two `C^n` functions is `C^n`. -/ lemma times_cont_diff.sub {n : with_top ℕ} {f g : E → F} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx, f x - g x) := by simpa only [sub_eq_add_neg] using hf.add hg.neg /-! ### Sum of finitely many functions -/ lemma times_cont_diff_within_at.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ} {t : set E} {x : E} (h : ∀ i ∈ s, times_cont_diff_within_at 𝕜 n (λ x, f i x) t x) : times_cont_diff_within_at 𝕜 n (λ x, (∑ i in s, f i x)) t x := begin classical, induction s using finset.induction_on with i s is IH, { simp [times_cont_diff_within_at_const] }, { simp only [is, finset.sum_insert, not_false_iff], exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) } end lemma times_cont_diff_at.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ} {x : E} (h : ∀ i ∈ s, times_cont_diff_at 𝕜 n (λ x, f i x) x) : times_cont_diff_at 𝕜 n (λ x, (∑ i in s, f i x)) x := by rw [← times_cont_diff_within_at_univ] at *; exact times_cont_diff_within_at.sum h lemma times_cont_diff_on.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ} {t : set E} (h : ∀ i ∈ s, times_cont_diff_on 𝕜 n (λ x, f i x) t) : times_cont_diff_on 𝕜 n (λ x, (∑ i in s, f i x)) t := λ x hx, times_cont_diff_within_at.sum (λ i hi, h i hi x hx) lemma times_cont_diff.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ} (h : ∀ i ∈ s, times_cont_diff 𝕜 n (λ x, f i x)) : times_cont_diff 𝕜 n (λ x, (∑ i in s, f i x)) := by simp [← times_cont_diff_on_univ] at *; exact times_cont_diff_on.sum h /-! ### Product of two functions -/ /- The product is smooth. -/ lemma times_cont_diff_mul {n : with_top ℕ} : times_cont_diff 𝕜 n (λ p : 𝕜 × 𝕜, p.1 * p.2) := is_bounded_bilinear_map_mul.times_cont_diff /-- The product of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma times_cont_diff_within_at.mul {n : with_top ℕ} {s : set E} {f g : E → 𝕜} (hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) : times_cont_diff_within_at 𝕜 n (λ x, f x * g x) s x := times_cont_diff_mul.times_cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ /-- The product of two `C^n` functions at a point is `C^n` at this point. -/ lemma times_cont_diff_at.mul {n : with_top ℕ} {f g : E → 𝕜} (hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) : times_cont_diff_at 𝕜 n (λ x, f x * g x) x := by rw [← times_cont_diff_within_at_univ] at *; exact hf.mul hg /-- The product of two `C^n` functions on a domain is `C^n`. -/ lemma times_cont_diff_on.mul {n : with_top ℕ} {s : set E} {f g : E → 𝕜} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λ x, f x * g x) s := λ x hx, (hf x hx).mul (hg x hx) /-- The product of two `C^n`functions is `C^n`. -/ lemma times_cont_diff.mul {n : with_top ℕ} {f g : E → 𝕜} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λ x, f x * g x) := times_cont_diff_mul.comp (hf.prod hg) lemma times_cont_diff_within_at.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : times_cont_diff_within_at 𝕜 n f s x) : times_cont_diff_within_at 𝕜 n (λ x, f x / c) s x := hf.mul times_cont_diff_within_at_const lemma times_cont_diff_at.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : times_cont_diff_at 𝕜 n f x) : times_cont_diff_at 𝕜 n (λ x, f x / c) x := hf.mul times_cont_diff_at_const lemma times_cont_diff_on.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (λ x, f x / c) s := hf.mul times_cont_diff_on_const lemma times_cont_diff.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (λ x, f x / c) := hf.mul times_cont_diff_const lemma times_cont_diff.pow {n : with_top ℕ} {f : E → 𝕜} (hf : times_cont_diff 𝕜 n f) : ∀ m : ℕ, times_cont_diff 𝕜 n (λ x, (f x) ^ m) | 0 := by simpa using times_cont_diff_const | (m + 1) := hf.mul (times_cont_diff.pow m) lemma times_cont_diff_at.pow {n : with_top ℕ} {f : E → 𝕜} (hf : times_cont_diff_at 𝕜 n f x) (m : ℕ) : times_cont_diff_at 𝕜 n (λ y, f y ^ m) x := (times_cont_diff_id.pow m).times_cont_diff_at.comp x hf lemma times_cont_diff_within_at.pow {n : with_top ℕ} {f : E → 𝕜} (hf : times_cont_diff_within_at 𝕜 n f s x) (m : ℕ) : times_cont_diff_within_at 𝕜 n (λ y, f y ^ m) s x := (times_cont_diff_id.pow m).times_cont_diff_at.comp_times_cont_diff_within_at x hf lemma times_cont_diff_on.pow {n : with_top ℕ} {f : E → 𝕜} (hf : times_cont_diff_on 𝕜 n f s) (m : ℕ) : times_cont_diff_on 𝕜 n (λ y, f y ^ m) s := λ y hy, (hf y hy).pow m /-! ### Scalar multiplication -/ /- The scalar multiplication is smooth. -/ lemma times_cont_diff_smul {n : with_top ℕ} : times_cont_diff 𝕜 n (λ p : 𝕜 × F, p.1 • p.2) := is_bounded_bilinear_map_smul.times_cont_diff /-- The scalar multiplication of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma times_cont_diff_within_at.smul {n : with_top ℕ} {s : set E} {f : E → 𝕜} {g : E → F} (hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) : times_cont_diff_within_at 𝕜 n (λ x, f x • g x) s x := times_cont_diff_smul.times_cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ /-- The scalar multiplication of two `C^n` functions at a point is `C^n` at this point. -/ lemma times_cont_diff_at.smul {n : with_top ℕ} {f : E → 𝕜} {g : E → F} (hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) : times_cont_diff_at 𝕜 n (λ x, f x • g x) x := by rw [← times_cont_diff_within_at_univ] at *; exact hf.smul hg /-- The scalar multiplication of two `C^n` functions is `C^n`. -/ lemma times_cont_diff.smul {n : with_top ℕ} {f : E → 𝕜} {g : E → F} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λ x, f x • g x) := times_cont_diff_smul.comp (hf.prod hg) /-- The scalar multiplication of two `C^n` functions on a domain is `C^n`. -/ lemma times_cont_diff_on.smul {n : with_top ℕ} {s : set E} {f : E → 𝕜} {g : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λ x, f x • g x) s := λ x hx, (hf x hx).smul (hg x hx) /-! ### Cartesian product of two functions-/ section prod_map variables {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] {n : with_top ℕ} /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma times_cont_diff_within_at.prod_map' {s : set E} {t : set E'} {f : E → F} {g : E' → F'} {p : E × E'} (hf : times_cont_diff_within_at 𝕜 n f s p.1) (hg : times_cont_diff_within_at 𝕜 n g t p.2) : times_cont_diff_within_at 𝕜 n (prod.map f g) (set.prod s t) p := (hf.comp p times_cont_diff_within_at_fst (prod_subset_preimage_fst _ _)).prod (hg.comp p times_cont_diff_within_at_snd (prod_subset_preimage_snd _ _)) lemma times_cont_diff_within_at.prod_map {s : set E} {t : set E'} {f : E → F} {g : E' → F'} {x : E} {y : E'} (hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g t y) : times_cont_diff_within_at 𝕜 n (prod.map f g) (set.prod s t) (x, y) := times_cont_diff_within_at.prod_map' hf hg /-- The product map of two `C^n` functions on a set is `C^n` on the product set. -/ lemma times_cont_diff_on.prod_map {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] {s : set E} {t : set E'} {n : with_top ℕ} {f : E → F} {g : E' → F'} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g t) : times_cont_diff_on 𝕜 n (prod.map f g) (set.prod s t) := (hf.comp times_cont_diff_on_fst (prod_subset_preimage_fst _ _)).prod (hg.comp (times_cont_diff_on_snd) (prod_subset_preimage_snd _ _)) /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma times_cont_diff_at.prod_map {f : E → F} {g : E' → F'} {x : E} {y : E'} (hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g y) : times_cont_diff_at 𝕜 n (prod.map f g) (x, y) := begin rw times_cont_diff_at at *, convert hf.prod_map hg, simp only [univ_prod_univ] end /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma times_cont_diff_at.prod_map' {f : E → F} {g : E' → F'} {p : E × E'} (hf : times_cont_diff_at 𝕜 n f p.1) (hg : times_cont_diff_at 𝕜 n g p.2) : times_cont_diff_at 𝕜 n (prod.map f g) p := begin rcases p, exact times_cont_diff_at.prod_map hf hg end /-- The product map of two `C^n` functions is `C^n`. -/ lemma times_cont_diff.prod_map {f : E → F} {g : E' → F'} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (prod.map f g) := begin rw times_cont_diff_iff_times_cont_diff_at at *, exact λ ⟨x, y⟩, (hf x).prod_map (hg y) end end prod_map /-! ### Inversion in a complete normed algebra -/ section algebra_inverse variables (𝕜) {R : Type*} [normed_ring R] [normed_algebra 𝕜 R] open normed_ring continuous_linear_map ring /-- In a complete normed algebra, the operation of inversion is `C^n`, for all `n`, at each invertible element. The proof is by induction, bootstrapping using an identity expressing the derivative of inversion as a bilinear map of inversion itself. -/ lemma times_cont_diff_at_ring_inverse [complete_space R] {n : with_top ℕ} (x : units R) : times_cont_diff_at 𝕜 n ring.inverse (x : R) := begin induction n using with_top.nat_induction with n IH Itop, { intros m hm, refine ⟨{y : R | is_unit y}, _, _⟩, { simp [nhds_within_univ], exact x.nhds }, { use (ftaylor_series_within 𝕜 inverse univ), rw [le_antisymm hm bot_le, has_ftaylor_series_up_to_on_zero_iff], split, { rintros _ ⟨x', rfl⟩, exact (inverse_continuous_at x').continuous_within_at }, { simp [ftaylor_series_within] } } }, { apply times_cont_diff_at_succ_iff_has_fderiv_at.mpr, refine ⟨λ (x : R), - lmul_left_right 𝕜 R (inverse x) (inverse x), _, _⟩, { refine ⟨{y : R | is_unit y}, x.nhds, _⟩, rintros _ ⟨y, rfl⟩, rw [inverse_unit], exact has_fderiv_at_ring_inverse y }, { convert (lmul_left_right_is_bounded_bilinear 𝕜 R).times_cont_diff.neg.comp_times_cont_diff_at (x : R) (IH.prod IH) } }, { exact times_cont_diff_at_top.mpr Itop } end variables (𝕜) {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [complete_space 𝕜'] lemma times_cont_diff_at_inv {x : 𝕜'} (hx : x ≠ 0) {n} : times_cont_diff_at 𝕜 n has_inv.inv x := by simpa only [inverse_eq_has_inv] using times_cont_diff_at_ring_inverse 𝕜 (units.mk0 x hx) lemma times_cont_diff_on_inv {n} : times_cont_diff_on 𝕜 n (has_inv.inv : 𝕜' → 𝕜') {0}ᶜ := λ x hx, (times_cont_diff_at_inv 𝕜 hx).times_cont_diff_within_at variable {𝕜} -- TODO: the next few lemmas don't need `𝕜` or `𝕜'` to be complete -- A good way to show this is to generalize `times_cont_diff_at_ring_inverse` to the setting -- of a function `f` such that `∀ᶠ x in 𝓝 a, x * f x = 1`. lemma times_cont_diff_within_at.inv {f : E → 𝕜'} {n} (hf : times_cont_diff_within_at 𝕜 n f s x) (hx : f x ≠ 0) : times_cont_diff_within_at 𝕜 n (λ x, (f x)⁻¹) s x := (times_cont_diff_at_inv 𝕜 hx).comp_times_cont_diff_within_at x hf lemma times_cont_diff_on.inv {f : E → 𝕜'} {n} (hf : times_cont_diff_on 𝕜 n f s) (h : ∀ x ∈ s, f x ≠ 0) : times_cont_diff_on 𝕜 n (λ x, (f x)⁻¹) s := λ x hx, (hf.times_cont_diff_within_at hx).inv (h x hx) lemma times_cont_diff_at.inv {f : E → 𝕜'} {n} (hf : times_cont_diff_at 𝕜 n f x) (hx : f x ≠ 0) : times_cont_diff_at 𝕜 n (λ x, (f x)⁻¹) x := hf.inv hx lemma times_cont_diff.inv {f : E → 𝕜'} {n} (hf : times_cont_diff 𝕜 n f) (h : ∀ x, f x ≠ 0) : times_cont_diff 𝕜 n (λ x, (f x)⁻¹) := by { rw times_cont_diff_iff_times_cont_diff_at, exact λ x, hf.times_cont_diff_at.inv (h x) } -- TODO: generalize to `f g : E → 𝕜'` lemma times_cont_diff_within_at.div [complete_space 𝕜] {f g : E → 𝕜} {n} (hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) (hx : g x ≠ 0) : times_cont_diff_within_at 𝕜 n (λ x, f x / g x) s x := hf.mul (hg.inv hx) lemma times_cont_diff_on.div [complete_space 𝕜] {f g : E → 𝕜} {n} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) (h₀ : ∀ x ∈ s, g x ≠ 0) : times_cont_diff_on 𝕜 n (f / g) s := λ x hx, (hf x hx).div (hg x hx) (h₀ x hx) lemma times_cont_diff_at.div [complete_space 𝕜] {f g : E → 𝕜} {n} (hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) (hx : g x ≠ 0) : times_cont_diff_at 𝕜 n (λ x, f x / g x) x := hf.div hg hx lemma times_cont_diff.div [complete_space 𝕜] {f g : E → 𝕜} {n} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) (h0 : ∀ x, g x ≠ 0) : times_cont_diff 𝕜 n (λ x, f x / g x) := begin simp only [times_cont_diff_iff_times_cont_diff_at] at *, exact λ x, (hf x).div (hg x) (h0 x) end end algebra_inverse /-! ### Inversion of continuous linear maps between Banach spaces -/ section map_inverse open continuous_linear_map /-- At a continuous linear equivalence `e : E ≃L[𝕜] F` between Banach spaces, the operation of inversion is `C^n`, for all `n`. -/ lemma times_cont_diff_at_map_inverse [complete_space E] {n : with_top ℕ} (e : E ≃L[𝕜] F) : times_cont_diff_at 𝕜 n inverse (e : E →L[𝕜] F) := begin nontriviality E, -- first, we use the lemma `to_ring_inverse` to rewrite in terms of `ring.inverse` in the ring -- `E →L[𝕜] E` let O₁ : (E →L[𝕜] E) → (F →L[𝕜] E) := λ f, f.comp (e.symm : (F →L[𝕜] E)), let O₂ : (E →L[𝕜] F) → (E →L[𝕜] E) := λ f, (e.symm : (F →L[𝕜] E)).comp f, have : continuous_linear_map.inverse = O₁ ∘ ring.inverse ∘ O₂ := funext (to_ring_inverse e), rw this, -- `O₁` and `O₂` are `times_cont_diff`, so we reduce to proving that `ring.inverse` is `times_cont_diff` have h₁ : times_cont_diff 𝕜 n O₁, from is_bounded_bilinear_map_comp.times_cont_diff.comp (times_cont_diff_const.prod times_cont_diff_id), have h₂ : times_cont_diff 𝕜 n O₂, from is_bounded_bilinear_map_comp.times_cont_diff.comp (times_cont_diff_id.prod times_cont_diff_const), refine h₁.times_cont_diff_at.comp _ (times_cont_diff_at.comp _ _ h₂.times_cont_diff_at), convert times_cont_diff_at_ring_inverse 𝕜 (1 : units (E →L[𝕜] E)), simp [O₂, one_def] end end map_inverse section function_inverse open continuous_linear_map /-- If `f` is a local homeomorphism and the point `a` is in its target, and if `f` is `n` times continuously differentiable at `f.symm a`, and if the derivative at `f.symm a` is a continuous linear equivalence, then `f.symm` is `n` times continuously differentiable at the point `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem local_homeomorph.times_cont_diff_at_symm [complete_space E] {n : with_top ℕ} (f : local_homeomorph E F) {f₀' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (hf₀' : has_fderiv_at f (f₀' : E →L[𝕜] F) (f.symm a)) (hf : times_cont_diff_at 𝕜 n f (f.symm a)) : times_cont_diff_at 𝕜 n f.symm a := begin -- We prove this by induction on `n` induction n using with_top.nat_induction with n IH Itop, { rw times_cont_diff_at_zero, exact ⟨f.target, mem_nhds_sets f.open_target ha, f.continuous_inv_fun⟩ }, { obtain ⟨f', ⟨u, hu, hff'⟩, hf'⟩ := times_cont_diff_at_succ_iff_has_fderiv_at.mp hf, apply times_cont_diff_at_succ_iff_has_fderiv_at.mpr, -- For showing `n.succ` times continuous differentiability (the main inductive step), it -- suffices to produce the derivative and show that it is `n` times continuously differentiable have eq_f₀' : f' (f.symm a) = f₀', { exact (hff' (f.symm a) (mem_of_nhds hu)).unique hf₀' }, -- This follows by a bootstrapping formula expressing the derivative as a function of `f` itself refine ⟨inverse ∘ f' ∘ f.symm, _, _⟩, { -- We first check that the derivative of `f` is that formula have h_nhds : {y : E | ∃ (e : E ≃L[𝕜] F), ↑e = f' y} ∈ 𝓝 ((f.symm) a), { have hf₀' := f₀'.nhds, rw ← eq_f₀' at hf₀', exact hf'.continuous_at.preimage_mem_nhds hf₀' }, obtain ⟨t, htu, ht, htf⟩ := mem_nhds_sets_iff.mp (filter.inter_mem_sets hu h_nhds), use f.target ∩ (f.symm) ⁻¹' t, refine ⟨mem_nhds_sets _ _, _⟩, { exact f.preimage_open_of_open_symm ht }, { exact mem_inter ha (mem_preimage.mpr htf) }, intros x hx, obtain ⟨hxu, e, he⟩ := htu hx.2, have h_deriv : has_fderiv_at f ↑e ((f.symm) x), { rw he, exact hff' (f.symm x) hxu }, convert f.has_fderiv_at_symm hx.1 h_deriv, simp [← he] }, { -- Then we check that the formula, being a composition of `times_cont_diff` pieces, is -- itself `times_cont_diff` have h_deriv₁ : times_cont_diff_at 𝕜 n inverse (f' (f.symm a)), { rw eq_f₀', exact times_cont_diff_at_map_inverse _ }, have h_deriv₂ : times_cont_diff_at 𝕜 n f.symm a, { refine IH (hf.of_le _), norm_cast, exact nat.le_succ n }, exact (h_deriv₁.comp _ hf').comp _ h_deriv₂ } }, { refine times_cont_diff_at_top.mpr _, intros n, exact Itop n (times_cont_diff_at_top.mp hf n) } end /-- Let `f` be a local homeomorphism of a nondiscrete normed field, let `a` be a point in its target. if `f` is `n` times continuously differentiable at `f.symm a`, and if the derivative at `f.symm a` is nonzero, then `f.symm` is `n` times continuously differentiable at the point `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem local_homeomorph.times_cont_diff_at_symm_deriv [complete_space 𝕜] {n : with_top ℕ} (f : local_homeomorph 𝕜 𝕜) {f₀' a : 𝕜} (h₀ : f₀' ≠ 0) (ha : a ∈ f.target) (hf₀' : has_deriv_at f f₀' (f.symm a)) (hf : times_cont_diff_at 𝕜 n f (f.symm a)) : times_cont_diff_at 𝕜 n f.symm a := f.times_cont_diff_at_symm ha (hf₀'.has_fderiv_at_equiv h₀) hf end function_inverse section real /-! ### Results over `ℝ` or `ℂ` The results in this section rely on the Mean Value Theorem, and therefore hold only over `ℝ` (and its extension fields such as `ℂ`). -/ variables {𝕂 : Type*} [is_R_or_C 𝕂] {E' : Type*} [normed_group E'] [normed_space 𝕂 E'] {F' : Type*} [normed_group F'] [normed_space 𝕂 F'] /-- If a function has a Taylor series at order at least 1, then at points in the interior of the domain of definition, the term of order 1 of this series is a strict derivative of `f`. -/ lemma has_ftaylor_series_up_to_on.has_strict_fderiv_at {s : set E'} {f : E' → F'} {x : E'} {p : E' → formal_multilinear_series 𝕂 E' F'} {n : with_top ℕ} (hf : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hs : s ∈ 𝓝 x) : has_strict_fderiv_at f ((continuous_multilinear_curry_fin1 𝕂 E' F') (p x 1)) x := has_strict_fderiv_at_of_has_fderiv_at_of_continuous_at (hf.eventually_has_fderiv_at hn hs) $ (continuous_multilinear_curry_fin1 𝕂 E' F').continuous_at.comp $ (hf.cont 1 hn).continuous_at hs /-- If a function is `C^n` with `1 ≤ n` around a point, and its derivative at that point is given to us as `f'`, then `f'` is also a strict derivative. -/ lemma times_cont_diff_at.has_strict_fderiv_at' {f : E' → F'} {f' : E' →L[𝕂] F'} {x : E'} {n : with_top ℕ} (hf : times_cont_diff_at 𝕂 n f x) (hf' : has_fderiv_at f f' x) (hn : 1 ≤ n) : has_strict_fderiv_at f f' x := begin rcases hf 1 hn with ⟨u, H, p, hp⟩, simp only [nhds_within_univ, mem_univ, insert_eq_of_mem] at H, have := hp.has_strict_fderiv_at le_rfl H, rwa hf'.unique this.has_fderiv_at end /-- If a function is `C^n` with `1 ≤ n` around a point, and its derivative at that point is given to us as `f'`, then `f'` is also a strict derivative. -/ lemma times_cont_diff_at.has_strict_deriv_at' {f : 𝕂 → F'} {f' : F'} {x : 𝕂} {n : with_top ℕ} (hf : times_cont_diff_at 𝕂 n f x) (hf' : has_deriv_at f f' x) (hn : 1 ≤ n) : has_strict_deriv_at f f' x := hf.has_strict_fderiv_at' hf' hn /-- If a function is `C^n` with `1 ≤ n` around a point, then the derivative of `f` at this point is also a strict derivative. -/ lemma times_cont_diff_at.has_strict_fderiv_at {f : E' → F'} {x : E'} {n : with_top ℕ} (hf : times_cont_diff_at 𝕂 n f x) (hn : 1 ≤ n) : has_strict_fderiv_at f (fderiv 𝕂 f x) x := hf.has_strict_fderiv_at' (hf.differentiable_at hn).has_fderiv_at hn /-- If a function is `C^n` with `1 ≤ n` around a point, then the derivative of `f` at this point is also a strict derivative. -/ lemma times_cont_diff_at.has_strict_deriv_at {f : 𝕂 → F'} {x : 𝕂} {n : with_top ℕ} (hf : times_cont_diff_at 𝕂 n f x) (hn : 1 ≤ n) : has_strict_deriv_at f (deriv f x) x := (hf.has_strict_fderiv_at hn).has_strict_deriv_at /-- If a function is `C^n` with `1 ≤ n`, then the derivative of `f` is also a strict derivative. -/ lemma times_cont_diff.has_strict_fderiv_at {f : E' → F'} {x : E'} {n : with_top ℕ} (hf : times_cont_diff 𝕂 n f) (hn : 1 ≤ n) : has_strict_fderiv_at f (fderiv 𝕂 f x) x := hf.times_cont_diff_at.has_strict_fderiv_at hn /-- If a function is `C^n` with `1 ≤ n`, then the derivative of `f` is also a strict derivative. -/ lemma times_cont_diff.has_strict_deriv_at {f : 𝕂 → F'} {x : 𝕂} {n : with_top ℕ} (hf : times_cont_diff 𝕂 n f) (hn : 1 ≤ n) : has_strict_deriv_at f (deriv f x) x := hf.times_cont_diff_at.has_strict_deriv_at hn end real section deriv /-! ### One dimension All results up to now have been expressed in terms of the general Fréchet derivative `fderiv`. For maps defined on the field, the one-dimensional derivative `deriv` is often easier to use. In this paragraph, we reformulate some higher smoothness results in terms of `deriv`. -/ variables {f₂ : 𝕜 → F} {s₂ : set 𝕜} open continuous_linear_map (smul_right) /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (formulated with `deriv_within`) is `C^n`. -/ theorem times_cont_diff_on_succ_iff_deriv_within {n : ℕ} (hs : unique_diff_on 𝕜 s₂) : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ times_cont_diff_on 𝕜 n (deriv_within f₂ s₂) s₂ := begin rw times_cont_diff_on_succ_iff_fderiv_within hs, congr' 2, apply le_antisymm, { assume h, have : deriv_within f₂ s₂ = (λ u : 𝕜 →L[𝕜] F, u 1) ∘ (fderiv_within 𝕜 f₂ s₂), by { ext x, refl }, simp only [this], apply times_cont_diff.comp_times_cont_diff_on _ h, exact (is_bounded_bilinear_map_apply.is_bounded_linear_map_left _).times_cont_diff }, { assume h, have : fderiv_within 𝕜 f₂ s₂ = smul_right (1 : 𝕜 →L[𝕜] 𝕜) ∘ deriv_within f₂ s₂, by { ext x, simp [deriv_within] }, simp only [this], apply times_cont_diff.comp_times_cont_diff_on _ h, exact (is_bounded_bilinear_map_smul_right.is_bounded_linear_map_right _).times_cont_diff } end /-- A function is `C^(n + 1)` on an open domain if and only if it is differentiable there, and its derivative (formulated with `deriv`) is `C^n`. -/ theorem times_cont_diff_on_succ_iff_deriv_of_open {n : ℕ} (hs : is_open s₂) : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ times_cont_diff_on 𝕜 n (deriv f₂) s₂ := begin rw times_cont_diff_on_succ_iff_deriv_within hs.unique_diff_on, congr' 2, rw ← iff_iff_eq, apply times_cont_diff_on_congr, assume x hx, exact deriv_within_of_open hs hx end /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (formulated with `deriv_within`) is `C^∞`. -/ theorem times_cont_diff_on_top_iff_deriv_within (hs : unique_diff_on 𝕜 s₂) : times_cont_diff_on 𝕜 ∞ f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ times_cont_diff_on 𝕜 ∞ (deriv_within f₂ s₂) s₂ := begin split, { assume h, refine ⟨h.differentiable_on le_top, _⟩, apply times_cont_diff_on_top.2 (λ n, ((times_cont_diff_on_succ_iff_deriv_within hs).1 _).2), exact h.of_le le_top }, { assume h, refine times_cont_diff_on_top.2 (λ n, _), have A : (n : with_top ℕ) ≤ ∞ := le_top, apply ((times_cont_diff_on_succ_iff_deriv_within hs).2 ⟨h.1, h.2.of_le A⟩).of_le, exact with_top.coe_le_coe.2 (nat.le_succ n) } end /-- A function is `C^∞` on an open domain if and only if it is differentiable there, and its derivative (formulated with `deriv`) is `C^∞`. -/ theorem times_cont_diff_on_top_iff_deriv_of_open (hs : is_open s₂) : times_cont_diff_on 𝕜 ∞ f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ times_cont_diff_on 𝕜 ∞ (deriv f₂) s₂ := begin rw times_cont_diff_on_top_iff_deriv_within hs.unique_diff_on, congr' 2, rw ← iff_iff_eq, apply times_cont_diff_on_congr, assume x hx, exact deriv_within_of_open hs hx end lemma times_cont_diff_on.deriv_within {m n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f₂ s₂) (hs : unique_diff_on 𝕜 s₂) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (deriv_within f₂ s₂) s₂ := begin cases m, { change ∞ + 1 ≤ n at hmn, have : n = ∞, by simpa using hmn, rw this at hf, exact ((times_cont_diff_on_top_iff_deriv_within hs).1 hf).2 }, { change (m.succ : with_top ℕ) ≤ n at hmn, exact ((times_cont_diff_on_succ_iff_deriv_within hs).1 (hf.of_le hmn)).2 } end lemma times_cont_diff_on.deriv_of_open {m n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f₂ s₂) (hs : is_open s₂) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (deriv f₂) s₂ := (hf.deriv_within hs.unique_diff_on hmn).congr (λ x hx, (deriv_within_of_open hs hx).symm) lemma times_cont_diff_on.continuous_on_deriv_within {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f₂ s₂) (hs : unique_diff_on 𝕜 s₂) (hn : 1 ≤ n) : continuous_on (deriv_within f₂ s₂) s₂ := ((times_cont_diff_on_succ_iff_deriv_within hs).1 (h.of_le hn)).2.continuous_on lemma times_cont_diff_on.continuous_on_deriv_of_open {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f₂ s₂) (hs : is_open s₂) (hn : 1 ≤ n) : continuous_on (deriv f₂) s₂ := ((times_cont_diff_on_succ_iff_deriv_of_open hs).1 (h.of_le hn)).2.continuous_on /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative is `C^n`. -/ theorem times_cont_diff_succ_iff_deriv {n : ℕ} : times_cont_diff 𝕜 ((n + 1) : ℕ) f₂ ↔ differentiable 𝕜 f₂ ∧ times_cont_diff 𝕜 n (deriv f₂) := by simp only [← times_cont_diff_on_univ, times_cont_diff_on_succ_iff_deriv_of_open, is_open_univ, differentiable_on_univ] end deriv section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is `n` times continuously differentiable over `ℂ`, then it is `n` times continuously differentiable over `ℝ`. In this paragraph, we give variants of this statement, in the general situation where `ℂ` and `ℝ` are replaced respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra over `𝕜`. -/ variables (𝕜) {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables [normed_space 𝕜' E] [is_scalar_tower 𝕜 𝕜' E] variables [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] variables {p' : E → formal_multilinear_series 𝕜' E F} {n : with_top ℕ} lemma has_ftaylor_series_up_to_on.restrict_scalars (h : has_ftaylor_series_up_to_on n f p' s) : has_ftaylor_series_up_to_on n f (λ x, (p' x).restrict_scalars 𝕜) s := { zero_eq := λ x hx, h.zero_eq x hx, fderiv_within := begin intros m hm x hx, convert ((continuous_multilinear_map.restrict_scalars_linear 𝕜).has_fderiv_at) .comp_has_fderiv_within_at _ ((h.fderiv_within m hm x hx).restrict_scalars 𝕜), end, cont := λ m hm, continuous_multilinear_map.continuous_restrict_scalars.comp_continuous_on (h.cont m hm) } lemma times_cont_diff_within_at.restrict_scalars (h : times_cont_diff_within_at 𝕜' n f s x) : times_cont_diff_within_at 𝕜 n f s x := begin intros m hm, rcases h m hm with ⟨u, u_mem, p', hp'⟩, exact ⟨u, u_mem, _, hp'.restrict_scalars _⟩ end lemma times_cont_diff_on.restrict_scalars (h : times_cont_diff_on 𝕜' n f s) : times_cont_diff_on 𝕜 n f s := λ x hx, (h x hx).restrict_scalars _ lemma times_cont_diff_at.restrict_scalars (h : times_cont_diff_at 𝕜' n f x) : times_cont_diff_at 𝕜 n f x := times_cont_diff_within_at_univ.1 $ h.times_cont_diff_within_at.restrict_scalars _ lemma times_cont_diff.restrict_scalars (h : times_cont_diff 𝕜' n f) : times_cont_diff 𝕜 n f := times_cont_diff_iff_times_cont_diff_at.2 $ λ x, h.times_cont_diff_at.restrict_scalars _ end restrict_scalars
d19010cf2bc04400b718eb165e3bda7b9b427947
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/analysis/normed_space/exponential.lean
5a1afca3c5990973c302755afc40e0d8423c0e0a
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,774
lean
/- Copyright (c) 2021 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import algebra.char_p.algebra import analysis.calculus.deriv import analysis.specific_limits import data.complex.exponential import analysis.complex.basic import topology.metric_space.cau_seq_filter /-! # Exponential in a Banach algebra In this file, we define `exp 𝕂 𝔸`, the exponential map in a normed algebra `𝔸` over a nondiscrete normed field `𝕂`. Although the definition doesn't require `𝔸` to be complete, we need to assume it for most results. We then prove basic results, as described below. ## Main result We prove most result for an arbitrary field `𝕂`, and then specialize to `𝕂 = ℝ` or `𝕂 = ℂ`. ### General case - `has_strict_fderiv_at_exp_zero_of_radius_pos` : `exp 𝕂 𝔸` has strict Fréchet-derivative `1 : 𝔸 →L[𝕂] 𝔸` at zero, as long as it converges on a neighborhood of zero (see also `has_strict_deriv_at_exp_zero_of_radius_pos` for the case `𝔸 = 𝕂`) - `exp_add_of_commute_of_lt_radius` : if `𝕂` has characteristic zero, then given two commuting elements `x` and `y` in the disk of convergence, we have `exp 𝕂 𝔸 (x+y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y)` - `exp_add_of_lt_radius` : if `𝕂` has characteristic zero and `𝔸` is commutative, then given two elements `x` and `y` in the disk of convergence, we have `exp 𝕂 𝔸 (x+y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y)` - `has_strict_fderiv_at_exp_of_lt_radius` : if `𝕂` has characteristic zero and `𝔸` is commutative, then given a point `x` in the disk of convergence, `exp 𝕂 𝔸` as strict Fréchet-derivative `exp 𝕂 𝔸 x • 1 : 𝔸 →L[𝕂] 𝔸` at x (see also `has_strict_deriv_at_exp_of_lt_radius` for the case `𝔸 = 𝕂`) ### `𝕂 = ℝ` or `𝕂 = ℂ` - `exp_series_radius_eq_top` : the `formal_multilinear_series` defining `exp 𝕂 𝔸` has infinite radius of convergence - `has_strict_fderiv_at_exp_zero` : `exp 𝕂 𝔸` has strict Fréchet-derivative `1 : 𝔸 →L[𝕂] 𝔸` at zero (see also `has_strict_deriv_at_exp_zero` for the case `𝔸 = 𝕂`) - `exp_add_of_commute` : given two commuting elements `x` and `y`, we have `exp 𝕂 𝔸 (x+y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y)` - `exp_add` : if `𝔸` is commutative, then we have `exp 𝕂 𝔸 (x+y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y)` for any `x` and `y` - `has_strict_fderiv_at_exp` : if `𝔸` is commutative, then given any point `x`, `exp 𝕂 𝔸` as strict Fréchet-derivative `exp 𝕂 𝔸 x • 1 : 𝔸 →L[𝕂] 𝔸` at x (see also `has_strict_deriv_at_exp` for the case `𝔸 = 𝕂`) ### Other useful compatibility results - `exp_eq_exp_of_field_extension` : given `𝕂' / 𝕂` a normed field extension (that is, an instance of `normed_algebra 𝕂 𝕂'`) and a normed algebra `𝔸` over both `𝕂` and `𝕂'` then `exp 𝕂 𝔸 = exp 𝕂' 𝔸` - `complex.exp_eq_exp_ℂ_ℂ` : `complex.exp = exp ℂ ℂ` - `real.exp_eq_exp_ℝ_ℝ` : `real.exp = exp ℝ ℝ` -/ open filter is_R_or_C continuous_multilinear_map normed_field asymptotics open_locale nat topological_space big_operators ennreal section any_field_any_algebra variables (𝕂 𝔸 : Type*) [nondiscrete_normed_field 𝕂] [normed_ring 𝔸] [normed_algebra 𝕂 𝔸] /-- In a Banach algebra `𝔸` over a normed field `𝕂`, `exp_series 𝕂 𝔸` is the `formal_multilinear_series` whose `n`-th term is the map `(xᵢ) : 𝔸ⁿ ↦ (1/n! : 𝕂) • ∏ xᵢ`. Its sum is the exponential map `exp 𝕂 𝔸 : 𝔸 → 𝔸`. -/ def exp_series : formal_multilinear_series 𝕂 𝔸 𝔸 := λ n, (1/n! : 𝕂) • continuous_multilinear_map.mk_pi_algebra_fin 𝕂 n 𝔸 /-- In a Banach algebra `𝔸` over a normed field `𝕂`, `exp 𝕂 𝔸 : 𝔸 → 𝔸` is the exponential map determined by the action of `𝕂` on `𝔸`. It is defined as the sum of the `formal_multilinear_series` `exp_series 𝕂 𝔸`. -/ noncomputable def exp (x : 𝔸) : 𝔸 := (exp_series 𝕂 𝔸).sum x variables {𝕂 𝔸} lemma exp_series_apply_eq (x : 𝔸) (n : ℕ) : exp_series 𝕂 𝔸 n (λ _, x) = (1 / n! : 𝕂) • x^n := by simp [exp_series] lemma exp_series_apply_eq' (x : 𝔸) : (λ n, exp_series 𝕂 𝔸 n (λ _, x)) = (λ n, (1 / n! : 𝕂) • x^n) := funext (exp_series_apply_eq x) lemma exp_series_apply_eq_field (x : 𝕂) (n : ℕ) : exp_series 𝕂 𝕂 n (λ _, x) = x^n / n! := begin rw [div_eq_inv_mul, ←smul_eq_mul, inv_eq_one_div], exact exp_series_apply_eq x n, end lemma exp_series_apply_eq_field' (x : 𝕂) : (λ n, exp_series 𝕂 𝕂 n (λ _, x)) = (λ n, x^n / n!) := funext (exp_series_apply_eq_field x) lemma exp_series_sum_eq (x : 𝔸) : (exp_series 𝕂 𝔸).sum x = ∑' (n : ℕ), (1 / n! : 𝕂) • x^n := tsum_congr (λ n, exp_series_apply_eq x n) lemma exp_series_sum_eq_field (x : 𝕂) : (exp_series 𝕂 𝕂).sum x = ∑' (n : ℕ), x^n / n! := tsum_congr (λ n, exp_series_apply_eq_field x n) lemma exp_eq_tsum : exp 𝕂 𝔸 = (λ x : 𝔸, ∑' (n : ℕ), (1 / n! : 𝕂) • x^n) := funext exp_series_sum_eq lemma exp_eq_tsum_field : exp 𝕂 𝕂 = (λ x : 𝕂, ∑' (n : ℕ), x^n / n!) := funext exp_series_sum_eq_field lemma exp_zero : exp 𝕂 𝔸 0 = 1 := begin suffices : (λ x : 𝔸, ∑' (n : ℕ), (1 / n! : 𝕂) • x^n) 0 = ∑' (n : ℕ), if n = 0 then 1 else 0, { have key : ∀ n ∉ ({0} : finset ℕ), (if n = 0 then (1 : 𝔸) else 0) = 0, from λ n hn, if_neg (finset.not_mem_singleton.mp hn), rw [exp_eq_tsum, this, tsum_eq_sum key, finset.sum_singleton], simp }, refine tsum_congr (λ n, _), split_ifs with h h; simp [h] end lemma norm_exp_series_summable_of_mem_ball (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : summable (λ n, ∥exp_series 𝕂 𝔸 n (λ _, x)∥) := (exp_series 𝕂 𝔸).summable_norm_apply hx lemma norm_exp_series_summable_of_mem_ball' (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : summable (λ n, ∥(1 / n! : 𝕂) • x^n∥) := begin change summable (norm ∘ _), rw ← exp_series_apply_eq', exact norm_exp_series_summable_of_mem_ball x hx end lemma norm_exp_series_field_summable_of_mem_ball (x : 𝕂) (hx : x ∈ emetric.ball (0 : 𝕂) (exp_series 𝕂 𝕂).radius) : summable (λ n, ∥x^n / n!∥) := begin change summable (norm ∘ _), rw ← exp_series_apply_eq_field', exact norm_exp_series_summable_of_mem_ball x hx end section complete_algebra variables [complete_space 𝔸] lemma exp_series_summable_of_mem_ball (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : summable (λ n, exp_series 𝕂 𝔸 n (λ _, x)) := summable_of_summable_norm (norm_exp_series_summable_of_mem_ball x hx) lemma exp_series_summable_of_mem_ball' (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : summable (λ n, (1 / n! : 𝕂) • x^n) := summable_of_summable_norm (norm_exp_series_summable_of_mem_ball' x hx) lemma exp_series_field_summable_of_mem_ball [complete_space 𝕂] (x : 𝕂) (hx : x ∈ emetric.ball (0 : 𝕂) (exp_series 𝕂 𝕂).radius) : summable (λ n, x^n / n!) := summable_of_summable_norm (norm_exp_series_field_summable_of_mem_ball x hx) lemma exp_series_has_sum_exp_of_mem_ball (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : has_sum (λ n, exp_series 𝕂 𝔸 n (λ _, x)) (exp 𝕂 𝔸 x) := formal_multilinear_series.has_sum (exp_series 𝕂 𝔸) hx lemma exp_series_has_sum_exp_of_mem_ball' (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : has_sum (λ n, (1 / n! : 𝕂) • x^n) (exp 𝕂 𝔸 x):= begin rw ← exp_series_apply_eq', exact exp_series_has_sum_exp_of_mem_ball x hx end lemma exp_series_field_has_sum_exp_of_mem_ball [complete_space 𝕂] (x : 𝕂) (hx : x ∈ emetric.ball (0 : 𝕂) (exp_series 𝕂 𝕂).radius) : has_sum (λ n, x^n / n!) (exp 𝕂 𝕂 x) := begin rw ← exp_series_apply_eq_field', exact exp_series_has_sum_exp_of_mem_ball x hx end lemma has_fpower_series_on_ball_exp_of_radius_pos (h : 0 < (exp_series 𝕂 𝔸).radius) : has_fpower_series_on_ball (exp 𝕂 𝔸) (exp_series 𝕂 𝔸) 0 (exp_series 𝕂 𝔸).radius := (exp_series 𝕂 𝔸).has_fpower_series_on_ball h lemma has_fpower_series_at_exp_zero_of_radius_pos (h : 0 < (exp_series 𝕂 𝔸).radius) : has_fpower_series_at (exp 𝕂 𝔸) (exp_series 𝕂 𝔸) 0 := (has_fpower_series_on_ball_exp_of_radius_pos h).has_fpower_series_at lemma continuous_on_exp : continuous_on (exp 𝕂 𝔸) (emetric.ball 0 (exp_series 𝕂 𝔸).radius) := formal_multilinear_series.continuous_on lemma analytic_at_exp_of_mem_ball (x : 𝔸) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : analytic_at 𝕂 (exp 𝕂 𝔸) x:= begin by_cases h : (exp_series 𝕂 𝔸).radius = 0, { rw h at hx, exact (ennreal.not_lt_zero hx).elim }, { have h := pos_iff_ne_zero.mpr h, exact (has_fpower_series_on_ball_exp_of_radius_pos h).analytic_at_of_mem hx } end /-- The exponential in a Banach-algebra `𝔸` over a normed field `𝕂` has strict Fréchet-derivative `1 : 𝔸 →L[𝕂] 𝔸` at zero, as long as it converges on a neighborhood of zero. -/ lemma has_strict_fderiv_at_exp_zero_of_radius_pos (h : 0 < (exp_series 𝕂 𝔸).radius) : has_strict_fderiv_at (exp 𝕂 𝔸) (1 : 𝔸 →L[𝕂] 𝔸) 0 := begin convert (has_fpower_series_at_exp_zero_of_radius_pos h).has_strict_fderiv_at, ext x, change x = exp_series 𝕂 𝔸 1 (λ _, x), simp [exp_series_apply_eq] end /-- The exponential in a Banach-algebra `𝔸` over a normed field `𝕂` has Fréchet-derivative `1 : 𝔸 →L[𝕂] 𝔸` at zero, as long as it converges on a neighborhood of zero. -/ lemma has_fderiv_at_exp_zero_of_radius_pos (h : 0 < (exp_series 𝕂 𝔸).radius) : has_fderiv_at (exp 𝕂 𝔸) (1 : 𝔸 →L[𝕂] 𝔸) 0 := (has_strict_fderiv_at_exp_zero_of_radius_pos h).has_fderiv_at /-- In a Banach-algebra `𝔸` over a normed field `𝕂` of characteristic zero, if `x` and `y` are in the disk of convergence and commute, then `exp 𝕂 𝔸 (x + y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y)`. -/ lemma exp_add_of_commute_of_mem_ball [char_zero 𝕂] {x y : 𝔸} (hxy : commute x y) (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) (hy : y ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : exp 𝕂 𝔸 (x + y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y) := begin rw [exp_eq_tsum, tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm (norm_exp_series_summable_of_mem_ball' x hx) (norm_exp_series_summable_of_mem_ball' y hy)], dsimp only, conv_lhs {congr, funext, rw [hxy.add_pow' _, finset.smul_sum]}, refine tsum_congr (λ n, finset.sum_congr rfl $ λ kl hkl, _), rw [nsmul_eq_smul_cast 𝕂, smul_smul, smul_mul_smul, ← (finset.nat.mem_antidiagonal.mp hkl), nat.cast_add_choose, (finset.nat.mem_antidiagonal.mp hkl)], congr' 1, have : (n! : 𝕂) ≠ 0 := nat.cast_ne_zero.mpr n.factorial_ne_zero, field_simp [this] end end complete_algebra end any_field_any_algebra section any_field_comm_algebra variables {𝕂 𝔸 : Type*} [nondiscrete_normed_field 𝕂] [normed_comm_ring 𝔸] [normed_algebra 𝕂 𝔸] [complete_space 𝔸] /-- In a commutative Banach-algebra `𝔸` over a normed field `𝕂` of characteristic zero, `exp 𝕂 𝔸 (x+y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y)` for all `x`, `y` in the disk of convergence. -/ lemma exp_add_of_mem_ball [char_zero 𝕂] {x y : 𝔸} (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) (hy : y ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : exp 𝕂 𝔸 (x + y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y) := exp_add_of_commute_of_mem_ball (commute.all x y) hx hy /-- The exponential map in a commutative Banach-algebra `𝔸` over a normed field `𝕂` of characteristic zero has Fréchet-derivative `exp 𝕂 𝔸 x • 1 : 𝔸 →L[𝕂] 𝔸` at any point `x` in the disk of convergence. -/ lemma has_fderiv_at_exp_of_mem_ball [char_zero 𝕂] {x : 𝔸} (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : has_fderiv_at (exp 𝕂 𝔸) (exp 𝕂 𝔸 x • 1 : 𝔸 →L[𝕂] 𝔸) x := begin have hpos : 0 < (exp_series 𝕂 𝔸).radius := (zero_le _).trans_lt hx, rw has_fderiv_at_iff_is_o_nhds_zero, suffices : (λ h, exp 𝕂 𝔸 x * (exp 𝕂 𝔸 (0 + h) - exp 𝕂 𝔸 0 - continuous_linear_map.id 𝕂 𝔸 h)) =ᶠ[𝓝 0] (λ h, exp 𝕂 𝔸 (x + h) - exp 𝕂 𝔸 x - exp 𝕂 𝔸 x • continuous_linear_map.id 𝕂 𝔸 h), { refine (is_o.const_mul_left _ _).congr' this (eventually_eq.refl _ _), rw ← has_fderiv_at_iff_is_o_nhds_zero, exact has_fderiv_at_exp_zero_of_radius_pos hpos }, have : ∀ᶠ h in 𝓝 (0 : 𝔸), h ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius := emetric.ball_mem_nhds _ hpos, filter_upwards [this], intros h hh, rw [exp_add_of_mem_ball hx hh, exp_zero, zero_add, continuous_linear_map.id_apply, smul_eq_mul], ring end /-- The exponential map in a commutative Banach-algebra `𝔸` over a normed field `𝕂` of characteristic zero has strict Fréchet-derivative `exp 𝕂 𝔸 x • 1 : 𝔸 →L[𝕂] 𝔸` at any point `x` in the disk of convergence. -/ lemma has_strict_fderiv_at_exp_of_mem_ball [char_zero 𝕂] {x : 𝔸} (hx : x ∈ emetric.ball (0 : 𝔸) (exp_series 𝕂 𝔸).radius) : has_strict_fderiv_at (exp 𝕂 𝔸) (exp 𝕂 𝔸 x • 1 : 𝔸 →L[𝕂] 𝔸) x := let ⟨p, hp⟩ := analytic_at_exp_of_mem_ball x hx in hp.has_fderiv_at.unique (has_fderiv_at_exp_of_mem_ball hx) ▸ hp.has_strict_fderiv_at end any_field_comm_algebra section deriv variables {𝕂 : Type*} [nondiscrete_normed_field 𝕂] [complete_space 𝕂] /-- The exponential map in a complete normed field `𝕂` of characteristic zero has strict derivative `exp 𝕂 𝕂 x` at any point `x` in the disk of convergence. -/ lemma has_strict_deriv_at_exp_of_mem_ball [char_zero 𝕂] {x : 𝕂} (hx : x ∈ emetric.ball (0 : 𝕂) (exp_series 𝕂 𝕂).radius) : has_strict_deriv_at (exp 𝕂 𝕂) (exp 𝕂 𝕂 x) x := by simpa using (has_strict_fderiv_at_exp_of_mem_ball hx).has_strict_deriv_at /-- The exponential map in a complete normed field `𝕂` of characteristic zero has derivative `exp 𝕂 𝕂 x` at any point `x` in the disk of convergence. -/ lemma has_deriv_at_exp_of_mem_ball [char_zero 𝕂] {x : 𝕂} (hx : x ∈ emetric.ball (0 : 𝕂) (exp_series 𝕂 𝕂).radius) : has_deriv_at (exp 𝕂 𝕂) (exp 𝕂 𝕂 x) x := (has_strict_deriv_at_exp_of_mem_ball hx).has_deriv_at /-- The exponential map in a complete normed field `𝕂` of characteristic zero has strict derivative `1` at zero, as long as it converges on a neighborhood of zero. -/ lemma has_strict_deriv_at_exp_zero_of_radius_pos (h : 0 < (exp_series 𝕂 𝕂).radius) : has_strict_deriv_at (exp 𝕂 𝕂) 1 0 := (has_strict_fderiv_at_exp_zero_of_radius_pos h).has_strict_deriv_at /-- The exponential map in a complete normed field `𝕂` of characteristic zero has derivative `1` at zero, as long as it converges on a neighborhood of zero. -/ lemma has_deriv_at_exp_zero_of_radius_pos (h : 0 < (exp_series 𝕂 𝕂).radius) : has_deriv_at (exp 𝕂 𝕂) 1 0 := (has_strict_deriv_at_exp_zero_of_radius_pos h).has_deriv_at end deriv section is_R_or_C section any_algebra variables {𝕂 𝔸 : Type*} [is_R_or_C 𝕂] [normed_ring 𝔸] [normed_algebra 𝕂 𝔸] -- This is private because one can use the more general `exp_series_summable_field` intead. private lemma real.summable_pow_div_factorial (x : ℝ) : summable (λ n : ℕ, x^n / n!) := begin by_cases h : x = 0, { refine summable_of_norm_bounded_eventually 0 summable_zero _, filter_upwards [eventually_cofinite_ne 0], intros n hn, rw [h, zero_pow' n hn, zero_div, norm_zero], exact le_refl _ }, { refine summable_of_ratio_test_tendsto_lt_one zero_lt_one (eventually_of_forall $ λ n, div_ne_zero (pow_ne_zero n h) (nat.cast_ne_zero.mpr n.factorial_ne_zero)) _, suffices : ∀ n : ℕ, ∥x^(n+1) / (n+1)!∥ / ∥x^n / n!∥ = ∥x∥ / ∥((n+1 : ℕ) : ℝ)∥, { conv {congr, funext, rw [this, real.norm_coe_nat] }, exact (tendsto_const_div_at_top_nhds_0_nat _).comp (tendsto_add_at_top_nat 1) }, intro n, calc ∥x^(n+1) / (n+1)!∥ / ∥x^n / n!∥ = (∥x∥^n * ∥x∥) * (∥(n! : ℝ)∥⁻¹ * ∥((n+1 : ℕ) : ℝ)∥⁻¹) * ((∥x∥^n)⁻¹ * ∥(n! : ℝ)∥) : by rw [ normed_field.norm_div, normed_field.norm_div, normed_field.norm_pow, normed_field.norm_pow, pow_add, pow_one, div_eq_mul_inv, div_eq_mul_inv, div_eq_mul_inv, mul_inv', inv_inv', nat.factorial_succ, nat.cast_mul, normed_field.norm_mul, mul_inv_rev' ] ... = (∥x∥ * ∥((n+1 : ℕ) : ℝ)∥⁻¹) * (∥x∥^n * (∥x∥^n)⁻¹) * (∥(n! : ℝ)∥ * ∥(n! : ℝ)∥⁻¹) : by linarith --faster than ac_refl ! ... = (∥x∥ * ∥((n+1 : ℕ) : ℝ)∥⁻¹) * 1 * 1 : by rw [mul_inv_cancel (pow_ne_zero _ $ λ h', h $ norm_eq_zero.mp h'), mul_inv_cancel (λ h', n.factorial_ne_zero $ nat.cast_eq_zero.mp $ norm_eq_zero.mp h')]; apply_instance ... = ∥x∥ / ∥((n+1 : ℕ) : ℝ)∥ : by rw [mul_one, mul_one, ← div_eq_mul_inv] } end variables (𝕂 𝔸) /-- In a normed algebra `𝔸` over `𝕂 = ℝ` or `𝕂 = ℂ`, the series defining the exponential map has an infinite radius of convergence. -/ lemma exp_series_radius_eq_top : (exp_series 𝕂 𝔸).radius = ∞ := begin refine (exp_series 𝕂 𝔸).radius_eq_top_of_summable_norm (λ r, _), refine summable_of_norm_bounded_eventually _ (real.summable_pow_div_factorial r) _, filter_upwards [eventually_cofinite_ne 0], intros n hn, rw [norm_mul, norm_norm (exp_series 𝕂 𝔸 n), exp_series, norm_smul, norm_div, norm_one, norm_pow, nnreal.norm_eq, norm_eq_abs, abs_cast_nat, mul_comm, ←mul_assoc, ←mul_div_assoc, mul_one], have : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕂 n 𝔸∥ ≤ 1 := norm_mk_pi_algebra_fin_le_of_pos (nat.pos_of_ne_zero hn), exact mul_le_of_le_one_right (div_nonneg (pow_nonneg r.coe_nonneg n) n!.cast_nonneg) this end lemma exp_series_radius_pos : 0 < (exp_series 𝕂 𝔸).radius := begin rw exp_series_radius_eq_top, exact with_top.zero_lt_top end variables {𝕂 𝔸} section complete_algebra lemma norm_exp_series_summable (x : 𝔸) : summable (λ n, ∥exp_series 𝕂 𝔸 n (λ _, x)∥) := norm_exp_series_summable_of_mem_ball x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) lemma norm_exp_series_summable' (x : 𝔸) : summable (λ n, ∥(1 / n! : 𝕂) • x^n∥) := norm_exp_series_summable_of_mem_ball' x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) lemma norm_exp_series_field_summable (x : 𝕂) : summable (λ n, ∥x^n / n!∥) := norm_exp_series_field_summable_of_mem_ball x ((exp_series_radius_eq_top 𝕂 𝕂).symm ▸ edist_lt_top _ _) variables [complete_space 𝔸] lemma exp_series_summable (x : 𝔸) : summable (λ n, exp_series 𝕂 𝔸 n (λ _, x)) := summable_of_summable_norm (norm_exp_series_summable x) lemma exp_series_summable' (x : 𝔸) : summable (λ n, (1 / n! : 𝕂) • x^n) := summable_of_summable_norm (norm_exp_series_summable' x) lemma exp_series_field_summable (x : 𝕂) : summable (λ n, x^n / n!) := summable_of_summable_norm (norm_exp_series_field_summable x) lemma exp_series_has_sum_exp (x : 𝔸) : has_sum (λ n, exp_series 𝕂 𝔸 n (λ _, x)) (exp 𝕂 𝔸 x) := exp_series_has_sum_exp_of_mem_ball x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) lemma exp_series_has_sum_exp' (x : 𝔸) : has_sum (λ n, (1 / n! : 𝕂) • x^n) (exp 𝕂 𝔸 x):= exp_series_has_sum_exp_of_mem_ball' x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) lemma exp_series_field_has_sum_exp (x : 𝕂) : has_sum (λ n, x^n / n!) (exp 𝕂 𝕂 x):= exp_series_field_has_sum_exp_of_mem_ball x ((exp_series_radius_eq_top 𝕂 𝕂).symm ▸ edist_lt_top _ _) lemma exp_has_fpower_series_on_ball : has_fpower_series_on_ball (exp 𝕂 𝔸) (exp_series 𝕂 𝔸) 0 ∞ := exp_series_radius_eq_top 𝕂 𝔸 ▸ has_fpower_series_on_ball_exp_of_radius_pos (exp_series_radius_pos _ _) lemma exp_has_fpower_series_at_zero : has_fpower_series_at (exp 𝕂 𝔸) (exp_series 𝕂 𝔸) 0 := exp_has_fpower_series_on_ball.has_fpower_series_at lemma exp_continuous : continuous (exp 𝕂 𝔸) := begin rw [continuous_iff_continuous_on_univ, ← metric.eball_top_eq_univ (0 : 𝔸), ← exp_series_radius_eq_top 𝕂 𝔸], exact continuous_on_exp end lemma exp_analytic (x : 𝔸) : analytic_at 𝕂 (exp 𝕂 𝔸) x := analytic_at_exp_of_mem_ball x ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) /-- The exponential in a Banach-algebra `𝔸` over `𝕂 = ℝ` or `𝕂 = ℂ` has strict Fréchet-derivative `1 : 𝔸 →L[𝕂] 𝔸` at zero. -/ lemma has_strict_fderiv_at_exp_zero : has_strict_fderiv_at (exp 𝕂 𝔸) (1 : 𝔸 →L[𝕂] 𝔸) 0 := has_strict_fderiv_at_exp_zero_of_radius_pos (exp_series_radius_pos 𝕂 𝔸) /-- The exponential in a Banach-algebra `𝔸` over `𝕂 = ℝ` or `𝕂 = ℂ` has Fréchet-derivative `1 : 𝔸 →L[𝕂] 𝔸` at zero. -/ lemma has_fderiv_at_exp_zero : has_fderiv_at (exp 𝕂 𝔸) (1 : 𝔸 →L[𝕂] 𝔸) 0 := has_strict_fderiv_at_exp_zero.has_fderiv_at end complete_algebra local attribute [instance] char_zero_R_or_C /-- In a Banach-algebra `𝔸` over `𝕂 = ℝ` or `𝕂 = ℂ`, if `x` and `y` commute, then `exp 𝕂 𝔸 (x+y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y)`. -/ lemma exp_add_of_commute [complete_space 𝔸] {x y : 𝔸} (hxy : commute x y) : exp 𝕂 𝔸 (x + y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y) := exp_add_of_commute_of_mem_ball hxy ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) end any_algebra section comm_algebra variables {𝕂 𝔸 : Type*} [is_R_or_C 𝕂] [normed_comm_ring 𝔸] [normed_algebra 𝕂 𝔸] [complete_space 𝔸] local attribute [instance] char_zero_R_or_C /-- In a comutative Banach-algebra `𝔸` over `𝕂 = ℝ` or `𝕂 = ℂ`, `exp 𝕂 𝔸 (x+y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y)`. -/ lemma exp_add {x y : 𝔸} : exp 𝕂 𝔸 (x + y) = (exp 𝕂 𝔸 x) * (exp 𝕂 𝔸 y) := exp_add_of_mem_ball ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) /-- The exponential map in a commutative Banach-algebra `𝔸` over `𝕂 = ℝ` or `𝕂 = ℂ` has strict Fréchet-derivative `exp 𝕂 𝔸 x • 1 : 𝔸 →L[𝕂] 𝔸` at any point `x`. -/ lemma has_strict_fderiv_at_exp {x : 𝔸} : has_strict_fderiv_at (exp 𝕂 𝔸) (exp 𝕂 𝔸 x • 1 : 𝔸 →L[𝕂] 𝔸) x := has_strict_fderiv_at_exp_of_mem_ball ((exp_series_radius_eq_top 𝕂 𝔸).symm ▸ edist_lt_top _ _) /-- The exponential map in a commutative Banach-algebra `𝔸` over `𝕂 = ℝ` or `𝕂 = ℂ` has Fréchet-derivative `exp 𝕂 𝔸 x • 1 : 𝔸 →L[𝕂] 𝔸` at any point `x`. -/ lemma has_fderiv_at_exp {x : 𝔸} : has_fderiv_at (exp 𝕂 𝔸) (exp 𝕂 𝔸 x • 1 : 𝔸 →L[𝕂] 𝔸) x := has_strict_fderiv_at_exp.has_fderiv_at end comm_algebra section deriv variables {𝕂 : Type*} [is_R_or_C 𝕂] local attribute [instance] char_zero_R_or_C /-- The exponential map in `𝕂 = ℝ` or `𝕂 = ℂ` has strict derivative `exp 𝕂 𝕂 x` at any point `x`. -/ lemma has_strict_deriv_at_exp {x : 𝕂} : has_strict_deriv_at (exp 𝕂 𝕂) (exp 𝕂 𝕂 x) x := has_strict_deriv_at_exp_of_mem_ball ((exp_series_radius_eq_top 𝕂 𝕂).symm ▸ edist_lt_top _ _) /-- The exponential map in `𝕂 = ℝ` or `𝕂 = ℂ` has derivative `exp 𝕂 𝕂 x` at any point `x`. -/ lemma has_deriv_at_exp {x : 𝕂} : has_deriv_at (exp 𝕂 𝕂) (exp 𝕂 𝕂 x) x := has_strict_deriv_at_exp.has_deriv_at /-- The exponential map in `𝕂 = ℝ` or `𝕂 = ℂ` has strict derivative `1` at zero. -/ lemma has_strict_deriv_at_exp_zero : has_strict_deriv_at (exp 𝕂 𝕂) 1 0 := has_strict_deriv_at_exp_zero_of_radius_pos (exp_series_radius_pos 𝕂 𝕂) /-- The exponential map in `𝕂 = ℝ` or `𝕂 = ℂ` has derivative `1` at zero. -/ lemma has_deriv_at_exp_zero : has_deriv_at (exp 𝕂 𝕂) 1 0 := has_strict_deriv_at_exp_zero.has_deriv_at end deriv end is_R_or_C section scalar_tower variables (𝕂 𝕂' 𝔸 : Type*) [nondiscrete_normed_field 𝕂] [nondiscrete_normed_field 𝕂'] [normed_ring 𝔸] [normed_algebra 𝕂 𝔸] [normed_algebra 𝕂 𝕂'] [normed_algebra 𝕂' 𝔸] [is_scalar_tower 𝕂 𝕂' 𝔸] (p : ℕ) [char_p 𝕂 p] include p lemma exp_series_eq_exp_series_of_field_extension (n : ℕ) (x : 𝔸) : (exp_series 𝕂 𝔸 n (λ _, x)) = (exp_series 𝕂' 𝔸 n (λ _, x)) := begin haveI : char_p 𝕂' p := char_p_of_injective_algebra_map (algebra_map 𝕂 𝕂').injective p, rw [exp_series, exp_series, smul_apply, mk_pi_algebra_fin_apply, list.of_fn_const, list.prod_repeat, smul_apply, mk_pi_algebra_fin_apply, list.of_fn_const, list.prod_repeat, ←inv_eq_one_div, ←inv_eq_one_div, ← smul_one_smul 𝕂' (_ : 𝕂) (_ : 𝔸)], congr, symmetry, have key : (n! : 𝕂) = 0 ↔ (n! : 𝕂') = 0, { rw [char_p.cast_eq_zero_iff 𝕂' p, char_p.cast_eq_zero_iff 𝕂 p] }, by_cases h : (n! : 𝕂) = 0, { have h' : (n! : 𝕂') = 0 := key.mp h, field_simp [h, h'] }, { have h' : (n! : 𝕂') ≠ 0 := λ hyp, h (key.mpr hyp), suffices : (n! : 𝕂) • (n!⁻¹ : 𝕂') = (n! : 𝕂) • ((n!⁻¹ : 𝕂) • 1), { apply_fun (λ (x : 𝕂'), (n!⁻¹ : 𝕂) • x) at this, rwa [inv_smul_smul' h, inv_smul_smul' h] at this }, rw [← smul_assoc, ← nsmul_eq_smul_cast, nsmul_eq_smul_cast 𝕂' _ (_ : 𝕂')], field_simp [h, h'] } end /-- Given `𝕂' / 𝕂` a normed field extension (that is, an instance of `normed_algebra 𝕂 𝕂'`) and a normed algebra `𝔸` over both `𝕂` and `𝕂'` then `exp 𝕂 𝔸 = exp 𝕂' 𝔸`. -/ lemma exp_eq_exp_of_field_extension : exp 𝕂 𝔸 = exp 𝕂' 𝔸 := begin ext, rw [exp, exp], refine tsum_congr (λ n, _), rw exp_series_eq_exp_series_of_field_extension 𝕂 𝕂' 𝔸 p n x end end scalar_tower section complex lemma complex.exp_eq_exp_ℂ_ℂ : complex.exp = exp ℂ ℂ := begin refine funext (λ x, _), rw [complex.exp, exp_eq_tsum_field], exact tendsto_nhds_unique x.exp'.tendsto_limit (exp_series_field_summable x).has_sum.tendsto_sum_nat end lemma exp_ℝ_ℂ_eq_exp_ℂ_ℂ : exp ℝ ℂ = exp ℂ ℂ := exp_eq_exp_of_field_extension ℝ ℂ ℂ 0 end complex section real lemma real.exp_eq_exp_ℝ_ℝ : real.exp = exp ℝ ℝ := begin refine funext (λ x, _), rw [real.exp, complex.exp_eq_exp_ℂ_ℂ, ← exp_ℝ_ℂ_eq_exp_ℂ_ℂ, exp_eq_tsum, exp_eq_tsum_field, ← re_to_complex, ← re_clm_apply, re_clm.map_tsum (exp_series_summable' (x : ℂ))], refine tsum_congr (λ n, _), rw [re_clm.map_smul, ← complex.of_real_pow, re_clm_apply, re_to_complex, complex.of_real_re, smul_eq_mul, one_div, mul_comm, div_eq_mul_inv] end end real
8634ca3657a82cd197220ea32e192ea421fbeda0
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/free_comm_ring.lean
887264d82f83ed7f894baba39f14a545162deca1
[ "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
14,051
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin -/ import data.mv_polynomial.equiv import data.mv_polynomial.comm_ring import logic.equiv.functor import ring_theory.free_ring /-! # Free commutative rings The theory of the free commutative ring generated by a type `α`. It is isomorphic to the polynomial ring over ℤ with variables in `α` ## Main definitions * `free_comm_ring α` : the free commutative ring on a type α * `lift (f : α → R)` : the ring hom `free_comm_ring α →+* R` induced by functoriality from `f`. * `map (f : α → β)` : the ring hom `free_comm_ring α →*+ free_comm_ring β` induced by functoriality from f. ## Main results `free_comm_ring` has functorial properties (it is an adjoint to the forgetful functor). In this file we have: * `of : α → free_comm_ring α` * `lift (f : α → R) : free_comm_ring α →+* R` * `map (f : α → β) : free_comm_ring α →+* free_comm_ring β` * `free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ` : `free_comm_ring α` is isomorphic to a polynomial ring. ## Implementation notes `free_comm_ring α` is implemented not using `mv_polynomial` but directly as the free abelian group on `multiset α`, the type of monomials in this free commutative ring. ## Tags free commutative ring, free ring -/ noncomputable theory open_locale classical polynomial universes u v variables (α : Type u) /-- `free_comm_ring α` is the free commutative ring on the type `α`. -/ @[derive [comm_ring, inhabited]] def free_comm_ring (α : Type u) : Type u := free_abelian_group $ multiplicative $ multiset α namespace free_comm_ring variables {α} /-- The canonical map from `α` to the free commutative ring on `α`. -/ def of (x : α) : free_comm_ring α := free_abelian_group.of $ multiplicative.of_add ({x} : multiset α) lemma of_injective : function.injective (of : α → free_comm_ring α) := free_abelian_group.of_injective.comp (λ x y, (multiset.coe_eq_coe.trans list.singleton_perm_singleton).mp) @[elab_as_eliminator] protected lemma induction_on {C : free_comm_ring α → Prop} (z : free_comm_ring α) (hn1 : C (-1)) (hb : ∀ b, C (of b)) (ha : ∀ x y, C x → C y → C (x + y)) (hm : ∀ x y, C x → C y → C (x * y)) : C z := have hn : ∀ x, C x → C (-x), from λ x ih, neg_one_mul x ▸ hm _ _ hn1 ih, have h1 : C 1, from neg_neg (1 : free_comm_ring α) ▸ hn _ hn1, free_abelian_group.induction_on z (add_left_neg (1 : free_comm_ring α) ▸ ha _ _ hn1 h1) (λ m, multiset.induction_on m h1 $ λ a m ih, hm _ _ (hb a) ih) (λ m ih, hn _ ih) ha section lift variables {R : Type v} [comm_ring R] (f : α → R) /-- A helper to implement `lift`. This is essentially `free_comm_monoid.lift`, but this does not currently exist. -/ private def lift_to_multiset : (α → R) ≃ (multiplicative (multiset α) →* R) := { to_fun := λ f, { to_fun := λ s, (s.to_add.map f).prod, map_mul' := λ x y, calc _ = multiset.prod ((multiset.map f x) + (multiset.map f y)) : by {congr' 1, exact multiset.map_add _ _ _} ... = _ : multiset.prod_add _ _, map_one' := rfl}, inv_fun := λ F x, F (multiplicative.of_add ({x} : multiset α)), left_inv := λ f, funext $ λ x, show (multiset.map f {x}).prod = _, by simp, right_inv := λ F, monoid_hom.ext $ λ x, let F' := F.to_additive'', x' := x.to_add in show (multiset.map (λ a, F' {a}) x').sum = F' x', begin rw [←multiset.map_map, ←add_monoid_hom.map_multiset_sum], exact F.congr_arg (multiset.sum_map_singleton x'), end } /-- Lift a map `α → R` to a additive group homomorphism `free_comm_ring α → R`. For a version producing a bundled homomorphism, see `lift_hom`. -/ def lift : (α → R) ≃ (free_comm_ring α →+* R) := equiv.trans lift_to_multiset free_abelian_group.lift_monoid @[simp] lemma lift_of (x : α) : lift f (of x) = f x := (free_abelian_group.lift.of _ _).trans $ mul_one _ @[simp] lemma lift_comp_of (f : free_comm_ring α →+* R) : lift (f ∘ of) = f := ring_hom.ext $ λ x, free_comm_ring.induction_on x (by rw [ring_hom.map_neg, ring_hom.map_one, f.map_neg, f.map_one]) (lift_of _) (λ x y ihx ihy, by rw [ring_hom.map_add, f.map_add, ihx, ihy]) (λ x y ihx ihy, by rw [ring_hom.map_mul, f.map_mul, ihx, ihy]) @[ext] lemma hom_ext ⦃f g : free_comm_ring α →+* R⦄ (h : ∀ x, f (of x) = g (of x)) : f = g := lift.symm.injective (funext h) end lift variables {β : Type v} (f : α → β) /-- A map `f : α → β` produces a ring homomorphism `free_comm_ring α →+* free_comm_ring β`. -/ def map : free_comm_ring α →+* free_comm_ring β := lift $ of ∘ f @[simp] lemma map_of (x : α) : map f (of x) = of (f x) := lift_of _ _ /-- `is_supported x s` means that all monomials showing up in `x` have variables in `s`. -/ def is_supported (x : free_comm_ring α) (s : set α) : Prop := x ∈ subring.closure (of '' s) section is_supported variables {x y : free_comm_ring α} {s t : set α} theorem is_supported_upwards (hs : is_supported x s) (hst : s ⊆ t) : is_supported x t := subring.closure_mono (set.monotone_image hst) hs theorem is_supported_add (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x + y) s := subring.add_mem _ hxs hys theorem is_supported_neg (hxs : is_supported x s) : is_supported (-x) s := subring.neg_mem _ hxs theorem is_supported_sub (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x - y) s := subring.sub_mem _ hxs hys theorem is_supported_mul (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x * y) s := subring.mul_mem _ hxs hys theorem is_supported_zero : is_supported 0 s := subring.zero_mem _ theorem is_supported_one : is_supported 1 s := subring.one_mem _ theorem is_supported_int {i : ℤ} {s : set α} : is_supported ↑i s := int.induction_on i is_supported_zero (λ i hi, by rw [int.cast_add, int.cast_one]; exact is_supported_add hi is_supported_one) (λ i hi, by rw [int.cast_sub, int.cast_one]; exact is_supported_sub hi is_supported_one) end is_supported /-- The restriction map from `free_comm_ring α` to `free_comm_ring s` where `s : set α`, defined by sending all variables not in `s` to zero. -/ def restriction (s : set α) [decidable_pred (∈ s)] : free_comm_ring α →+* free_comm_ring s := lift (λ p, if H : p ∈ s then of (⟨p, H⟩ : s) else 0) section restriction variables (s : set α) [decidable_pred (∈ s)] (x y : free_comm_ring α) @[simp] lemma restriction_of (p) : restriction s (of p) = if H : p ∈ s then of ⟨p, H⟩ else 0 := lift_of _ _ end restriction theorem is_supported_of {p} {s : set α} : is_supported (of p) s ↔ p ∈ s := suffices is_supported (of p) s → p ∈ s, from ⟨this, λ hps, subring.subset_closure ⟨p, hps, rfl⟩⟩, assume hps : is_supported (of p) s, begin haveI := classical.dec_pred s, have : ∀ x, is_supported x s → ∃ (n : ℤ), lift (λ a, if a ∈ s then (0 : ℤ[X]) else polynomial.X) x = n, { intros x hx, refine subring.in_closure.rec_on hx _ _ _ _, { use 1, rw [ring_hom.map_one], norm_cast }, { use -1, rw [ring_hom.map_neg, ring_hom.map_one, int.cast_neg, int.cast_one] }, { rintros _ ⟨z, hzs, rfl⟩ _ _, use 0, rw [ring_hom.map_mul, lift_of, if_pos hzs, zero_mul], norm_cast }, { rintros x y ⟨q, hq⟩ ⟨r, hr⟩, refine ⟨q+r, _⟩, rw [ring_hom.map_add, hq, hr], norm_cast } }, specialize this (of p) hps, rw [lift_of] at this, split_ifs at this, { exact h }, exfalso, apply ne.symm int.zero_ne_one, rcases this with ⟨w, H⟩, rw ←polynomial.C_eq_int_cast at H, have : polynomial.X.coeff 1 = (polynomial.C ↑w).coeff 1, by rw H, rwa [polynomial.coeff_C, if_neg (one_ne_zero : 1 ≠ 0), polynomial.coeff_X, if_pos rfl] at this end theorem map_subtype_val_restriction {x} (s : set α) [decidable_pred (∈ s)] (hxs : is_supported x s) : map (subtype.val : s → α) (restriction s x) = x := begin refine subring.in_closure.rec_on hxs _ _ _ _, { rw ring_hom.map_one, refl }, { rw [ring_hom.map_neg, ring_hom.map_neg, ring_hom.map_one], refl }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [ring_hom.map_mul, restriction_of, dif_pos hps, ring_hom.map_mul, map_of, ih] }, { intros x y ihx ihy, rw [ring_hom.map_add, ring_hom.map_add, ihx, ihy] } end theorem exists_finite_support (x : free_comm_ring α) : ∃ s : set α, set.finite s ∧ is_supported x s := free_comm_ring.induction_on x ⟨∅, set.finite_empty, is_supported_neg is_supported_one⟩ (λ p, ⟨{p}, set.finite_singleton p, is_supported_of.2 $ set.mem_singleton _⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, hfs.union hft, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, hfs.union hft, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) theorem exists_finset_support (x : free_comm_ring α) : ∃ s : finset α, is_supported x ↑s := let ⟨s, hfs, hxs⟩ := exists_finite_support x in ⟨hfs.to_finset, by rwa set.finite.coe_to_finset⟩ end free_comm_ring namespace free_ring open function variable (α) /-- The canonical ring homomorphism from the free ring generated by `α` to the free commutative ring generated by `α`. -/ def to_free_comm_ring {α} : free_ring α →+* free_comm_ring α := free_ring.lift free_comm_ring.of instance : has_coe (free_ring α) (free_comm_ring α) := ⟨to_free_comm_ring⟩ /-- The natural map `free_ring α → free_comm_ring α`, as a `ring_hom`. -/ def coe_ring_hom : free_ring α →+* free_comm_ring α := to_free_comm_ring @[simp, norm_cast] protected lemma coe_zero : ↑(0 : free_ring α) = (0 : free_comm_ring α) := rfl @[simp, norm_cast] protected lemma coe_one : ↑(1 : free_ring α) = (1 : free_comm_ring α) := rfl variable {α} @[simp] protected lemma coe_of (a : α) : ↑(free_ring.of a) = free_comm_ring.of a := free_ring.lift_of _ _ @[simp, norm_cast] protected lemma coe_neg (x : free_ring α) : ↑(-x) = -(x : free_comm_ring α) := (free_ring.lift _).map_neg _ @[simp, norm_cast] protected lemma coe_add (x y : free_ring α) : ↑(x + y) = (x : free_comm_ring α) + y := (free_ring.lift _).map_add _ _ @[simp, norm_cast] protected lemma coe_sub (x y : free_ring α) : ↑(x - y) = (x : free_comm_ring α) - y := (free_ring.lift _).map_sub _ _ @[simp, norm_cast] protected lemma coe_mul (x y : free_ring α) : ↑(x * y) = (x : free_comm_ring α) * y := (free_ring.lift _).map_mul _ _ variable (α) protected lemma coe_surjective : surjective (coe : free_ring α → free_comm_ring α) := λ x, begin apply free_comm_ring.induction_on x, { use -1, refl }, { intro x, use free_ring.of x, refl }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x + y, exact (free_ring.lift _).map_add _ _ }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x * y, exact (free_ring.lift _).map_mul _ _ } end lemma coe_eq : (coe : free_ring α → free_comm_ring α) = @functor.map free_abelian_group _ _ _ (λ (l : list α), (l : multiset α)) := funext $ λ x, free_abelian_group.lift.unique _ _ $ λ L, by { simp_rw [free_abelian_group.lift.of, (∘)], exact free_monoid.rec_on L rfl (λ hd tl ih, by { rw [(free_monoid.lift _).map_mul, free_monoid.lift_eval_of, ih], refl }) } /-- If α has size at most 1 then the natural map from the free ring on `α` to the free commutative ring on `α` is an isomorphism of rings. -/ def subsingleton_equiv_free_comm_ring [subsingleton α] : free_ring α ≃+* free_comm_ring α := ring_equiv.of_bijective (coe_ring_hom _) begin have : (coe_ring_hom _ : free_ring α → free_comm_ring α) = (functor.map_equiv free_abelian_group (multiset.subsingleton_equiv α)) := coe_eq α, rw this, apply equiv.bijective, end instance [subsingleton α] : comm_ring (free_ring α) := { mul_comm := λ x y, by { rw [← (subsingleton_equiv_free_comm_ring α).symm_apply_apply (y * x), ((subsingleton_equiv_free_comm_ring α)).map_mul, mul_comm, ← ((subsingleton_equiv_free_comm_ring α)).map_mul, (subsingleton_equiv_free_comm_ring α).symm_apply_apply], }, .. free_ring.ring α } end free_ring /-- The free commutative ring on `α` is isomorphic to the polynomial ring over ℤ with variables in `α` -/ def free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ := ring_equiv.of_hom_inv (free_comm_ring.lift $ (λ a, mv_polynomial.X a : α → mv_polynomial α ℤ)) (mv_polynomial.eval₂_hom (int.cast_ring_hom (free_comm_ring α)) free_comm_ring.of) (by { ext, simp }) (by ext; simp) /-- The free commutative ring on the empty type is isomorphic to `ℤ`. -/ def free_comm_ring_pempty_equiv_int : free_comm_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.is_empty_ring_equiv _ pempty) /-- The free commutative ring on a type with one term is isomorphic to `ℤ[X]`. -/ def free_comm_ring_punit_equiv_polynomial_int : free_comm_ring punit.{u+1} ≃+* ℤ[X] := (free_comm_ring_equiv_mv_polynomial_int _).trans (mv_polynomial.punit_alg_equiv ℤ).to_ring_equiv open free_ring /-- The free ring on the empty type is isomorphic to `ℤ`. -/ def free_ring_pempty_equiv_int : free_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_pempty_equiv_int /-- The free ring on a type with one term is isomorphic to `ℤ[X]`. -/ def free_ring_punit_equiv_polynomial_int : free_ring punit.{u+1} ≃+* ℤ[X] := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_punit_equiv_polynomial_int
1323a43d883af68581b0a7c98a2a6af082f91d23
54deab7025df5d2df4573383df7e1e5497b7a2c2
/data/list/basic.lean
41e9315d9e661dfbd5930befcdb9e4fd2f2971dd
[ "Apache-2.0" ]
permissive
HGldJ1966/mathlib
f8daac93a5b4ae805cfb0ecebac21a9ce9469009
c5c5b504b918a6c5e91e372ee29ed754b0513e85
refs/heads/master
1,611,340,395,683
1,503,040,489,000
1,503,040,489,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
39,410
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn Basic properties of lists. -/ import logic.basic data.nat.basic data.option open function nat namespace list universes u v w variables {α : Type u} {β : Type v} {γ : Type w} @[simp] theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ []. theorem head_eq_of_cons_eq {α : Type} {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) theorem tail_eq_of_cons_eq {α : Type} {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) theorem cons_inj {α : Type} {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe /- append -/ theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_foldl (f : α → β → α) (a : α) (s t : list β) : foldl f a (s ++ t) = foldl f (foldl f a s) t := by {revert a, induction s with b s H, exact λ_, rfl, intros, simp [foldl], rw H _} theorem append_foldr (f : α → β → β) (a : β) (s t : list α) : foldr f a (s ++ t) = foldr f (foldr f a t) s := by {revert a, induction s with b s H, exact λ_, rfl, intros, simp [foldr], rw H _} /- repeat take drop -/ def split_at : ℕ → list α → list α × list α | 0 a := ([], a) | (succ n) [] := ([], []) | (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r) @[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l) | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := by simp [split_at, split_at_eq_take_drop n xs] @[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := by simp [take_append_drop n xs] -- TODO(Leo): cleanup proof after arith dec proc theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂ | [] [] t₁ t₂ h hl := ⟨rfl, h⟩ | (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl | [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm | (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap, let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩ theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ := (append_inj h hl).left theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ := (append_inj h hl).right theorem append_right_inj {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ := append_inj h $ @nat.add_right_cancel _ (length t₁) _ $ let hap := congr_arg length h in by simp at hap; rwa [← hl] at hap /- concat -/ def concat : list α → α → list α | [] a := [a] | (b::l) a := b :: concat l a attribute [simp] concat @[simp] theorem concat_nil (a : α) : concat [] a = [a] := rfl @[simp] theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl @[simp] theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := by induction l; intro h; contradiction @[simp] theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by induction l₁ with b l₁ ih; [simp, simp [ih]] @[simp] lemma concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp [*, concat] @[simp] lemma length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) := by simp [succ_eq_add_one] theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by induction l₂ with b l₂ ih; simp /- reverse -/ @[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl local attribute [simp] reverse_core @[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a := have aux : ∀ l₁ l₂, reverse_core l₁ (concat l₂ a) = concat (reverse_core l₁ l₂) a, by intros l₁; induction l₁; intros; rsimp, aux l nil @[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl @[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) := by induction s; simp [*] @[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l := by induction l; simp [*] theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) := by simp @[simp] theorem length_reverse (l : list α) : length (reverse l) = length l := by induction l; simp [*] @[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) := by induction l; simp [*] /- last -/ @[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ := by {induction l; intros, contradiction, simp [*], reflexivity} @[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := begin induction l with hd tl ih; rsimp, have haux : tl ++ [a] ≠ [], {apply append_ne_nil_of_ne_nil_right, contradiction}, simp [*] end theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a := by simp [*] @[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl @[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) : last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ /- head and tail -/ @[simp] theorem head_cons [h : inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl @[simp] theorem tail_nil : tail (@nil α) = [] := rfl @[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl @[simp] theorem head_append [h : inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s := by {induction s, contradiction, simp} theorem cons_head_tail [h : inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := by {induction l, contradiction, simp} /- map -/ lemma map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) := by induction l; simp [*] theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by induction l; simp [*] @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l := by revert a; induction l; intros; simp [*, foldl] @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l := by revert a; induction l; intros; simp [*, foldr] theorem foldl_hom (f : α → β) (g : α → γ → α) (g' : β → γ → β) (a : α) (h : ∀a x, f (g a x) = g' (f a) x) (l : list γ) : f (foldl g a l) = foldl g' (f a) l := by revert a; induction l; intros; simp [*, foldl] theorem foldr_hom (f : α → β) (g : γ → α → α) (g' : γ → β → β) (a : α) (h : ∀x a, f (g x a) = g' x (f a)) (l : list γ) : f (foldr g a l) = foldr g' (f a) l := by revert a; induction l; intros; simp [*, foldr] /- mem -/ theorem eq_nil_of_forall_not_mem : ∀ {l : list α}, (∀ a, a ∉ l) → l = nil | [] := assume h, rfl | (b :: l') := assume h, absurd (mem_cons_self b l') (h b) theorem mem_singleton {a b : α} : a ∈ [b] → a = b := assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, this) (assume : a ∈ [], absurd this (not_mem_nil a)) @[simp] theorem mem_singleton_iff (a b : α) : a ∈ [b] ↔ a = b := iff.intro mem_singleton (begin intro h, simp [h] end) theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l := assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl) (assume : a = b, begin subst a, exact binl end) (assume : a ∈ l, this) theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s++t := mt mem_append.1 $ not_or_of_not_and_not ⟨h₁, h₂⟩ theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l | (b::l) _ := zero_lt_succ _ theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ (a::t) := begin induction l with b l ih; simp at h; cases h with h h, { subst h, exact ⟨[], l, rfl⟩ }, { cases ih h with s e, cases e with t e, subst l, exact ⟨b::s, t, rfl⟩ } end theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l := or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r) theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b := assume nin aeqb, absurd (or.inl aeqb) nin theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l := assume nin nainl, absurd (or.inr nainl) nin theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l := assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2)) theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l := assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p) @[simp] theorem mem_reverse (a : α) (l : list α) : a ∈ reverse l ↔ a ∈ l := by induction l; simp [*]; rw mem_append_eq theorem mem_map (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l := begin induction l with b l' ih, {simp at h, contradiction }, {simp, simp at h, cases h with h h, {simp [*]}, {exact or.inr (ih h)}} end theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b := begin induction l with c l' ih, {simp at h, contradiction}, {cases (eq_or_mem_of_mem_cons h) with h h, {existsi c, simp [h]}, {cases ih h with a ha, cases ha with ha₁ ha₂, existsi a, simp [*] }} end theorem mem_map_iff {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := ⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map f la⟩ theorem mem_join_iff {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l | [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩ | (c :: L) := by simp [join, @mem_join_iff L]; exact ⟨λh, match h with | or.inl ac := ⟨c, ac, or.inl rfl⟩ | or.inr ⟨l, al, lL⟩ := ⟨l, al, or.inr lL⟩ end, λ⟨l, al, o⟩, o.elim (λ lc, by rw lc at al; exact or.inl al) (λlL, or.inr ⟨l, al, lL⟩)⟩ theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l := mem_join_iff.1 theorem mem_join {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L := mem_join_iff.2 ⟨l, lL, al⟩ lemma mem_bind_iff {b : β} {l : list α} {f : α → list β} : b ∈ bind l f ↔ ∃ a ∈ l, b ∈ f a := iff.trans mem_join_iff ⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩, λ ⟨a, al, bfa⟩, ⟨f a, mem_map _ al, bfa⟩⟩ lemma exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ bind l f → ∃ a ∈ l, b ∈ f a := mem_bind_iff.1 lemma mem_bind {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ bind l f := mem_bind_iff.2 ⟨a, al, h⟩ /- list subset -/ theorem subset_app_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_app_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_right _ _ theorem cons_subset_of_subset_of_mem {a : α} {l m : list α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m := λ b, or_imp_iff_and_imp.2 ⟨λ e, e.symm ▸ ainm, @lsubm _⟩ theorem app_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l := λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _) theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = [] | [] s := rfl | (a::l) s := false.elim $ s $ mem_cons_self a l /- sublists -/ @[simp] theorem nil_sublist : Π (l : list α), [] <+ l | [] := sublist.slnil | (a :: l) := sublist.cons _ _ a (nil_sublist l) @[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l | [] := sublist.slnil | (a :: l) := sublist.cons2 _ _ a (sublist.refl l) @[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ := sublist.rec_on h₂ (λ_ s, s) (λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁)) (λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁ (λ_, nil_sublist _) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl) l₁ h₁ @[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l := sublist.cons _ _ _ (sublist.refl l) theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ := sublist.trans (sublist_cons a l₁) theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ := sublist.cons2 _ _ _ s @[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂ | [] l₂ := nil_sublist _ | (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂) @[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂ | [] l₂ := sublist.refl _ | (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂) theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ := sublist.cons _ _ _ theorem sublist_app_of_sublist_left (l l₁ l₂ : list α) (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_app_of_sublist_right (l l₁ l₂ : list α) (s : l <+ l₂) : l <+ l₁++l₂ := s.trans $ sublist_append_right _ _ theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂ | ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s | ._ (sublist.cons2 ._ ._ a s) := s theorem subset_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (subset_of_sublist s h) | ._ ._ (sublist.cons2 l₁ l₂ a s) b h := match eq_or_mem_of_mem_cons h with | or.inl h := h ▸ mem_cons_self _ _ | or.inr h := mem_cons_of_mem _ (subset_of_sublist s h) end theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] := eq_nil_of_subset_nil $ subset_of_sublist s theorem eq_nil_of_map_eq_nil {f : α → β} {l :list α} (h : map f l = nil) : l = nil := eq_nil_of_length_eq_zero (begin rw [← length_map f l], simp [h] end) theorem eq_of_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := let ⟨a, _, e⟩ := exists_of_mem_map h in e.symm /- index_of -/ section index_of variable [decidable_eq α] @[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 := assume e, if_pos e @[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 := index_of_cons_eq _ rfl @[simp] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) := assume n, if_neg n theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l := begin induction l with b l ih; simp [not_or_iff, -add_comm], by_cases a = b with h; simp [h, -add_comm], { intro, contradiction }, { rw ← ih, exact ⟨succ_inj, congr_arg _⟩ } end @[simp] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l := index_of_eq_length.2 theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l := begin induction l with b l ih; simp [-add_comm, index_of_cons], by_cases a = b with h; simp [h, -add_comm, zero_le], exact succ_le_succ ih end theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l := ⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al, λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩ end index_of /- nth element -/ theorem nth_le_nth : Π (l : list α) (n h), nth l n = some (nth_le l n h) | [] n h := absurd h (not_lt_zero n) | (a :: l) 0 h := rfl | (a :: l) (n+1) h := nth_le_nth l n _ theorem nth_ge_len : Π (l : list α) (n), n ≥ length l → nth l n = none | [] n h := rfl | (a :: l) 0 h := absurd h (not_lt_zero _) | (a :: l) (n+1) h := nth_ge_len l n (le_of_succ_le_succ h) theorem ext : Π {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂ | [] [] h := rfl | (a::l₁) [] h := by have h0 := h 0; contradiction | [] (a'::l₂) h := by have h0 := h 0; contradiction | (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa; simp [*, ext (λn, h (n+1))] theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ := ext $ λn, if h₁ : n < length l₁ then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])] else let h₁ := le_of_not_gt h₁ in by rw [nth_ge_len _ _ h₁, nth_ge_len _ _ (by rwa [← hl])] @[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a | (b::l) h := by by_cases a = b with h'; simp * @[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a := by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)] theorem nth_le_reverse_aux1 : Π (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2 | [] r i := λh1 h2, rfl | (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, by simp); exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2) theorem nth_le_reverse_aux2 : Π (l r : list α) (i : nat) (h1) (h2), nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2 | [] r i h1 h2 := absurd h2 (not_lt_zero _) | (a :: l) r 0 h1 h2 := begin have aux := nth_le_reverse_aux1 l (a :: r) 0, rw zero_add at aux, exact aux _ (zero_lt_succ _) end | (a :: l) r (i+1) h1 h2 := begin have aux := nth_le_reverse_aux2 l (a :: r) i, have heq := calc length (a :: l) - 1 - (i + 1) = length l - (1 + i) : by rw add_comm; refl ... = length l - 1 - i : by rw nat.sub_sub, rw [← heq] at aux, apply aux end @[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) : nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 := nth_le_reverse_aux2 _ _ _ _ _ def to_array (l : list α) : array α l.length := {data := λ v, l.nth_le v.1 v.2} def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget attribute [simp] inth /- take, drop -/ @[simp] theorem take_zero : ∀ (l : list α), take 0 l = [] := begin intros, reflexivity end @[simp] theorem take_nil : ∀ n, take n [] = ([] : list α) | 0 := rfl | (n+1) := rfl theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl theorem take_all : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_all end theorem take_all_of_ge : ∀ {n} {l : list α}, n ≥ length l → take n l = l | 0 [] h := rfl | 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _)) | (n+1) [] h := rfl | (n+1) (a::l) h := begin change a :: take n l = a :: l, rw [take_all_of_ge (le_of_succ_le_succ h)] end theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l | n 0 l := by rw [min_zero, take_zero, take_nil] | 0 m l := by simp | (succ n) (succ m) nil := by simp | (succ n) (succ m) (a::l) := by simp [min_succ_succ, take_take] /- take_while -/ def take_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: take_while l else [] /- find -/ def find (p : α → Prop) [decidable_pred p] : list α → option α | [] := none | (a::l) := if p a then some a else find l def find_indexes_aux (p : α → Prop) [decidable_pred p] : list α → nat → list nat | [] n := [] | (a::l) n := let t := find_indexes_aux l (succ n) in if p a then n :: t else t def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat := find_indexes_aux p l 0 def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a) /- foldl, foldr, scanl, scanr -/ attribute [simp] foldl foldr @[simp] lemma foldr_eta : ∀ (l : list α), foldr cons [] l = l | [] := rfl | (x::l) := by simp [foldr_eta l] def scanl (f : α → β → α) : α → list β → list α | a [] := [a] | a (b::l) := a :: scanl (f a b) l def scanr_aux (f : α → β → β) (b : β) : list α → β × list β | [] := (b, []) | (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l') def scanr (f : α → β → β) (b : β) (l : list α) : list β := let (b', l') := scanr_aux f b l in b' :: l' @[simp] lemma scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl @[simp] lemma scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α), scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l) | a [] := rfl | a (x::l) := let t := scanr_aux_cons x l in by simp [scanr, scanr_aux] at t; simp [scanr, scanr_aux, t] @[simp] lemma scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : scanr f b (a::l) = foldr f b (a::l) :: scanr f b l := by simp [scanr] /- sum -/ def sum [has_add α] [has_zero α] : list α → α := foldl (+) 0 /- filter -/ @[simp] theorem filter_subset {p : α → Prop} [h : decidable_pred p] (l : list α) : filter p l ⊆ l := subset_of_sublist $ filter_sublist l theorem of_mem_filter {p : α → Prop} [h : decidable_pred p] {a : α} : ∀ {l}, a ∈ filter p l → p a | [] ain := absurd ain (not_mem_nil a) | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, begin simp [pb] at ain, assumption end, or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, begin rw [← this] at pb, exact pb end) (assume : a ∈ filter p l, of_mem_filter this) else begin simp [pb] at ain, exact (of_mem_filter ain) end theorem mem_of_mem_filter {p : α → Prop} [h : decidable_pred p] {a : α} {l} (h : a ∈ filter p l) : a ∈ l := filter_subset l h theorem mem_filter_of_mem {p : α → Prop} [h : decidable_pred p] {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | [] ain pa := absurd ain (not_mem_nil a) | (b::l) ain pa := if pb : p b then or.elim (eq_or_mem_of_mem_cons ain) (assume : a = b, by simp [pb, this]) (assume : a ∈ l, begin simp [pb], exact (mem_cons_of_mem _ (mem_filter_of_mem this pa)) end) else or.elim (eq_or_mem_of_mem_cons ain) (assume : a = b, begin simp [this] at pa, contradiction end) --absurd (this ▸ pa) pb) (assume : a ∈ l, by simp [pa, pb, mem_filter_of_mem this]) @[simp] lemma span_eq_take_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), span p l = (take_while p l, drop_while p l) | [] := rfl | (a::l) := by by_cases p a with pa; simp [span, take_while, drop_while, pa, span_eq_take_drop l] @[simp] lemma take_while_append_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), take_while p l ++ drop_while p l = l | [] := rfl | (a::l) := by by_cases p a with pa; simp [take_while, drop_while, pa, take_while_append_drop l] /- count -/ section count variable [decidable_eq α] def count (a : α) : list α → nat | [] := 0 | (x::xs) := if a = x then succ (count xs) else count xs @[simp] theorem count_nil (a : α) : count a [] = 0 := rfl theorem count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl theorem count_cons' (a b : α) (l : list α) : count a (b :: l) = count a l + (if a = b then 1 else 0) := decidable.by_cases (assume : a = b, begin rw [count_cons, if_pos this, if_pos this] end) (assume : a ≠ b, begin rw [count_cons, if_neg this, if_neg this], reflexivity end) @[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h theorem count_cons_ge_count (a b : α) (l : list α) : count a (b :: l) ≥ count a l := decidable.by_cases (assume : a = b, begin subst b, rw count_cons_self, apply le_succ end) (assume : a ≠ b, begin rw (count_cons_of_ne this), apply le_refl end) -- TODO(Jeremy): without the reflexivity, this yields the goal "1 = 1". the first is from has_one, -- the second is succ 0. Make sure the simplifier can eventually handle this. theorem count_singleton (a : α) : count a [a] = 1 := by simp @[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ | [] l₂ := begin rw [nil_append, count_nil, zero_add] end | (b::l₁) l₂ := decidable.by_cases (assume : a = b, by rw [←this, cons_append, count_cons_self, count_cons_self, succ_add, count_append]) (assume : a ≠ b, by rw [cons_append, count_cons_of_ne this, count_cons_of_ne this, count_append]) @[simp] theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by rw [concat_eq_append, count_append, count_singleton] theorem mem_of_count_pos : ∀ {a : α} {l : list α}, count a l > 0 → a ∈ l | a [] h := absurd h (lt_irrefl _) | a (b::l) h := decidable.by_cases (assume : a = b, begin subst b, apply mem_cons_self end) (assume : a ≠ b, have count a l > 0, begin rw [count_cons_of_ne this] at h, exact h end, have a ∈ l, from mem_of_count_pos this, show a ∈ b::l, from mem_cons_of_mem _ this) theorem count_pos_of_mem : ∀ {a : α} {l : list α}, a ∈ l → count a l > 0 | a [] h := absurd h (not_mem_nil _) | a (b::l) h := or.elim h (assume : a = b, begin subst b, rw count_cons_self, apply zero_lt_succ end) (assume : a ∈ l, calc count a (b::l) ≥ count a l : count_cons_ge_count _ _ _ ... > 0 : count_pos_of_mem this) theorem mem_iff_count_pos (a : α) (l : list α) : a ∈ l ↔ count a l > 0 := iff.intro count_pos_of_mem mem_of_count_pos @[simp] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := have ∀ n, count a l = n → count a l = 0, begin intro n, cases n, { intro this, exact this }, intro this, exact absurd (mem_of_count_pos (begin rw this, exact dec_trivial end)) h end, this (count a l) rfl theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := assume : a ∈ l, have count a l > 0, from count_pos_of_mem this, show false, begin rw h at this, exact nat.not_lt_zero _ this end end count /- prefix, suffix, infix -/ def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂ def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂ def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂ infix ` <+: `:50 := is_prefix infix ` <:+ `:50 := is_suffix infix ` <:+: `:50 := is_infix lemma prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩ lemma suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩ lemma infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ lemma prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩ lemma suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩ lemma infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨[], t, h⟩ lemma infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨t, [], by simp [h]⟩ lemma infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l lemma sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ := λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _) lemma length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ := length_le_of_sublist $ sublist_of_infix s lemma eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] := eq_nil_of_sublist_nil $ sublist_of_infix s lemma eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] := eq_nil_of_infix_nil $ infix_of_prefix s lemma eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] := eq_nil_of_infix_nil $ infix_of_suffix s lemma infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ := ⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩, λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩ def inits : list α → list (list α) | [] := [[]] | (a::l) := [] :: map (λt, a::t) (inits l) attribute [simp] inits local infixr :: := list.cons -- temporary hack to fix overload issue @[simp] lemma mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := by simp; exact ⟨λh, by rw h; exact prefix_refl [], eq_nil_of_prefix_nil⟩ | s (a::t) := by simp; exact ⟨λo, match s, o with | ._, or.inl rfl := ⟨_, rfl⟩ | s, or.inr mm := let ⟨r, hr, hs⟩ := exists_of_mem_map mm, ⟨s, ht⟩ := (mem_inits _ _).1 hr in by rw [← hs, ← ht]; exact ⟨s, rfl⟩ end, λmi, match s, mi with | [], ⟨._, rfl⟩ := or.inl rfl | (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba st, or.inr $ by rw ba; exact mem_map _ ((mem_inits _ _).2 ⟨_, st⟩) end⟩ def tails : list α → list (list α) | [] := [[]] | (a::l) := (a::l) :: tails l attribute [simp] tails @[simp] lemma mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a::t) := by simp [mem_tails s t]; exact show s <:+ t ∨ s = a :: t ↔ s <:+ a :: t, from ⟨λo, match s, t, o with | s, ._, or.inl ⟨l, rfl⟩ := ⟨a::l, rfl⟩ | ._, t, or.inr rfl := suffix_refl _ end, λe, match s, t, e with | ._, t, ⟨[], rfl⟩ := or.inr rfl | s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inl ⟨l, lt⟩) end⟩ def sublists_aux : list α → (list α → list β → list β) → list β | [] f := [] | (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r))) def sublists (l : list α) : list (list α) := [] :: sublists_aux l cons lemma sublists_aux_eq_foldl : ∀ (l : list α) {β : Type u} (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons) | [] β f := rfl | (a::l) β f := suffices ∀ t, foldr (λ ys r, f ys (f (a :: ys) r)) [] t = foldr f [] (t.foldr (λ ys r, ys :: (a :: ys) :: r) nil), by simp [sublists_aux]; rw [sublists_aux_eq_foldl l, sublists_aux_eq_foldl l (λ ys r, ys :: (a :: ys) :: r), this], λt, by induction t; simp; simp [ih_1] lemma sublists_aux_cons_cons (l : list α) (a : α) : sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) := by rw [← sublists_aux_eq_foldl]; refl @[simp] lemma mem_sublists (s t : list α) : s ∈ sublists t ↔ s <+ t := by simp [sublists]; exact ⟨λm, let good := λ (l : list (list α)), ∀ s ∈ l, s <+ t in suffices ∀ l (f : list α → list (list α) → list (list α)), (∀ {x y}, x <+ l → good y → good (f x y)) → l <+ t → good (sublists_aux l f), from or.elim m (λe, by rw e; apply nil_sublist) (this t cons (λ x y hx hy s m, by exact or.elim m (λe, by rw e; exact hx) (hy s)) (sublist.refl _) s), begin intro l; induction l with a l IH; intros f al sl x m, exact false.elim m, refine al (cons_sublist_cons a (nil_sublist _)) _ _ m, exact λs hs, IH _ (λx y hx hy, al (sublist_cons_of_sublist _ hx) (al (cons_sublist_cons _ hx) hy)) (sublist_of_cons_sublist sl) _ hs end, λsl, begin have this : ∀ {a : α} {y t}, y ∈ t → y ∈ foldr (λ ys r, ys :: (a :: ys) :: r) nil t ∧ a :: y ∈ foldr (λ ys r, ys :: (a :: ys) :: r) nil t, { intros a y t yt, induction t with x t IH, exact absurd yt (not_mem_nil _), simp, simp at yt, cases yt with yx yt, { rw yx, exact ⟨or.inl rfl, or.inr $ or.inl rfl⟩ }, { cases IH yt with h1 h2, exact ⟨or.inr $ or.inr h1, or.inr $ or.inr h2⟩ } }, induction sl with l₁ l₂ a sl IH l₁ l₂ a sl IH, exact or.inl rfl, { refine or.imp_right (λh, _) IH, rw sublists_aux_cons_cons, exact mem_cons_of_mem _ (this h).left }, { refine or.inr _, rw sublists_aux_cons_cons, simp, refine or.imp (λ(h : l₁ = []), by rw h) (λh, _) IH, exact (this h).right }, end⟩ instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂) | [] l₂ := is_true ⟨l₂, rfl⟩ | (a::l₁) [] := is_false $ λ⟨t, te⟩, list.no_confusion te | (a::l₁) (b::l₂) := if h : a = b then decidable_of_decidable_of_iff (decidable_prefix l₁ l₂) $ by rw [← h]; exact ⟨λ⟨t, te⟩, ⟨t, by rw [← te]; refl⟩, λ⟨t, te⟩, list.no_confusion te (λ_ te, ⟨t, te⟩)⟩ else is_false $ λ⟨t, te⟩, list.no_confusion te $ λh', absurd h' h -- Alternatively, use mem_tails instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂) | [] l₂ := is_true ⟨l₂, append_nil _⟩ | (a::l₁) [] := is_false $ λ⟨t, te⟩, absurd te $ append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h | l₁ l₂ := let len1 := length l₁, len2 := length l₂ in if hl : len1 ≤ len2 then if he : drop (len2 - len1) l₂ = l₁ then is_true $ ⟨take (len2 - len1) l₂, by rw [← he, take_append_drop]⟩ else is_false $ suffices length l₁ ≤ length l₂ → l₁ <:+ l₂ → drop (length l₂ - length l₁) l₂ = l₁, from λsuf, he (this hl suf), λ hl ⟨t, te⟩, and.right $ append_right_inj (eq.trans (take_append_drop (length l₂ - length l₁) l₂) te.symm) $ by simp; exact nat.sub_sub_self hl else is_false $ λ⟨t, te⟩, hl $ show length l₁ ≤ length l₂, by rw [← te, length_append]; apply nat.le_add_left instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂) | [] l₂ := is_true ⟨[], l₂, rfl⟩ | (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $ append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h | l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $ by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm; exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩ instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂) | [] l₂ := is_true $ nil_sublist _ | (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h | (a::l₁) (b::l₂) := if h : a = b then decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $ by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩ else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂) ⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with | a, l₁, sublist.cons ._ ._ ._ s', h := s' | ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h end⟩ /- transpose -/ def transpose_aux : list α → list (list α) → list (list α) | [] ls := ls | (a::i) [] := [a] :: transpose_aux i [] | (a::i) (l::ls) := (a::l) :: transpose_aux i ls def transpose : list (list α) → list (list α) | [] := [] | (l::ls) := transpose_aux l (transpose ls) /- permutations -/ def permutations_aux2 (t : α) (ts : list α) : list α → (list α → β) → list β → list α × list β | [] f r := (ts, r) | (y::ys) f r := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) r in (y :: us, f (t :: y :: us) :: zs) private def meas : list α × list α → ℕ × ℕ | (l, i) := (length l + length i, length l) local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas def permutations_aux.F : Π (x : list α × list α), (Π (y : list α × list α), y ≺ x → list (list α)) → list (list α) | ([], is) IH := [] | (t::ts, is) IH := have h1 : (ts, t :: is) ≺ (t :: ts, is), from show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is, length (t :: ts)), by rw nat.succ_add; exact prod.lex.right _ _ (lt_succ_self _), have h2 : (is, []) ≺ (t :: ts, is), from prod.lex.left _ _ _ (lt_add_of_pos_left _ (succ_pos _)), foldr (λy r, (permutations_aux2 t ts y id r).2) (IH (ts, t::is) h1) (is :: IH (is, []) h2) def permutations_aux : list α × list α → list (list α) := well_founded.fix (inv_image.wf meas (prod.lex_wf lt_wf lt_wf)) permutations_aux.F def permutations (l : list α) : list (list α) := l :: permutations_aux (l, []) def permutations_aux.eqn_1 (is : list α) : permutations_aux ([], is) = [] := well_founded.fix_eq _ _ _ def permutations_aux.eqn_2 (t : α) (ts is) : permutations_aux (t::ts, is) = foldr (λy r, (permutations_aux2 t ts y id r).2) (permutations_aux (ts, t::is)) (permutations is) := well_founded.fix_eq _ _ _ end list
2b250a3deaf87e531cc16ebdf5da7c1b8195c7df
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/data/num.lean
0209b937ddae5f9fe9d3e0dbc2d2de75167639ae
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,770
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.num Author: Leonardo de Moura -/ import data.bool tools.helper_tactics open bool eq.ops decidable helper_tactics namespace pos_num theorem succ_not_is_one (a : pos_num) : is_one (succ a) = ff := pos_num.induction_on a rfl (take n iH, rfl) (take n iH, rfl) theorem succ_one : succ one = bit0 one theorem succ_bit1 (a : pos_num) : succ (bit1 a) = bit0 (succ a) theorem succ_bit0 (a : pos_num) : succ (bit0 a) = bit1 a theorem ne_of_bit0_ne_bit0 {a b : pos_num} (H₁ : bit0 a ≠ bit0 b) : a ≠ b := assume H : a = b, absurd rfl (H ▸ H₁) theorem ne_of_bit1_ne_bit1 {a b : pos_num} (H₁ : bit1 a ≠ bit1 b) : a ≠ b := assume H : a = b, absurd rfl (H ▸ H₁) theorem pred_succ : ∀ (a : pos_num), pred (succ a) = a | one := rfl | (bit0 a) := by rewrite succ_bit0 | (bit1 a) := calc pred (succ (bit1 a)) = cond (is_one (succ a)) one (bit1 (pred (succ a))) : rfl ... = cond ff one (bit1 (pred (succ a))) : succ_not_is_one ... = bit1 (pred (succ a)) : rfl ... = bit1 a : pred_succ a section variables (a b : pos_num) theorem one_add_one : one + one = bit0 one theorem one_add_bit0 : one + (bit0 a) = bit1 a theorem one_add_bit1 : one + (bit1 a) = succ (bit1 a) theorem bit0_add_one : (bit0 a) + one = bit1 a theorem bit1_add_one : (bit1 a) + one = succ (bit1 a) theorem bit0_add_bit0 : (bit0 a) + (bit0 b) = bit0 (a + b) theorem bit0_add_bit1 : (bit0 a) + (bit1 b) = bit1 (a + b) theorem bit1_add_bit0 : (bit1 a) + (bit0 b) = bit1 (a + b) theorem bit1_add_bit1 : (bit1 a) + (bit1 b) = succ (bit1 (a + b)) theorem one_mul : one * a = a end theorem mul_one : ∀ a, a * one = a | one := rfl | (bit1 n) := calc bit1 n * one = bit0 (n * one) + one : rfl ... = bit0 n + one : mul_one n ... = bit1 n : bit0_add_one | (bit0 n) := calc bit0 n * one = bit0 (n * one) : rfl ... = bit0 n : mul_one n theorem decidable_eq [instance] : ∀ (a b : pos_num), decidable (a = b) | one one := inl rfl | one (bit0 b) := inr (λ H, pos_num.no_confusion H) | one (bit1 b) := inr (λ H, pos_num.no_confusion H) | (bit0 a) one := inr (λ H, pos_num.no_confusion H) | (bit0 a) (bit0 b) := match decidable_eq a b with | inl H₁ := inl (eq.rec_on H₁ rfl) | inr H₁ := inr (λ H, pos_num.no_confusion H (λ H₂, absurd H₂ H₁)) end | (bit0 a) (bit1 b) := inr (λ H, pos_num.no_confusion H) | (bit1 a) one := inr (λ H, pos_num.no_confusion H) | (bit1 a) (bit0 b) := inr (λ H, pos_num.no_confusion H) | (bit1 a) (bit1 b) := match decidable_eq a b with | inl H₁ := inl (eq.rec_on H₁ rfl) | inr H₁ := inr (λ H, pos_num.no_confusion H (λ H₂, absurd H₂ H₁)) end local notation a < b := (lt a b = tt) local notation a `≮`:50 b:50 := (lt a b = ff) theorem lt_one_right_eq_ff : ∀ a : pos_num, a ≮ one | one := rfl | (bit0 a) := rfl | (bit1 a) := rfl theorem lt_one_succ_eq_tt : ∀ a : pos_num, one < succ a | one := rfl | (bit0 a) := rfl | (bit1 a) := rfl theorem lt_of_lt_bit0_bit0 {a b : pos_num} (H : bit0 a < bit0 b) : a < b := H theorem lt_of_lt_bit0_bit1 {a b : pos_num} (H : bit1 a < bit0 b) : a < b := H theorem lt_of_lt_bit1_bit1 {a b : pos_num} (H : bit1 a < bit1 b) : a < b := H theorem lt_of_lt_bit1_bit0 {a b : pos_num} (H : bit0 a < bit1 b) : a < succ b := H theorem lt_bit0_bit0_eq_lt (a b : pos_num) : lt (bit0 a) (bit0 b) = lt a b := rfl theorem lt_bit1_bit1_eq_lt (a b : pos_num) : lt (bit1 a) (bit1 b) = lt a b := rfl theorem lt_bit1_bit0_eq_lt (a b : pos_num) : lt (bit1 a) (bit0 b) = lt a b := rfl theorem lt_bit0_bit1_eq_lt_succ (a b : pos_num) : lt (bit0 a) (bit1 b) = lt a (succ b) := rfl theorem lt_irrefl : ∀ (a : pos_num), a ≮ a | one := rfl | (bit0 a) := begin rewrite lt_bit0_bit0_eq_lt, apply lt_irrefl end | (bit1 a) := begin rewrite lt_bit1_bit1_eq_lt, apply lt_irrefl end theorem ne_of_lt_eq_tt : ∀ {a b : pos_num}, a < b → a = b → false | one ⌞one⌟ H₁ (eq.refl one) := absurd H₁ ff_ne_tt | (bit0 a) ⌞(bit0 a)⌟ H₁ (eq.refl (bit0 a)) := begin rewrite lt_bit0_bit0_eq_lt at H₁, apply (ne_of_lt_eq_tt H₁ (eq.refl a)) end | (bit1 a) ⌞(bit1 a)⌟ H₁ (eq.refl (bit1 a)) := begin rewrite lt_bit1_bit1_eq_lt at H₁, apply (ne_of_lt_eq_tt H₁ (eq.refl a)) end theorem lt_base : ∀ a : pos_num, a < succ a | one := rfl | (bit0 a) := begin rewrite [succ_bit0, lt_bit0_bit1_eq_lt_succ], apply lt_base end | (bit1 a) := begin rewrite [succ_bit1, lt_bit1_bit0_eq_lt], apply lt_base end theorem lt_step : ∀ {a b : pos_num}, a < b → a < succ b | one one H := rfl | one (bit0 b) H := rfl | one (bit1 b) H := rfl | (bit0 a) one H := absurd H ff_ne_tt | (bit0 a) (bit0 b) H := begin rewrite [succ_bit0, lt_bit0_bit1_eq_lt_succ, lt_bit0_bit0_eq_lt at H], apply (lt_step H) end | (bit0 a) (bit1 b) H := begin rewrite [succ_bit1, lt_bit0_bit0_eq_lt, lt_bit0_bit1_eq_lt_succ at H], exact H end | (bit1 a) one H := absurd H ff_ne_tt | (bit1 a) (bit0 b) H := begin rewrite [succ_bit0, lt_bit1_bit1_eq_lt, lt_bit1_bit0_eq_lt at H], exact H end | (bit1 a) (bit1 b) H := begin rewrite [succ_bit1, lt_bit1_bit0_eq_lt, lt_bit1_bit1_eq_lt at H], apply (lt_step H) end theorem lt_of_lt_succ_succ : ∀ {a b : pos_num}, succ a < succ b → a < b | one one H := absurd H ff_ne_tt | one (bit0 b) H := rfl | one (bit1 b) H := rfl | (bit0 a) one H := begin rewrite [succ_bit0 at H, succ_one at H, lt_bit1_bit0_eq_lt at H], apply (absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff a) H) end | (bit0 a) (bit0 b) H := by exact H | (bit0 a) (bit1 b) H := by exact H | (bit1 a) one H := begin rewrite [succ_bit1 at H, succ_one at H, lt_bit0_bit0_eq_lt at H], apply (absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff (succ a)) H) end | (bit1 a) (bit0 b) H := begin rewrite [succ_bit1 at H, succ_bit0 at H, lt_bit0_bit1_eq_lt_succ at H], rewrite lt_bit1_bit0_eq_lt, apply (lt_of_lt_succ_succ H) end | (bit1 a) (bit1 b) H := begin rewrite [lt_bit1_bit1_eq_lt, *succ_bit1 at H, lt_bit0_bit0_eq_lt at H], apply (lt_of_lt_succ_succ H) end theorem lt_succ_succ : ∀ {a b : pos_num}, a < b → succ a < succ b | one one H := absurd H ff_ne_tt | one (bit0 b) H := begin rewrite [succ_bit0, succ_one, lt_bit0_bit1_eq_lt_succ], apply lt_one_succ_eq_tt end | one (bit1 b) H := begin rewrite [succ_one, succ_bit1, lt_bit0_bit0_eq_lt], apply lt_one_succ_eq_tt end | (bit0 a) one H := absurd H ff_ne_tt | (bit0 a) (bit0 b) H := by exact H | (bit0 a) (bit1 b) H := by exact H | (bit1 a) one H := absurd H ff_ne_tt | (bit1 a) (bit0 b) H := begin rewrite [succ_bit1, succ_bit0, lt_bit0_bit1_eq_lt_succ, lt_bit1_bit0_eq_lt at H], apply (lt_succ_succ H) end | (bit1 a) (bit1 b) H := begin rewrite [lt_bit1_bit1_eq_lt at H, *succ_bit1, lt_bit0_bit0_eq_lt], apply (lt_succ_succ H) end theorem lt_of_lt_succ : ∀ {a b : pos_num}, succ a < b → a < b | one one H := absurd_of_eq_ff_of_eq_tt !lt_one_right_eq_ff H | one (bit0 b) H := rfl | one (bit1 b) H := rfl | (bit0 a) one H := absurd_of_eq_ff_of_eq_tt !lt_one_right_eq_ff H | (bit0 a) (bit0 b) H := by exact H | (bit0 a) (bit1 b) H := begin rewrite [succ_bit0 at H, lt_bit1_bit1_eq_lt at H, lt_bit0_bit1_eq_lt_succ], apply (lt_step H) end | (bit1 a) one H := absurd_of_eq_ff_of_eq_tt !lt_one_right_eq_ff H | (bit1 a) (bit0 b) H := begin rewrite [lt_bit1_bit0_eq_lt, succ_bit1 at H, lt_bit0_bit0_eq_lt at H], apply (lt_of_lt_succ H) end | (bit1 a) (bit1 b) H := begin rewrite [succ_bit1 at H, lt_bit0_bit1_eq_lt_succ at H, lt_bit1_bit1_eq_lt], apply (lt_of_lt_succ_succ H) end theorem lt_of_lt_succ_of_ne : ∀ {a b : pos_num}, a < succ b → a ≠ b → a < b | one one H₁ H₂ := absurd rfl H₂ | one (bit0 b) H₁ H₂ := rfl | one (bit1 b) H₁ H₂ := rfl | (bit0 a) one H₁ H₂ := begin rewrite [succ_one at H₁, lt_bit0_bit0_eq_lt at H₁], apply (absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₁) end | (bit0 a) (bit0 b) H₁ H₂ := begin rewrite [lt_bit0_bit0_eq_lt, succ_bit0 at H₁, lt_bit0_bit1_eq_lt_succ at H₁], apply (lt_of_lt_succ_of_ne H₁ (ne_of_bit0_ne_bit0 H₂)) end | (bit0 a) (bit1 b) H₁ H₂ := begin rewrite [succ_bit1 at H₁, lt_bit0_bit0_eq_lt at H₁, lt_bit0_bit1_eq_lt_succ], exact H₁ end | (bit1 a) one H₁ H₂ := begin rewrite [succ_one at H₁, lt_bit1_bit0_eq_lt at H₁], apply (absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₁) end | (bit1 a) (bit0 b) H₁ H₂ := begin rewrite [succ_bit0 at H₁, lt_bit1_bit1_eq_lt at H₁, lt_bit1_bit0_eq_lt], exact H₁ end | (bit1 a) (bit1 b) H₁ H₂ := begin rewrite [succ_bit1 at H₁, lt_bit1_bit0_eq_lt at H₁, lt_bit1_bit1_eq_lt], apply (lt_of_lt_succ_of_ne H₁ (ne_of_bit1_ne_bit1 H₂)) end theorem lt_trans : ∀ {a b c : pos_num}, a < b → b < c → a < c | one b (bit0 c) H₁ H₂ := rfl | one b (bit1 c) H₁ H₂ := rfl | a (bit0 b) one H₁ H₂ := absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₂ | a (bit1 b) one H₁ H₂ := absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₂ | (bit0 a) (bit0 b) (bit0 c) H₁ H₂ := begin rewrite lt_bit0_bit0_eq_lt at *, apply (lt_trans H₁ H₂) end | (bit0 a) (bit0 b) (bit1 c) H₁ H₂ := begin rewrite [lt_bit0_bit1_eq_lt_succ at *, lt_bit0_bit0_eq_lt at H₁], apply (lt_trans H₁ H₂) end | (bit0 a) (bit1 b) (bit0 c) H₁ H₂ := begin rewrite [lt_bit0_bit1_eq_lt_succ at H₁, lt_bit1_bit0_eq_lt at H₂, lt_bit0_bit0_eq_lt], apply (@by_cases (a = b)), begin intro H, rewrite -H at H₂, exact H₂ end, begin intro H, apply (lt_trans (lt_of_lt_succ_of_ne H₁ H) H₂) end end | (bit0 a) (bit1 b) (bit1 c) H₁ H₂ := begin rewrite [lt_bit0_bit1_eq_lt_succ at *, lt_bit1_bit1_eq_lt at H₂], apply (lt_trans H₁ (lt_succ_succ H₂)) end | (bit1 a) (bit0 b) (bit0 c) H₁ H₂ := begin rewrite [lt_bit0_bit0_eq_lt at H₂, lt_bit1_bit0_eq_lt at *], apply (lt_trans H₁ H₂) end | (bit1 a) (bit0 b) (bit1 c) H₁ H₂ := begin rewrite [lt_bit1_bit0_eq_lt at H₁, lt_bit0_bit1_eq_lt_succ at H₂, lt_bit1_bit1_eq_lt], apply (@by_cases (b = c)), begin intro H, rewrite H at H₁, exact H₁ end, begin intro H, apply (lt_trans H₁ (lt_of_lt_succ_of_ne H₂ H)) end end | (bit1 a) (bit1 b) (bit0 c) H₁ H₂ := begin rewrite [lt_bit1_bit1_eq_lt at H₁, lt_bit1_bit0_eq_lt at H₂, lt_bit1_bit0_eq_lt], apply (lt_trans H₁ H₂) end | (bit1 a) (bit1 b) (bit1 c) H₁ H₂ := begin rewrite lt_bit1_bit1_eq_lt at *, apply (lt_trans H₁ H₂) end theorem lt_antisymm : ∀ {a b : pos_num}, a < b → b ≮ a | one one H := rfl | one (bit0 b) H := rfl | one (bit1 b) H := rfl | (bit0 a) one H := absurd H ff_ne_tt | (bit0 a) (bit0 b) H := begin rewrite lt_bit0_bit0_eq_lt at *, apply (lt_antisymm H) end | (bit0 a) (bit1 b) H := begin rewrite lt_bit1_bit0_eq_lt, rewrite lt_bit0_bit1_eq_lt_succ at H, have H₁ : succ b ≮ a, from lt_antisymm H, apply eq_ff_of_ne_tt, intro H₂, apply (@by_cases (succ b = a)), show succ b = a → false, begin intro Hp, rewrite -Hp at H, apply (absurd_of_eq_ff_of_eq_tt (lt_irrefl (succ b)) H) end, show succ b ≠ a → false, begin intro Hn, have H₃ : succ b < succ a, from lt_succ_succ H₂, have H₄ : succ b < a, from lt_of_lt_succ_of_ne H₃ Hn, apply (absurd_of_eq_ff_of_eq_tt H₁ H₄) end, end | (bit1 a) one H := absurd H ff_ne_tt | (bit1 a) (bit0 b) H := begin rewrite lt_bit0_bit1_eq_lt_succ, rewrite lt_bit1_bit0_eq_lt at H, have H₁ : lt b a = ff, from lt_antisymm H, apply eq_ff_of_ne_tt, intro H₂, apply (@by_cases (b = a)), show b = a → false, begin intro Hp, rewrite -Hp at H, apply (absurd_of_eq_ff_of_eq_tt (lt_irrefl b) H) end, show b ≠ a → false, begin intro Hn, have H₃ : b < a, from lt_of_lt_succ_of_ne H₂ Hn, apply (absurd_of_eq_ff_of_eq_tt H₁ H₃) end, end | (bit1 a) (bit1 b) H := begin rewrite lt_bit1_bit1_eq_lt at *, apply (lt_antisymm H) end local notation a ≤ b := (le a b = tt) theorem le_refl : ∀ a : pos_num, a ≤ a := lt_base theorem le_eq_lt_succ {a b : pos_num} : le a b = lt a (succ b) := rfl theorem not_lt_of_le : ∀ {a b : pos_num}, a ≤ b → b < a → false | one one H₁ H₂ := absurd H₂ ff_ne_tt | one (bit0 b) H₁ H₂ := absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₂ | one (bit1 b) H₁ H₂ := absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₂ | (bit0 a) one H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_one at H₁, lt_bit0_bit0_eq_lt at H₁], apply (absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₁) end | (bit0 a) (bit0 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_bit0 at H₁, lt_bit0_bit1_eq_lt_succ at H₁], rewrite [lt_bit0_bit0_eq_lt at H₂], apply (not_lt_of_le H₁ H₂) end | (bit0 a) (bit1 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_bit1 at H₁, lt_bit0_bit0_eq_lt at H₁], rewrite [lt_bit1_bit0_eq_lt at H₂], apply (not_lt_of_le H₁ H₂) end | (bit1 a) one H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_one at H₁, lt_bit1_bit0_eq_lt at H₁], apply (absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₁) end | (bit1 a) (bit0 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_bit0 at H₁, lt_bit1_bit1_eq_lt at H₁], rewrite lt_bit0_bit1_eq_lt_succ at H₂, have H₃ : a < succ b, from lt_step H₁, apply (@by_cases (b = a)), begin intro Hba, rewrite -Hba at H₁, apply (absurd_of_eq_ff_of_eq_tt (lt_irrefl b) H₁) end, begin intro Hnba, have H₄ : b < a, from lt_of_lt_succ_of_ne H₂ Hnba, apply (not_lt_of_le H₃ H₄) end end | (bit1 a) (bit1 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_bit1 at H₁, lt_bit1_bit0_eq_lt at H₁], rewrite [lt_bit1_bit1_eq_lt at H₂], apply (not_lt_of_le H₁ H₂) end theorem le_antisymm : ∀ {a b : pos_num}, a ≤ b → b ≤ a → a = b | one one H₁ H₂ := rfl | one (bit0 b) H₁ H₂ := by apply (absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff b) H₂) | one (bit1 b) H₁ H₂ := by apply (absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff b) H₂) | (bit0 a) one H₁ H₂ := by apply (absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff a) H₁) | (bit0 a) (bit0 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at *, succ_bit0 at *, lt_bit0_bit1_eq_lt_succ at *], have H : a = b, from le_antisymm H₁ H₂, rewrite H end | (bit0 a) (bit1 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at *, succ_bit1 at H₁, succ_bit0 at H₂], rewrite [lt_bit0_bit0_eq_lt at H₁, lt_bit1_bit1_eq_lt at H₂], apply (false.rec _ (not_lt_of_le H₁ H₂)) end | (bit1 a) one H₁ H₂ := by apply (absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff a) H₁) | (bit1 a) (bit0 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at *, succ_bit0 at H₁, succ_bit1 at H₂], rewrite [lt_bit1_bit1_eq_lt at H₁, lt_bit0_bit0_eq_lt at H₂], apply (false.rec _ (not_lt_of_le H₂ H₁)) end | (bit1 a) (bit1 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at *, succ_bit1 at *, lt_bit1_bit0_eq_lt at *], have H : a = b, from le_antisymm H₁ H₂, rewrite H end theorem le_trans {a b c : pos_num} : a ≤ b → b ≤ c → a ≤ c := begin intros [H₁, H₂], rewrite [le_eq_lt_succ at *], apply (@by_cases (a = b)), begin intro Hab, rewrite Hab, exact H₂ end, begin intro Hnab, have Haltb : a < b, from lt_of_lt_succ_of_ne H₁ Hnab, apply (lt_trans Haltb H₂) end, end end pos_num